Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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/Sema/Overload.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/DeclObjC.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/TargetInfo.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/Optional.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallString.h"
35#include <algorithm>
36#include <cstdlib>
37
38using namespace clang;
39using namespace sema;
40
41static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
44 });
45}
46
47/// A convenience routine for creating a decayed reference to a function.
48static ExprResult
49CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 const Expr *Base, bool HadMultipleCandidates,
51 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54 return ExprError();
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
57 // called on both.
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60 // being used.
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62 return ExprError();
63 DeclRefExpr *DRE = new (S.Context)
64 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
65 if (HadMultipleCandidates)
66 DRE->setHadMultipleCandidates(true);
67
68 S.MarkDeclRefReferenced(DRE, Base);
69 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
70 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
71 S.ResolveExceptionSpec(Loc, FPT);
72 DRE->setType(Fn->getType());
73 }
74 }
75 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
76 CK_FunctionToPointerDecay);
77}
78
79static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
82 bool CStyle,
83 bool AllowObjCWritebackConversion);
84
85static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
86 QualType &ToType,
87 bool InOverloadResolution,
88 StandardConversionSequence &SCS,
89 bool CStyle);
90static OverloadingResult
91IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
92 UserDefinedConversionSequence& User,
93 OverloadCandidateSet& Conversions,
94 bool AllowExplicit,
95 bool AllowObjCConversionOnExplicit);
96
97
98static ImplicitConversionSequence::CompareKind
99CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
100 const StandardConversionSequence& SCS1,
101 const StandardConversionSequence& SCS2);
102
103static ImplicitConversionSequence::CompareKind
104CompareQualificationConversions(Sema &S,
105 const StandardConversionSequence& SCS1,
106 const StandardConversionSequence& SCS2);
107
108static ImplicitConversionSequence::CompareKind
109CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
110 const StandardConversionSequence& SCS1,
111 const StandardConversionSequence& SCS2);
112
113/// GetConversionRank - Retrieve the implicit conversion rank
114/// corresponding to the given implicit conversion kind.
115ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
116 static const ImplicitConversionRank
117 Rank[(int)ICK_Num_Conversion_Kinds] = {
118 ICR_Exact_Match,
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
124 ICR_Promotion,
125 ICR_Promotion,
126 ICR_Promotion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_OCL_Scalar_Widening,
138 ICR_Complex_Real_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Writeback_Conversion,
142 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
143 // it was omitted by the patch that added
144 // ICK_Zero_Event_Conversion
145 ICR_C_Conversion,
146 ICR_C_Conversion_Extension
147 };
148 return Rank[(int)Kind];
149}
150
151/// GetImplicitConversionName - Return the name of this kind of
152/// implicit conversion.
153static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
155 "No conversion",
156 "Lvalue-to-rvalue",
157 "Array-to-pointer",
158 "Function-to-pointer",
159 "Function pointer conversion",
160 "Qualification",
161 "Integral promotion",
162 "Floating point promotion",
163 "Complex promotion",
164 "Integral conversion",
165 "Floating conversion",
166 "Complex conversion",
167 "Floating-integral conversion",
168 "Pointer conversion",
169 "Pointer-to-member conversion",
170 "Boolean conversion",
171 "Compatible-types conversion",
172 "Derived-to-base conversion",
173 "Vector conversion",
174 "Vector splat",
175 "Complex-real conversion",
176 "Block Pointer conversion",
177 "Transparent Union Conversion",
178 "Writeback conversion",
179 "OpenCL Zero Event Conversion",
180 "C specific type conversion",
181 "Incompatible pointer conversion"
182 };
183 return Name[Kind];
184}
185
186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
192 DeprecatedStringLiteralToCharPtr = false;
193 QualificationIncludesObjCLifetime = false;
194 ReferenceBinding = false;
195 DirectBinding = false;
196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
200 ObjCLifetimeConversionBinding = false;
201 CopyConstructor = nullptr;
202}
203
204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
220/// used as part of the ranking of standard conversion sequences
221/// (C++ 13.3.3.2p4).
222bool StandardConversionSequence::isPointerConversionToBool() const {
223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
227 if (getToType(1)->isBooleanType() &&
228 (getFromType()->isPointerType() ||
229 getFromType()->isMemberPointerType() ||
230 getFromType()->isObjCObjectPointerType() ||
231 getFromType()->isBlockPointerType() ||
232 getFromType()->isNullPtrType() ||
233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234 return true;
235
236 return false;
237}
238
239/// isPointerConversionToVoidPointer - Determines whether this
240/// conversion is a conversion of a pointer to a void pointer. This is
241/// used as part of the ranking of standard conversion sequences (C++
242/// 13.3.3.2p4).
243bool
244StandardConversionSequence::
245isPointerConversionToVoidPointer(ASTContext& Context) const {
246 QualType FromType = getFromType();
247 QualType ToType = getToType(1);
248
249 // Note that FromType has not necessarily been transformed by the
250 // array-to-pointer implicit conversion, so check for its presence
251 // and redo the conversion to get a pointer.
252 if (First == ICK_Array_To_Pointer)
253 FromType = Context.getArrayDecayedType(FromType);
254
255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
257 return ToPtrType->getPointeeType()->isVoidType();
258
259 return false;
260}
261
262/// Skip any implicit casts which could be either part of a narrowing conversion
263/// or after one in an implicit conversion.
264static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
265 const Expr *Converted) {
266 // We can have cleanups wrapping the converted expression; these need to be
267 // preserved so that destructors run if necessary.
268 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
269 Expr *Inner =
270 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
271 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
272 EWC->getObjects());
273 }
274
275 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
276 switch (ICE->getCastKind()) {
277 case CK_NoOp:
278 case CK_IntegralCast:
279 case CK_IntegralToBoolean:
280 case CK_IntegralToFloating:
281 case CK_BooleanToSignedIntegral:
282 case CK_FloatingToIntegral:
283 case CK_FloatingToBoolean:
284 case CK_FloatingCast:
285 Converted = ICE->getSubExpr();
286 continue;
287
288 default:
289 return Converted;
290 }
291 }
292
293 return Converted;
294}
295
296/// Check if this standard conversion sequence represents a narrowing
297/// conversion, according to C++11 [dcl.init.list]p7.
298///
299/// \param Ctx The AST context.
300/// \param Converted The result of applying this standard conversion sequence.
301/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
302/// value of the expression prior to the narrowing conversion.
303/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
304/// type of the expression prior to the narrowing conversion.
305/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
306/// from floating point types to integral types should be ignored.
307NarrowingKind StandardConversionSequence::getNarrowingKind(
308 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
309 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
310 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")((Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"
) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 310, __PRETTY_FUNCTION__))
;
311
312 // C++11 [dcl.init.list]p7:
313 // A narrowing conversion is an implicit conversion ...
314 QualType FromType = getToType(0);
315 QualType ToType = getToType(1);
316
317 // A conversion to an enumeration type is narrowing if the conversion to
318 // the underlying type is narrowing. This only arises for expressions of
319 // the form 'Enum{init}'.
320 if (auto *ET = ToType->getAs<EnumType>())
321 ToType = ET->getDecl()->getIntegerType();
322
323 switch (Second) {
324 // 'bool' is an integral type; dispatch to the right place to handle it.
325 case ICK_Boolean_Conversion:
326 if (FromType->isRealFloatingType())
327 goto FloatingIntegralConversion;
328 if (FromType->isIntegralOrUnscopedEnumerationType())
329 goto IntegralConversion;
330 // Boolean conversions can be from pointers and pointers to members
331 // [conv.bool], and those aren't considered narrowing conversions.
332 return NK_Not_Narrowing;
333
334 // -- from a floating-point type to an integer type, or
335 //
336 // -- from an integer type or unscoped enumeration type to a floating-point
337 // type, except where the source is a constant expression and the actual
338 // value after conversion will fit into the target type and will produce
339 // the original value when converted back to the original type, or
340 case ICK_Floating_Integral:
341 FloatingIntegralConversion:
342 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
343 return NK_Type_Narrowing;
344 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
345 ToType->isRealFloatingType()) {
346 if (IgnoreFloatToIntegralConversion)
347 return NK_Not_Narrowing;
348 llvm::APSInt IntConstantValue;
349 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
350 assert(Initializer && "Unknown conversion expression")((Initializer && "Unknown conversion expression") ? static_cast
<void> (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 350, __PRETTY_FUNCTION__))
;
351
352 // If it's value-dependent, we can't tell whether it's narrowing.
353 if (Initializer->isValueDependent())
354 return NK_Dependent_Narrowing;
355
356 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
357 // Convert the integer to the floating type.
358 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
359 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
360 llvm::APFloat::rmNearestTiesToEven);
361 // And back.
362 llvm::APSInt ConvertedValue = IntConstantValue;
363 bool ignored;
364 Result.convertToInteger(ConvertedValue,
365 llvm::APFloat::rmTowardZero, &ignored);
366 // If the resulting value is different, this was a narrowing conversion.
367 if (IntConstantValue != ConvertedValue) {
368 ConstantValue = APValue(IntConstantValue);
369 ConstantType = Initializer->getType();
370 return NK_Constant_Narrowing;
371 }
372 } else {
373 // Variables are always narrowings.
374 return NK_Variable_Narrowing;
375 }
376 }
377 return NK_Not_Narrowing;
378
379 // -- from long double to double or float, or from double to float, except
380 // where the source is a constant expression and the actual value after
381 // conversion is within the range of values that can be represented (even
382 // if it cannot be represented exactly), or
383 case ICK_Floating_Conversion:
384 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
385 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
386 // FromType is larger than ToType.
387 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
388
389 // If it's value-dependent, we can't tell whether it's narrowing.
390 if (Initializer->isValueDependent())
391 return NK_Dependent_Narrowing;
392
393 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
394 // Constant!
395 assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail
("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 395, __PRETTY_FUNCTION__))
;
396 llvm::APFloat FloatVal = ConstantValue.getFloat();
397 // Convert the source value into the target type.
398 bool ignored;
399 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
400 Ctx.getFloatTypeSemantics(ToType),
401 llvm::APFloat::rmNearestTiesToEven, &ignored);
402 // If there was no overflow, the source value is within the range of
403 // values that can be represented.
404 if (ConvertStatus & llvm::APFloat::opOverflow) {
405 ConstantType = Initializer->getType();
406 return NK_Constant_Narrowing;
407 }
408 } else {
409 return NK_Variable_Narrowing;
410 }
411 }
412 return NK_Not_Narrowing;
413
414 // -- from an integer type or unscoped enumeration type to an integer type
415 // that cannot represent all the values of the original type, except where
416 // the source is a constant expression and the actual value after
417 // conversion will fit into the target type and will produce the original
418 // value when converted back to the original type.
419 case ICK_Integral_Conversion:
420 IntegralConversion: {
421 assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 421, __PRETTY_FUNCTION__))
;
422 assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 422, __PRETTY_FUNCTION__))
;
423 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
424 const unsigned FromWidth = Ctx.getIntWidth(FromType);
425 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
426 const unsigned ToWidth = Ctx.getIntWidth(ToType);
427
428 if (FromWidth > ToWidth ||
429 (FromWidth == ToWidth && FromSigned != ToSigned) ||
430 (FromSigned && !ToSigned)) {
431 // Not all values of FromType can be represented in ToType.
432 llvm::APSInt InitializerValue;
433 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
434
435 // If it's value-dependent, we can't tell whether it's narrowing.
436 if (Initializer->isValueDependent())
437 return NK_Dependent_Narrowing;
438
439 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
440 // Such conversions on variables are always narrowing.
441 return NK_Variable_Narrowing;
442 }
443 bool Narrowing = false;
444 if (FromWidth < ToWidth) {
445 // Negative -> unsigned is narrowing. Otherwise, more bits is never
446 // narrowing.
447 if (InitializerValue.isSigned() && InitializerValue.isNegative())
448 Narrowing = true;
449 } else {
450 // Add a bit to the InitializerValue so we don't have to worry about
451 // signed vs. unsigned comparisons.
452 InitializerValue = InitializerValue.extend(
453 InitializerValue.getBitWidth() + 1);
454 // Convert the initializer to and from the target width and signed-ness.
455 llvm::APSInt ConvertedValue = InitializerValue;
456 ConvertedValue = ConvertedValue.trunc(ToWidth);
457 ConvertedValue.setIsSigned(ToSigned);
458 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
459 ConvertedValue.setIsSigned(InitializerValue.isSigned());
460 // If the result is different, this was a narrowing conversion.
461 if (ConvertedValue != InitializerValue)
462 Narrowing = true;
463 }
464 if (Narrowing) {
465 ConstantType = Initializer->getType();
466 ConstantValue = APValue(InitializerValue);
467 return NK_Constant_Narrowing;
468 }
469 }
470 return NK_Not_Narrowing;
471 }
472
473 default:
474 // Other kinds of conversions are not narrowings.
475 return NK_Not_Narrowing;
476 }
477}
478
479/// dump - Print this standard conversion sequence to standard
480/// error. Useful for debugging overloading issues.
481LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
482 raw_ostream &OS = llvm::errs();
483 bool PrintedSomething = false;
484 if (First != ICK_Identity) {
485 OS << GetImplicitConversionName(First);
486 PrintedSomething = true;
487 }
488
489 if (Second != ICK_Identity) {
490 if (PrintedSomething) {
491 OS << " -> ";
492 }
493 OS << GetImplicitConversionName(Second);
494
495 if (CopyConstructor) {
496 OS << " (by copy constructor)";
497 } else if (DirectBinding) {
498 OS << " (direct reference binding)";
499 } else if (ReferenceBinding) {
500 OS << " (reference binding)";
501 }
502 PrintedSomething = true;
503 }
504
505 if (Third != ICK_Identity) {
506 if (PrintedSomething) {
507 OS << " -> ";
508 }
509 OS << GetImplicitConversionName(Third);
510 PrintedSomething = true;
511 }
512
513 if (!PrintedSomething) {
514 OS << "No conversions required";
515 }
516}
517
518/// dump - Print this user-defined conversion sequence to standard
519/// error. Useful for debugging overloading issues.
520void UserDefinedConversionSequence::dump() const {
521 raw_ostream &OS = llvm::errs();
522 if (Before.First || Before.Second || Before.Third) {
523 Before.dump();
524 OS << " -> ";
525 }
526 if (ConversionFunction)
527 OS << '\'' << *ConversionFunction << '\'';
528 else
529 OS << "aggregate initialization";
530 if (After.First || After.Second || After.Third) {
531 OS << " -> ";
532 After.dump();
533 }
534}
535
536/// dump - Print this implicit conversion sequence to standard
537/// error. Useful for debugging overloading issues.
538void ImplicitConversionSequence::dump() const {
539 raw_ostream &OS = llvm::errs();
540 if (isStdInitializerListElement())
541 OS << "Worst std::initializer_list element conversion: ";
542 switch (ConversionKind) {
543 case StandardConversion:
544 OS << "Standard conversion: ";
545 Standard.dump();
546 break;
547 case UserDefinedConversion:
548 OS << "User-defined conversion: ";
549 UserDefined.dump();
550 break;
551 case EllipsisConversion:
552 OS << "Ellipsis conversion";
553 break;
554 case AmbiguousConversion:
555 OS << "Ambiguous conversion";
556 break;
557 case BadConversion:
558 OS << "Bad conversion";
559 break;
560 }
561
562 OS << "\n";
563}
564
565void AmbiguousConversionSequence::construct() {
566 new (&conversions()) ConversionSet();
567}
568
569void AmbiguousConversionSequence::destruct() {
570 conversions().~ConversionSet();
571}
572
573void
574AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
575 FromTypePtr = O.FromTypePtr;
576 ToTypePtr = O.ToTypePtr;
577 new (&conversions()) ConversionSet(O.conversions());
578}
579
580namespace {
581 // Structure used by DeductionFailureInfo to store
582 // template argument information.
583 struct DFIArguments {
584 TemplateArgument FirstArg;
585 TemplateArgument SecondArg;
586 };
587 // Structure used by DeductionFailureInfo to store
588 // template parameter and template argument information.
589 struct DFIParamWithArguments : DFIArguments {
590 TemplateParameter Param;
591 };
592 // Structure used by DeductionFailureInfo to store template argument
593 // information and the index of the problematic call argument.
594 struct DFIDeducedMismatchArgs : DFIArguments {
595 TemplateArgumentList *TemplateArgs;
596 unsigned CallArgIndex;
597 };
598 // Structure used by DeductionFailureInfo to store information about
599 // unsatisfied constraints.
600 struct CNSInfo {
601 TemplateArgumentList *TemplateArgs;
602 ConstraintSatisfaction Satisfaction;
603 };
604}
605
606/// Convert from Sema's representation of template deduction information
607/// to the form used in overload-candidate information.
608DeductionFailureInfo
609clang::MakeDeductionFailureInfo(ASTContext &Context,
610 Sema::TemplateDeductionResult TDK,
611 TemplateDeductionInfo &Info) {
612 DeductionFailureInfo Result;
613 Result.Result = static_cast<unsigned>(TDK);
614 Result.HasDiagnostic = false;
615 switch (TDK) {
616 case Sema::TDK_Invalid:
617 case Sema::TDK_InstantiationDepth:
618 case Sema::TDK_TooManyArguments:
619 case Sema::TDK_TooFewArguments:
620 case Sema::TDK_MiscellaneousDeductionFailure:
621 case Sema::TDK_CUDATargetMismatch:
622 Result.Data = nullptr;
623 break;
624
625 case Sema::TDK_Incomplete:
626 case Sema::TDK_InvalidExplicitArguments:
627 Result.Data = Info.Param.getOpaqueValue();
628 break;
629
630 case Sema::TDK_DeducedMismatch:
631 case Sema::TDK_DeducedMismatchNested: {
632 // FIXME: Should allocate from normal heap so that we can free this later.
633 auto *Saved = new (Context) DFIDeducedMismatchArgs;
634 Saved->FirstArg = Info.FirstArg;
635 Saved->SecondArg = Info.SecondArg;
636 Saved->TemplateArgs = Info.take();
637 Saved->CallArgIndex = Info.CallArgIndex;
638 Result.Data = Saved;
639 break;
640 }
641
642 case Sema::TDK_NonDeducedMismatch: {
643 // FIXME: Should allocate from normal heap so that we can free this later.
644 DFIArguments *Saved = new (Context) DFIArguments;
645 Saved->FirstArg = Info.FirstArg;
646 Saved->SecondArg = Info.SecondArg;
647 Result.Data = Saved;
648 break;
649 }
650
651 case Sema::TDK_IncompletePack:
652 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
653 case Sema::TDK_Inconsistent:
654 case Sema::TDK_Underqualified: {
655 // FIXME: Should allocate from normal heap so that we can free this later.
656 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
657 Saved->Param = Info.Param;
658 Saved->FirstArg = Info.FirstArg;
659 Saved->SecondArg = Info.SecondArg;
660 Result.Data = Saved;
661 break;
662 }
663
664 case Sema::TDK_SubstitutionFailure:
665 Result.Data = Info.take();
666 if (Info.hasSFINAEDiagnostic()) {
667 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
668 SourceLocation(), PartialDiagnostic::NullDiagnostic());
669 Info.takeSFINAEDiagnostic(*Diag);
670 Result.HasDiagnostic = true;
671 }
672 break;
673
674 case Sema::TDK_ConstraintsNotSatisfied: {
675 CNSInfo *Saved = new (Context) CNSInfo;
676 Saved->TemplateArgs = Info.take();
677 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
678 Result.Data = Saved;
679 break;
680 }
681
682 case Sema::TDK_Success:
683 case Sema::TDK_NonDependentConversionFailure:
684 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 684)
;
685 }
686
687 return Result;
688}
689
690void DeductionFailureInfo::Destroy() {
691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
692 case Sema::TDK_Success:
693 case Sema::TDK_Invalid:
694 case Sema::TDK_InstantiationDepth:
695 case Sema::TDK_Incomplete:
696 case Sema::TDK_TooManyArguments:
697 case Sema::TDK_TooFewArguments:
698 case Sema::TDK_InvalidExplicitArguments:
699 case Sema::TDK_CUDATargetMismatch:
700 case Sema::TDK_NonDependentConversionFailure:
701 break;
702
703 case Sema::TDK_IncompletePack:
704 case Sema::TDK_Inconsistent:
705 case Sema::TDK_Underqualified:
706 case Sema::TDK_DeducedMismatch:
707 case Sema::TDK_DeducedMismatchNested:
708 case Sema::TDK_NonDeducedMismatch:
709 // FIXME: Destroy the data?
710 Data = nullptr;
711 break;
712
713 case Sema::TDK_SubstitutionFailure:
714 // FIXME: Destroy the template argument list?
715 Data = nullptr;
716 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
717 Diag->~PartialDiagnosticAt();
718 HasDiagnostic = false;
719 }
720 break;
721
722 case Sema::TDK_ConstraintsNotSatisfied:
723 // FIXME: Destroy the template argument list?
724 Data = nullptr;
725 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
726 Diag->~PartialDiagnosticAt();
727 HasDiagnostic = false;
728 }
729 break;
730
731 // Unhandled
732 case Sema::TDK_MiscellaneousDeductionFailure:
733 break;
734 }
735}
736
737PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
738 if (HasDiagnostic)
739 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
740 return nullptr;
741}
742
743TemplateParameter DeductionFailureInfo::getTemplateParameter() {
744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745 case Sema::TDK_Success:
746 case Sema::TDK_Invalid:
747 case Sema::TDK_InstantiationDepth:
748 case Sema::TDK_TooManyArguments:
749 case Sema::TDK_TooFewArguments:
750 case Sema::TDK_SubstitutionFailure:
751 case Sema::TDK_DeducedMismatch:
752 case Sema::TDK_DeducedMismatchNested:
753 case Sema::TDK_NonDeducedMismatch:
754 case Sema::TDK_CUDATargetMismatch:
755 case Sema::TDK_NonDependentConversionFailure:
756 case Sema::TDK_ConstraintsNotSatisfied:
757 return TemplateParameter();
758
759 case Sema::TDK_Incomplete:
760 case Sema::TDK_InvalidExplicitArguments:
761 return TemplateParameter::getFromOpaqueValue(Data);
762
763 case Sema::TDK_IncompletePack:
764 case Sema::TDK_Inconsistent:
765 case Sema::TDK_Underqualified:
766 return static_cast<DFIParamWithArguments*>(Data)->Param;
767
768 // Unhandled
769 case Sema::TDK_MiscellaneousDeductionFailure:
770 break;
771 }
772
773 return TemplateParameter();
774}
775
776TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
777 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
778 case Sema::TDK_Success:
779 case Sema::TDK_Invalid:
780 case Sema::TDK_InstantiationDepth:
781 case Sema::TDK_TooManyArguments:
782 case Sema::TDK_TooFewArguments:
783 case Sema::TDK_Incomplete:
784 case Sema::TDK_IncompletePack:
785 case Sema::TDK_InvalidExplicitArguments:
786 case Sema::TDK_Inconsistent:
787 case Sema::TDK_Underqualified:
788 case Sema::TDK_NonDeducedMismatch:
789 case Sema::TDK_CUDATargetMismatch:
790 case Sema::TDK_NonDependentConversionFailure:
791 return nullptr;
792
793 case Sema::TDK_DeducedMismatch:
794 case Sema::TDK_DeducedMismatchNested:
795 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
796
797 case Sema::TDK_SubstitutionFailure:
798 return static_cast<TemplateArgumentList*>(Data);
799
800 case Sema::TDK_ConstraintsNotSatisfied:
801 return static_cast<CNSInfo*>(Data)->TemplateArgs;
802
803 // Unhandled
804 case Sema::TDK_MiscellaneousDeductionFailure:
805 break;
806 }
807
808 return nullptr;
809}
810
811const TemplateArgument *DeductionFailureInfo::getFirstArg() {
812 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
813 case Sema::TDK_Success:
814 case Sema::TDK_Invalid:
815 case Sema::TDK_InstantiationDepth:
816 case Sema::TDK_Incomplete:
817 case Sema::TDK_TooManyArguments:
818 case Sema::TDK_TooFewArguments:
819 case Sema::TDK_InvalidExplicitArguments:
820 case Sema::TDK_SubstitutionFailure:
821 case Sema::TDK_CUDATargetMismatch:
822 case Sema::TDK_NonDependentConversionFailure:
823 case Sema::TDK_ConstraintsNotSatisfied:
824 return nullptr;
825
826 case Sema::TDK_IncompletePack:
827 case Sema::TDK_Inconsistent:
828 case Sema::TDK_Underqualified:
829 case Sema::TDK_DeducedMismatch:
830 case Sema::TDK_DeducedMismatchNested:
831 case Sema::TDK_NonDeducedMismatch:
832 return &static_cast<DFIArguments*>(Data)->FirstArg;
833
834 // Unhandled
835 case Sema::TDK_MiscellaneousDeductionFailure:
836 break;
837 }
838
839 return nullptr;
840}
841
842const TemplateArgument *DeductionFailureInfo::getSecondArg() {
843 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
844 case Sema::TDK_Success:
845 case Sema::TDK_Invalid:
846 case Sema::TDK_InstantiationDepth:
847 case Sema::TDK_Incomplete:
848 case Sema::TDK_IncompletePack:
849 case Sema::TDK_TooManyArguments:
850 case Sema::TDK_TooFewArguments:
851 case Sema::TDK_InvalidExplicitArguments:
852 case Sema::TDK_SubstitutionFailure:
853 case Sema::TDK_CUDATargetMismatch:
854 case Sema::TDK_NonDependentConversionFailure:
855 case Sema::TDK_ConstraintsNotSatisfied:
856 return nullptr;
857
858 case Sema::TDK_Inconsistent:
859 case Sema::TDK_Underqualified:
860 case Sema::TDK_DeducedMismatch:
861 case Sema::TDK_DeducedMismatchNested:
862 case Sema::TDK_NonDeducedMismatch:
863 return &static_cast<DFIArguments*>(Data)->SecondArg;
864
865 // Unhandled
866 case Sema::TDK_MiscellaneousDeductionFailure:
867 break;
868 }
869
870 return nullptr;
871}
872
873llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
874 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
875 case Sema::TDK_DeducedMismatch:
876 case Sema::TDK_DeducedMismatchNested:
877 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
878
879 default:
880 return llvm::None;
881 }
882}
883
884bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
885 OverloadedOperatorKind Op) {
886 if (!AllowRewrittenCandidates)
887 return false;
888 return Op == OO_EqualEqual || Op == OO_Spaceship;
889}
890
891bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
892 ASTContext &Ctx, const FunctionDecl *FD) {
893 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
894 return false;
895 // Don't bother adding a reversed candidate that can never be a better
896 // match than the non-reversed version.
897 return FD->getNumParams() != 2 ||
898 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
899 FD->getParamDecl(1)->getType()) ||
900 FD->hasAttr<EnableIfAttr>();
901}
902
903void OverloadCandidateSet::destroyCandidates() {
904 for (iterator i = begin(), e = end(); i != e; ++i) {
905 for (auto &C : i->Conversions)
906 C.~ImplicitConversionSequence();
907 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
908 i->DeductionFailure.Destroy();
909 }
910}
911
912void OverloadCandidateSet::clear(CandidateSetKind CSK) {
913 destroyCandidates();
914 SlabAllocator.Reset();
915 NumInlineBytesUsed = 0;
916 Candidates.clear();
917 Functions.clear();
918 Kind = CSK;
919}
920
921namespace {
922 class UnbridgedCastsSet {
923 struct Entry {
924 Expr **Addr;
925 Expr *Saved;
926 };
927 SmallVector<Entry, 2> Entries;
928
929 public:
930 void save(Sema &S, Expr *&E) {
931 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 931, __PRETTY_FUNCTION__))
;
932 Entry entry = { &E, E };
933 Entries.push_back(entry);
934 E = S.stripARCUnbridgedCast(E);
935 }
936
937 void restore() {
938 for (SmallVectorImpl<Entry>::iterator
939 i = Entries.begin(), e = Entries.end(); i != e; ++i)
940 *i->Addr = i->Saved;
941 }
942 };
943}
944
945/// checkPlaceholderForOverload - Do any interesting placeholder-like
946/// preprocessing on the given expression.
947///
948/// \param unbridgedCasts a collection to which to add unbridged casts;
949/// without this, they will be immediately diagnosed as errors
950///
951/// Return true on unrecoverable error.
952static bool
953checkPlaceholderForOverload(Sema &S, Expr *&E,
954 UnbridgedCastsSet *unbridgedCasts = nullptr) {
955 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
956 // We can't handle overloaded expressions here because overload
957 // resolution might reasonably tweak them.
958 if (placeholder->getKind() == BuiltinType::Overload) return false;
959
960 // If the context potentially accepts unbridged ARC casts, strip
961 // the unbridged cast and add it to the collection for later restoration.
962 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
963 unbridgedCasts) {
964 unbridgedCasts->save(S, E);
965 return false;
966 }
967
968 // Go ahead and check everything else.
969 ExprResult result = S.CheckPlaceholderExpr(E);
970 if (result.isInvalid())
971 return true;
972
973 E = result.get();
974 return false;
975 }
976
977 // Nothing to do.
978 return false;
979}
980
981/// checkArgPlaceholdersForOverload - Check a set of call operands for
982/// placeholders.
983static bool checkArgPlaceholdersForOverload(Sema &S,
984 MultiExprArg Args,
985 UnbridgedCastsSet &unbridged) {
986 for (unsigned i = 0, e = Args.size(); i != e; ++i)
987 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
988 return true;
989
990 return false;
991}
992
993/// Determine whether the given New declaration is an overload of the
994/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
995/// New and Old cannot be overloaded, e.g., if New has the same signature as
996/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
997/// functions (or function templates) at all. When it does return Ovl_Match or
998/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
999/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1000/// declaration.
1001///
1002/// Example: Given the following input:
1003///
1004/// void f(int, float); // #1
1005/// void f(int, int); // #2
1006/// int f(int, int); // #3
1007///
1008/// When we process #1, there is no previous declaration of "f", so IsOverload
1009/// will not be used.
1010///
1011/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1012/// the parameter types, we see that #1 and #2 are overloaded (since they have
1013/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1014/// unchanged.
1015///
1016/// When we process #3, Old is an overload set containing #1 and #2. We compare
1017/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1018/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1019/// functions are not part of the signature), IsOverload returns Ovl_Match and
1020/// MatchedDecl will be set to point to the FunctionDecl for #2.
1021///
1022/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1023/// by a using declaration. The rules for whether to hide shadow declarations
1024/// ignore some properties which otherwise figure into a function template's
1025/// signature.
1026Sema::OverloadKind
1027Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1028 NamedDecl *&Match, bool NewIsUsingDecl) {
1029 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1030 I != E; ++I) {
1031 NamedDecl *OldD = *I;
1032
1033 bool OldIsUsingDecl = false;
1034 if (isa<UsingShadowDecl>(OldD)) {
1035 OldIsUsingDecl = true;
1036
1037 // We can always introduce two using declarations into the same
1038 // context, even if they have identical signatures.
1039 if (NewIsUsingDecl) continue;
1040
1041 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1042 }
1043
1044 // A using-declaration does not conflict with another declaration
1045 // if one of them is hidden.
1046 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1047 continue;
1048
1049 // If either declaration was introduced by a using declaration,
1050 // we'll need to use slightly different rules for matching.
1051 // Essentially, these rules are the normal rules, except that
1052 // function templates hide function templates with different
1053 // return types or template parameter lists.
1054 bool UseMemberUsingDeclRules =
1055 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1056 !New->getFriendObjectKind();
1057
1058 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1059 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1060 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1061 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1062 continue;
1063 }
1064
1065 if (!isa<FunctionTemplateDecl>(OldD) &&
1066 !shouldLinkPossiblyHiddenDecl(*I, New))
1067 continue;
1068
1069 Match = *I;
1070 return Ovl_Match;
1071 }
1072
1073 // Builtins that have custom typechecking or have a reference should
1074 // not be overloadable or redeclarable.
1075 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1076 Match = *I;
1077 return Ovl_NonFunction;
1078 }
1079 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1080 // We can overload with these, which can show up when doing
1081 // redeclaration checks for UsingDecls.
1082 assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast<
void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1082, __PRETTY_FUNCTION__))
;
1083 } else if (isa<TagDecl>(OldD)) {
1084 // We can always overload with tags by hiding them.
1085 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1086 // Optimistically assume that an unresolved using decl will
1087 // overload; if it doesn't, we'll have to diagnose during
1088 // template instantiation.
1089 //
1090 // Exception: if the scope is dependent and this is not a class
1091 // member, the using declaration can only introduce an enumerator.
1092 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1093 Match = *I;
1094 return Ovl_NonFunction;
1095 }
1096 } else {
1097 // (C++ 13p1):
1098 // Only function declarations can be overloaded; object and type
1099 // declarations cannot be overloaded.
1100 Match = *I;
1101 return Ovl_NonFunction;
1102 }
1103 }
1104
1105 // C++ [temp.friend]p1:
1106 // For a friend function declaration that is not a template declaration:
1107 // -- if the name of the friend is a qualified or unqualified template-id,
1108 // [...], otherwise
1109 // -- if the name of the friend is a qualified-id and a matching
1110 // non-template function is found in the specified class or namespace,
1111 // the friend declaration refers to that function, otherwise,
1112 // -- if the name of the friend is a qualified-id and a matching function
1113 // template is found in the specified class or namespace, the friend
1114 // declaration refers to the deduced specialization of that function
1115 // template, otherwise
1116 // -- the name shall be an unqualified-id [...]
1117 // If we get here for a qualified friend declaration, we've just reached the
1118 // third bullet. If the type of the friend is dependent, skip this lookup
1119 // until instantiation.
1120 if (New->getFriendObjectKind() && New->getQualifier() &&
1121 !New->getDescribedFunctionTemplate() &&
1122 !New->getDependentSpecializationInfo() &&
1123 !New->getType()->isDependentType()) {
1124 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1125 TemplateSpecResult.addAllDecls(Old);
1126 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1127 /*QualifiedFriend*/true)) {
1128 New->setInvalidDecl();
1129 return Ovl_Overload;
1130 }
1131
1132 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1133 return Ovl_Match;
1134 }
1135
1136 return Ovl_Overload;
1137}
1138
1139bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1140 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1141 bool ConsiderRequiresClauses) {
1142 // C++ [basic.start.main]p2: This function shall not be overloaded.
1143 if (New->isMain())
1144 return false;
1145
1146 // MSVCRT user defined entry points cannot be overloaded.
1147 if (New->isMSVCRTEntryPoint())
1148 return false;
1149
1150 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1151 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1152
1153 // C++ [temp.fct]p2:
1154 // A function template can be overloaded with other function templates
1155 // and with normal (non-template) functions.
1156 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1157 return true;
1158
1159 // Is the function New an overload of the function Old?
1160 QualType OldQType = Context.getCanonicalType(Old->getType());
1161 QualType NewQType = Context.getCanonicalType(New->getType());
1162
1163 // Compare the signatures (C++ 1.3.10) of the two functions to
1164 // determine whether they are overloads. If we find any mismatch
1165 // in the signature, they are overloads.
1166
1167 // If either of these functions is a K&R-style function (no
1168 // prototype), then we consider them to have matching signatures.
1169 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1170 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1171 return false;
1172
1173 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1174 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1175
1176 // The signature of a function includes the types of its
1177 // parameters (C++ 1.3.10), which includes the presence or absence
1178 // of the ellipsis; see C++ DR 357).
1179 if (OldQType != NewQType &&
1180 (OldType->getNumParams() != NewType->getNumParams() ||
1181 OldType->isVariadic() != NewType->isVariadic() ||
1182 !FunctionParamTypesAreEqual(OldType, NewType)))
1183 return true;
1184
1185 // C++ [temp.over.link]p4:
1186 // The signature of a function template consists of its function
1187 // signature, its return type and its template parameter list. The names
1188 // of the template parameters are significant only for establishing the
1189 // relationship between the template parameters and the rest of the
1190 // signature.
1191 //
1192 // We check the return type and template parameter lists for function
1193 // templates first; the remaining checks follow.
1194 //
1195 // However, we don't consider either of these when deciding whether
1196 // a member introduced by a shadow declaration is hidden.
1197 if (!UseMemberUsingDeclRules && NewTemplate &&
1198 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1199 OldTemplate->getTemplateParameters(),
1200 false, TPL_TemplateMatch) ||
1201 !Context.hasSameType(Old->getDeclaredReturnType(),
1202 New->getDeclaredReturnType())))
1203 return true;
1204
1205 // If the function is a class member, its signature includes the
1206 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1207 //
1208 // As part of this, also check whether one of the member functions
1209 // is static, in which case they are not overloads (C++
1210 // 13.1p2). While not part of the definition of the signature,
1211 // this check is important to determine whether these functions
1212 // can be overloaded.
1213 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1214 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1215 if (OldMethod && NewMethod &&
1216 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1217 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1218 if (!UseMemberUsingDeclRules &&
1219 (OldMethod->getRefQualifier() == RQ_None ||
1220 NewMethod->getRefQualifier() == RQ_None)) {
1221 // C++0x [over.load]p2:
1222 // - Member function declarations with the same name and the same
1223 // parameter-type-list as well as member function template
1224 // declarations with the same name, the same parameter-type-list, and
1225 // the same template parameter lists cannot be overloaded if any of
1226 // them, but not all, have a ref-qualifier (8.3.5).
1227 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1228 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1229 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1230 }
1231 return true;
1232 }
1233
1234 // We may not have applied the implicit const for a constexpr member
1235 // function yet (because we haven't yet resolved whether this is a static
1236 // or non-static member function). Add it now, on the assumption that this
1237 // is a redeclaration of OldMethod.
1238 auto OldQuals = OldMethod->getMethodQualifiers();
1239 auto NewQuals = NewMethod->getMethodQualifiers();
1240 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1241 !isa<CXXConstructorDecl>(NewMethod))
1242 NewQuals.addConst();
1243 // We do not allow overloading based off of '__restrict'.
1244 OldQuals.removeRestrict();
1245 NewQuals.removeRestrict();
1246 if (OldQuals != NewQuals)
1247 return true;
1248 }
1249
1250 // Though pass_object_size is placed on parameters and takes an argument, we
1251 // consider it to be a function-level modifier for the sake of function
1252 // identity. Either the function has one or more parameters with
1253 // pass_object_size or it doesn't.
1254 if (functionHasPassObjectSizeParams(New) !=
1255 functionHasPassObjectSizeParams(Old))
1256 return true;
1257
1258 // enable_if attributes are an order-sensitive part of the signature.
1259 for (specific_attr_iterator<EnableIfAttr>
1260 NewI = New->specific_attr_begin<EnableIfAttr>(),
1261 NewE = New->specific_attr_end<EnableIfAttr>(),
1262 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1263 OldE = Old->specific_attr_end<EnableIfAttr>();
1264 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1265 if (NewI == NewE || OldI == OldE)
1266 return true;
1267 llvm::FoldingSetNodeID NewID, OldID;
1268 NewI->getCond()->Profile(NewID, Context, true);
1269 OldI->getCond()->Profile(OldID, Context, true);
1270 if (NewID != OldID)
1271 return true;
1272 }
1273
1274 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1275 // Don't allow overloading of destructors. (In theory we could, but it
1276 // would be a giant change to clang.)
1277 if (!isa<CXXDestructorDecl>(New)) {
1278 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1279 OldTarget = IdentifyCUDATarget(Old);
1280 if (NewTarget != CFT_InvalidTarget) {
1281 assert((OldTarget != CFT_InvalidTarget) &&(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1282, __PRETTY_FUNCTION__))
1282 "Unexpected invalid target.")(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1282, __PRETTY_FUNCTION__))
;
1283
1284 // Allow overloading of functions with same signature and different CUDA
1285 // target attributes.
1286 if (NewTarget != OldTarget)
1287 return true;
1288 }
1289 }
1290 }
1291
1292 if (ConsiderRequiresClauses) {
1293 Expr *NewRC = New->getTrailingRequiresClause(),
1294 *OldRC = Old->getTrailingRequiresClause();
1295 if ((NewRC != nullptr) != (OldRC != nullptr))
1296 // RC are most certainly different - these are overloads.
1297 return true;
1298
1299 if (NewRC) {
1300 llvm::FoldingSetNodeID NewID, OldID;
1301 NewRC->Profile(NewID, Context, /*Canonical=*/true);
1302 OldRC->Profile(OldID, Context, /*Canonical=*/true);
1303 if (NewID != OldID)
1304 // RCs are not equivalent - these are overloads.
1305 return true;
1306 }
1307 }
1308
1309 // The signatures match; this is not an overload.
1310 return false;
1311}
1312
1313/// Tries a user-defined conversion from From to ToType.
1314///
1315/// Produces an implicit conversion sequence for when a standard conversion
1316/// is not an option. See TryImplicitConversion for more information.
1317static ImplicitConversionSequence
1318TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1319 bool SuppressUserConversions,
1320 bool AllowExplicit,
1321 bool InOverloadResolution,
1322 bool CStyle,
1323 bool AllowObjCWritebackConversion,
1324 bool AllowObjCConversionOnExplicit) {
1325 ImplicitConversionSequence ICS;
1326
1327 if (SuppressUserConversions) {
1328 // We're not in the case above, so there is no conversion that
1329 // we can perform.
1330 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1331 return ICS;
1332 }
1333
1334 // Attempt user-defined conversion.
1335 OverloadCandidateSet Conversions(From->getExprLoc(),
1336 OverloadCandidateSet::CSK_Normal);
1337 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1338 Conversions, AllowExplicit,
1339 AllowObjCConversionOnExplicit)) {
1340 case OR_Success:
1341 case OR_Deleted:
1342 ICS.setUserDefined();
1343 // C++ [over.ics.user]p4:
1344 // A conversion of an expression of class type to the same class
1345 // type is given Exact Match rank, and a conversion of an
1346 // expression of class type to a base class of that type is
1347 // given Conversion rank, in spite of the fact that a copy
1348 // constructor (i.e., a user-defined conversion function) is
1349 // called for those cases.
1350 if (CXXConstructorDecl *Constructor
1351 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1352 QualType FromCanon
1353 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1354 QualType ToCanon
1355 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1356 if (Constructor->isCopyConstructor() &&
1357 (FromCanon == ToCanon ||
1358 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1359 // Turn this into a "standard" conversion sequence, so that it
1360 // gets ranked with standard conversion sequences.
1361 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1362 ICS.setStandard();
1363 ICS.Standard.setAsIdentityConversion();
1364 ICS.Standard.setFromType(From->getType());
1365 ICS.Standard.setAllToTypes(ToType);
1366 ICS.Standard.CopyConstructor = Constructor;
1367 ICS.Standard.FoundCopyConstructor = Found;
1368 if (ToCanon != FromCanon)
1369 ICS.Standard.Second = ICK_Derived_To_Base;
1370 }
1371 }
1372 break;
1373
1374 case OR_Ambiguous:
1375 ICS.setAmbiguous();
1376 ICS.Ambiguous.setFromType(From->getType());
1377 ICS.Ambiguous.setToType(ToType);
1378 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1379 Cand != Conversions.end(); ++Cand)
1380 if (Cand->Best)
1381 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1382 break;
1383
1384 // Fall through.
1385 case OR_No_Viable_Function:
1386 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1387 break;
1388 }
1389
1390 return ICS;
1391}
1392
1393/// TryImplicitConversion - Attempt to perform an implicit conversion
1394/// from the given expression (Expr) to the given type (ToType). This
1395/// function returns an implicit conversion sequence that can be used
1396/// to perform the initialization. Given
1397///
1398/// void f(float f);
1399/// void g(int i) { f(i); }
1400///
1401/// this routine would produce an implicit conversion sequence to
1402/// describe the initialization of f from i, which will be a standard
1403/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1404/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1405//
1406/// Note that this routine only determines how the conversion can be
1407/// performed; it does not actually perform the conversion. As such,
1408/// it will not produce any diagnostics if no conversion is available,
1409/// but will instead return an implicit conversion sequence of kind
1410/// "BadConversion".
1411///
1412/// If @p SuppressUserConversions, then user-defined conversions are
1413/// not permitted.
1414/// If @p AllowExplicit, then explicit user-defined conversions are
1415/// permitted.
1416///
1417/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1418/// writeback conversion, which allows __autoreleasing id* parameters to
1419/// be initialized with __strong id* or __weak id* arguments.
1420static ImplicitConversionSequence
1421TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1422 bool SuppressUserConversions,
1423 bool AllowExplicit,
1424 bool InOverloadResolution,
1425 bool CStyle,
1426 bool AllowObjCWritebackConversion,
1427 bool AllowObjCConversionOnExplicit) {
1428 ImplicitConversionSequence ICS;
1429 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1430 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1431 ICS.setStandard();
1432 return ICS;
1433 }
1434
1435 if (!S.getLangOpts().CPlusPlus) {
1436 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1437 return ICS;
1438 }
1439
1440 // C++ [over.ics.user]p4:
1441 // A conversion of an expression of class type to the same class
1442 // type is given Exact Match rank, and a conversion of an
1443 // expression of class type to a base class of that type is
1444 // given Conversion rank, in spite of the fact that a copy/move
1445 // constructor (i.e., a user-defined conversion function) is
1446 // called for those cases.
1447 QualType FromType = From->getType();
1448 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1449 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1450 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1451 ICS.setStandard();
1452 ICS.Standard.setAsIdentityConversion();
1453 ICS.Standard.setFromType(FromType);
1454 ICS.Standard.setAllToTypes(ToType);
1455
1456 // We don't actually check at this point whether there is a valid
1457 // copy/move constructor, since overloading just assumes that it
1458 // exists. When we actually perform initialization, we'll find the
1459 // appropriate constructor to copy the returned object, if needed.
1460 ICS.Standard.CopyConstructor = nullptr;
1461
1462 // Determine whether this is considered a derived-to-base conversion.
1463 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1464 ICS.Standard.Second = ICK_Derived_To_Base;
1465
1466 return ICS;
1467 }
1468
1469 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1470 AllowExplicit, InOverloadResolution, CStyle,
1471 AllowObjCWritebackConversion,
1472 AllowObjCConversionOnExplicit);
1473}
1474
1475ImplicitConversionSequence
1476Sema::TryImplicitConversion(Expr *From, QualType ToType,
1477 bool SuppressUserConversions,
1478 bool AllowExplicit,
1479 bool InOverloadResolution,
1480 bool CStyle,
1481 bool AllowObjCWritebackConversion) {
1482 return ::TryImplicitConversion(*this, From, ToType,
1483 SuppressUserConversions, AllowExplicit,
1484 InOverloadResolution, CStyle,
1485 AllowObjCWritebackConversion,
1486 /*AllowObjCConversionOnExplicit=*/false);
1487}
1488
1489/// PerformImplicitConversion - Perform an implicit conversion of the
1490/// expression From to the type ToType. Returns the
1491/// converted expression. Flavor is the kind of conversion we're
1492/// performing, used in the error message. If @p AllowExplicit,
1493/// explicit user-defined conversions are permitted.
1494ExprResult
1495Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496 AssignmentAction Action, bool AllowExplicit) {
1497 ImplicitConversionSequence ICS;
1498 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1499}
1500
1501ExprResult
1502Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1503 AssignmentAction Action, bool AllowExplicit,
1504 ImplicitConversionSequence& ICS) {
1505 if (checkPlaceholderForOverload(*this, From))
1506 return ExprError();
1507
1508 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1509 bool AllowObjCWritebackConversion
1510 = getLangOpts().ObjCAutoRefCount &&
1511 (Action == AA_Passing || Action == AA_Sending);
1512 if (getLangOpts().ObjC)
1513 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1514 From->getType(), From);
1515 ICS = ::TryImplicitConversion(*this, From, ToType,
1516 /*SuppressUserConversions=*/false,
1517 AllowExplicit,
1518 /*InOverloadResolution=*/false,
1519 /*CStyle=*/false,
1520 AllowObjCWritebackConversion,
1521 /*AllowObjCConversionOnExplicit=*/false);
1522 return PerformImplicitConversion(From, ToType, ICS, Action);
1523}
1524
1525/// Determine whether the conversion from FromType to ToType is a valid
1526/// conversion that strips "noexcept" or "noreturn" off the nested function
1527/// type.
1528bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1529 QualType &ResultTy) {
1530 if (Context.hasSameUnqualifiedType(FromType, ToType))
1531 return false;
1532
1533 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1534 // or F(t noexcept) -> F(t)
1535 // where F adds one of the following at most once:
1536 // - a pointer
1537 // - a member pointer
1538 // - a block pointer
1539 // Changes here need matching changes in FindCompositePointerType.
1540 CanQualType CanTo = Context.getCanonicalType(ToType);
1541 CanQualType CanFrom = Context.getCanonicalType(FromType);
1542 Type::TypeClass TyClass = CanTo->getTypeClass();
1543 if (TyClass != CanFrom->getTypeClass()) return false;
1544 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1545 if (TyClass == Type::Pointer) {
1546 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1547 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1548 } else if (TyClass == Type::BlockPointer) {
1549 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1550 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1551 } else if (TyClass == Type::MemberPointer) {
1552 auto ToMPT = CanTo.castAs<MemberPointerType>();
1553 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1554 // A function pointer conversion cannot change the class of the function.
1555 if (ToMPT->getClass() != FromMPT->getClass())
1556 return false;
1557 CanTo = ToMPT->getPointeeType();
1558 CanFrom = FromMPT->getPointeeType();
1559 } else {
1560 return false;
1561 }
1562
1563 TyClass = CanTo->getTypeClass();
1564 if (TyClass != CanFrom->getTypeClass()) return false;
1565 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1566 return false;
1567 }
1568
1569 const auto *FromFn = cast<FunctionType>(CanFrom);
1570 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1571
1572 const auto *ToFn = cast<FunctionType>(CanTo);
1573 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1574
1575 bool Changed = false;
1576
1577 // Drop 'noreturn' if not present in target type.
1578 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1579 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1580 Changed = true;
1581 }
1582
1583 // Drop 'noexcept' if not present in target type.
1584 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1585 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1586 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1587 FromFn = cast<FunctionType>(
1588 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1589 EST_None)
1590 .getTypePtr());
1591 Changed = true;
1592 }
1593
1594 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1595 // only if the ExtParameterInfo lists of the two function prototypes can be
1596 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1597 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1598 bool CanUseToFPT, CanUseFromFPT;
1599 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1600 CanUseFromFPT, NewParamInfos) &&
1601 CanUseToFPT && !CanUseFromFPT) {
1602 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1603 ExtInfo.ExtParameterInfos =
1604 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1605 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1606 FromFPT->getParamTypes(), ExtInfo);
1607 FromFn = QT->getAs<FunctionType>();
1608 Changed = true;
1609 }
1610 }
1611
1612 if (!Changed)
1613 return false;
1614
1615 assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void>
(0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1615, __PRETTY_FUNCTION__))
;
1616 if (QualType(FromFn, 0) != CanTo) return false;
1617
1618 ResultTy = ToType;
1619 return true;
1620}
1621
1622/// Determine whether the conversion from FromType to ToType is a valid
1623/// vector conversion.
1624///
1625/// \param ICK Will be set to the vector conversion kind, if this is a vector
1626/// conversion.
1627static bool IsVectorConversion(Sema &S, QualType FromType,
1628 QualType ToType, ImplicitConversionKind &ICK) {
1629 // We need at least one of these types to be a vector type to have a vector
1630 // conversion.
1631 if (!ToType->isVectorType() && !FromType->isVectorType())
1632 return false;
1633
1634 // Identical types require no conversions.
1635 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1636 return false;
1637
1638 // There are no conversions between extended vector types, only identity.
1639 if (ToType->isExtVectorType()) {
1640 // There are no conversions between extended vector types other than the
1641 // identity conversion.
1642 if (FromType->isExtVectorType())
1643 return false;
1644
1645 // Vector splat from any arithmetic type to a vector.
1646 if (FromType->isArithmeticType()) {
1647 ICK = ICK_Vector_Splat;
1648 return true;
1649 }
1650 }
1651
1652 // We can perform the conversion between vector types in the following cases:
1653 // 1)vector types are equivalent AltiVec and GCC vector types
1654 // 2)lax vector conversions are permitted and the vector types are of the
1655 // same size
1656 if (ToType->isVectorType() && FromType->isVectorType()) {
1657 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1658 S.isLaxVectorConversion(FromType, ToType)) {
1659 ICK = ICK_Vector_Conversion;
1660 return true;
1661 }
1662 }
1663
1664 return false;
1665}
1666
1667static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1668 bool InOverloadResolution,
1669 StandardConversionSequence &SCS,
1670 bool CStyle);
1671
1672/// IsStandardConversion - Determines whether there is a standard
1673/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1674/// expression From to the type ToType. Standard conversion sequences
1675/// only consider non-class types; for conversions that involve class
1676/// types, use TryImplicitConversion. If a conversion exists, SCS will
1677/// contain the standard conversion sequence required to perform this
1678/// conversion and this routine will return true. Otherwise, this
1679/// routine will return false and the value of SCS is unspecified.
1680static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1681 bool InOverloadResolution,
1682 StandardConversionSequence &SCS,
1683 bool CStyle,
1684 bool AllowObjCWritebackConversion) {
1685 QualType FromType = From->getType();
1686
1687 // Standard conversions (C++ [conv])
1688 SCS.setAsIdentityConversion();
1689 SCS.IncompatibleObjC = false;
1690 SCS.setFromType(FromType);
1691 SCS.CopyConstructor = nullptr;
1692
1693 // There are no standard conversions for class types in C++, so
1694 // abort early. When overloading in C, however, we do permit them.
1695 if (S.getLangOpts().CPlusPlus &&
1696 (FromType->isRecordType() || ToType->isRecordType()))
1697 return false;
1698
1699 // The first conversion can be an lvalue-to-rvalue conversion,
1700 // array-to-pointer conversion, or function-to-pointer conversion
1701 // (C++ 4p1).
1702
1703 if (FromType == S.Context.OverloadTy) {
1704 DeclAccessPair AccessPair;
1705 if (FunctionDecl *Fn
1706 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1707 AccessPair)) {
1708 // We were able to resolve the address of the overloaded function,
1709 // so we can convert to the type of that function.
1710 FromType = Fn->getType();
1711 SCS.setFromType(FromType);
1712
1713 // we can sometimes resolve &foo<int> regardless of ToType, so check
1714 // if the type matches (identity) or we are converting to bool
1715 if (!S.Context.hasSameUnqualifiedType(
1716 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1717 QualType resultTy;
1718 // if the function type matches except for [[noreturn]], it's ok
1719 if (!S.IsFunctionConversion(FromType,
1720 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1721 // otherwise, only a boolean conversion is standard
1722 if (!ToType->isBooleanType())
1723 return false;
1724 }
1725
1726 // Check if the "from" expression is taking the address of an overloaded
1727 // function and recompute the FromType accordingly. Take advantage of the
1728 // fact that non-static member functions *must* have such an address-of
1729 // expression.
1730 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1731 if (Method && !Method->isStatic()) {
1732 assert(isa<UnaryOperator>(From->IgnoreParens()) &&((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1733, __PRETTY_FUNCTION__))
1733 "Non-unary operator on non-static member address")((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1733, __PRETTY_FUNCTION__))
;
1734 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1736, __PRETTY_FUNCTION__))
1735 == UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1736, __PRETTY_FUNCTION__))
1736 "Non-address-of operator on non-static member address")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1736, __PRETTY_FUNCTION__))
;
1737 const Type *ClassType
1738 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1739 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1740 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1741 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1743, __PRETTY_FUNCTION__))
1742 UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1743, __PRETTY_FUNCTION__))
1743 "Non-address-of operator for overloaded function expression")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1743, __PRETTY_FUNCTION__))
;
1744 FromType = S.Context.getPointerType(FromType);
1745 }
1746
1747 // Check that we've computed the proper type after overload resolution.
1748 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1749 // be calling it from within an NDEBUG block.
1750 assert(S.Context.hasSameType(((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1752, __PRETTY_FUNCTION__))
1751 FromType,((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1752, __PRETTY_FUNCTION__))
1752 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1752, __PRETTY_FUNCTION__))
;
1753 } else {
1754 return false;
1755 }
1756 }
1757 // Lvalue-to-rvalue conversion (C++11 4.1):
1758 // A glvalue (3.10) of a non-function, non-array type T can
1759 // be converted to a prvalue.
1760 bool argIsLValue = From->isGLValue();
1761 if (argIsLValue &&
1762 !FromType->isFunctionType() && !FromType->isArrayType() &&
1763 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1764 SCS.First = ICK_Lvalue_To_Rvalue;
1765
1766 // C11 6.3.2.1p2:
1767 // ... if the lvalue has atomic type, the value has the non-atomic version
1768 // of the type of the lvalue ...
1769 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1770 FromType = Atomic->getValueType();
1771
1772 // If T is a non-class type, the type of the rvalue is the
1773 // cv-unqualified version of T. Otherwise, the type of the rvalue
1774 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1775 // just strip the qualifiers because they don't matter.
1776 FromType = FromType.getUnqualifiedType();
1777 } else if (FromType->isArrayType()) {
1778 // Array-to-pointer conversion (C++ 4.2)
1779 SCS.First = ICK_Array_To_Pointer;
1780
1781 // An lvalue or rvalue of type "array of N T" or "array of unknown
1782 // bound of T" can be converted to an rvalue of type "pointer to
1783 // T" (C++ 4.2p1).
1784 FromType = S.Context.getArrayDecayedType(FromType);
1785
1786 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1787 // This conversion is deprecated in C++03 (D.4)
1788 SCS.DeprecatedStringLiteralToCharPtr = true;
1789
1790 // For the purpose of ranking in overload resolution
1791 // (13.3.3.1.1), this conversion is considered an
1792 // array-to-pointer conversion followed by a qualification
1793 // conversion (4.4). (C++ 4.2p2)
1794 SCS.Second = ICK_Identity;
1795 SCS.Third = ICK_Qualification;
1796 SCS.QualificationIncludesObjCLifetime = false;
1797 SCS.setAllToTypes(FromType);
1798 return true;
1799 }
1800 } else if (FromType->isFunctionType() && argIsLValue) {
1801 // Function-to-pointer conversion (C++ 4.3).
1802 SCS.First = ICK_Function_To_Pointer;
1803
1804 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1805 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1806 if (!S.checkAddressOfFunctionIsAvailable(FD))
1807 return false;
1808
1809 // An lvalue of function type T can be converted to an rvalue of
1810 // type "pointer to T." The result is a pointer to the
1811 // function. (C++ 4.3p1).
1812 FromType = S.Context.getPointerType(FromType);
1813 } else {
1814 // We don't require any conversions for the first step.
1815 SCS.First = ICK_Identity;
1816 }
1817 SCS.setToType(0, FromType);
1818
1819 // The second conversion can be an integral promotion, floating
1820 // point promotion, integral conversion, floating point conversion,
1821 // floating-integral conversion, pointer conversion,
1822 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1823 // For overloading in C, this can also be a "compatible-type"
1824 // conversion.
1825 bool IncompatibleObjC = false;
1826 ImplicitConversionKind SecondICK = ICK_Identity;
1827 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1828 // The unqualified versions of the types are the same: there's no
1829 // conversion to do.
1830 SCS.Second = ICK_Identity;
1831 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1832 // Integral promotion (C++ 4.5).
1833 SCS.Second = ICK_Integral_Promotion;
1834 FromType = ToType.getUnqualifiedType();
1835 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1836 // Floating point promotion (C++ 4.6).
1837 SCS.Second = ICK_Floating_Promotion;
1838 FromType = ToType.getUnqualifiedType();
1839 } else if (S.IsComplexPromotion(FromType, ToType)) {
1840 // Complex promotion (Clang extension)
1841 SCS.Second = ICK_Complex_Promotion;
1842 FromType = ToType.getUnqualifiedType();
1843 } else if (ToType->isBooleanType() &&
1844 (FromType->isArithmeticType() ||
1845 FromType->isAnyPointerType() ||
1846 FromType->isBlockPointerType() ||
1847 FromType->isMemberPointerType() ||
1848 FromType->isNullPtrType())) {
1849 // Boolean conversions (C++ 4.12).
1850 SCS.Second = ICK_Boolean_Conversion;
1851 FromType = S.Context.BoolTy;
1852 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1853 ToType->isIntegralType(S.Context)) {
1854 // Integral conversions (C++ 4.7).
1855 SCS.Second = ICK_Integral_Conversion;
1856 FromType = ToType.getUnqualifiedType();
1857 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1858 // Complex conversions (C99 6.3.1.6)
1859 SCS.Second = ICK_Complex_Conversion;
1860 FromType = ToType.getUnqualifiedType();
1861 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1862 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1863 // Complex-real conversions (C99 6.3.1.7)
1864 SCS.Second = ICK_Complex_Real;
1865 FromType = ToType.getUnqualifiedType();
1866 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1867 // FIXME: disable conversions between long double and __float128 if
1868 // their representation is different until there is back end support
1869 // We of course allow this conversion if long double is really double.
1870 if (&S.Context.getFloatTypeSemantics(FromType) !=
1871 &S.Context.getFloatTypeSemantics(ToType)) {
1872 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1873 ToType == S.Context.LongDoubleTy) ||
1874 (FromType == S.Context.LongDoubleTy &&
1875 ToType == S.Context.Float128Ty));
1876 if (Float128AndLongDouble &&
1877 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1878 &llvm::APFloat::PPCDoubleDouble()))
1879 return false;
1880 }
1881 // Floating point conversions (C++ 4.8).
1882 SCS.Second = ICK_Floating_Conversion;
1883 FromType = ToType.getUnqualifiedType();
1884 } else if ((FromType->isRealFloatingType() &&
1885 ToType->isIntegralType(S.Context)) ||
1886 (FromType->isIntegralOrUnscopedEnumerationType() &&
1887 ToType->isRealFloatingType())) {
1888 // Floating-integral conversions (C++ 4.9).
1889 SCS.Second = ICK_Floating_Integral;
1890 FromType = ToType.getUnqualifiedType();
1891 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1892 SCS.Second = ICK_Block_Pointer_Conversion;
1893 } else if (AllowObjCWritebackConversion &&
1894 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1895 SCS.Second = ICK_Writeback_Conversion;
1896 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1897 FromType, IncompatibleObjC)) {
1898 // Pointer conversions (C++ 4.10).
1899 SCS.Second = ICK_Pointer_Conversion;
1900 SCS.IncompatibleObjC = IncompatibleObjC;
1901 FromType = FromType.getUnqualifiedType();
1902 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1903 InOverloadResolution, FromType)) {
1904 // Pointer to member conversions (4.11).
1905 SCS.Second = ICK_Pointer_Member;
1906 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1907 SCS.Second = SecondICK;
1908 FromType = ToType.getUnqualifiedType();
1909 } else if (!S.getLangOpts().CPlusPlus &&
1910 S.Context.typesAreCompatible(ToType, FromType)) {
1911 // Compatible conversions (Clang extension for C function overloading)
1912 SCS.Second = ICK_Compatible_Conversion;
1913 FromType = ToType.getUnqualifiedType();
1914 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1915 InOverloadResolution,
1916 SCS, CStyle)) {
1917 SCS.Second = ICK_TransparentUnionConversion;
1918 FromType = ToType;
1919 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1920 CStyle)) {
1921 // tryAtomicConversion has updated the standard conversion sequence
1922 // appropriately.
1923 return true;
1924 } else if (ToType->isEventT() &&
1925 From->isIntegerConstantExpr(S.getASTContext()) &&
1926 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1927 SCS.Second = ICK_Zero_Event_Conversion;
1928 FromType = ToType;
1929 } else if (ToType->isQueueT() &&
1930 From->isIntegerConstantExpr(S.getASTContext()) &&
1931 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1932 SCS.Second = ICK_Zero_Queue_Conversion;
1933 FromType = ToType;
1934 } else if (ToType->isSamplerT() &&
1935 From->isIntegerConstantExpr(S.getASTContext())) {
1936 SCS.Second = ICK_Compatible_Conversion;
1937 FromType = ToType;
1938 } else {
1939 // No second conversion required.
1940 SCS.Second = ICK_Identity;
1941 }
1942 SCS.setToType(1, FromType);
1943
1944 // The third conversion can be a function pointer conversion or a
1945 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1946 bool ObjCLifetimeConversion;
1947 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1948 // Function pointer conversions (removing 'noexcept') including removal of
1949 // 'noreturn' (Clang extension).
1950 SCS.Third = ICK_Function_Conversion;
1951 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1952 ObjCLifetimeConversion)) {
1953 SCS.Third = ICK_Qualification;
1954 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1955 FromType = ToType;
1956 } else {
1957 // No conversion required
1958 SCS.Third = ICK_Identity;
1959 }
1960
1961 // C++ [over.best.ics]p6:
1962 // [...] Any difference in top-level cv-qualification is
1963 // subsumed by the initialization itself and does not constitute
1964 // a conversion. [...]
1965 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1966 QualType CanonTo = S.Context.getCanonicalType(ToType);
1967 if (CanonFrom.getLocalUnqualifiedType()
1968 == CanonTo.getLocalUnqualifiedType() &&
1969 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1970 FromType = ToType;
1971 CanonFrom = CanonTo;
1972 }
1973
1974 SCS.setToType(2, FromType);
1975
1976 if (CanonFrom == CanonTo)
1977 return true;
1978
1979 // If we have not converted the argument type to the parameter type,
1980 // this is a bad conversion sequence, unless we're resolving an overload in C.
1981 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1982 return false;
1983
1984 ExprResult ER = ExprResult{From};
1985 Sema::AssignConvertType Conv =
1986 S.CheckSingleAssignmentConstraints(ToType, ER,
1987 /*Diagnose=*/false,
1988 /*DiagnoseCFAudited=*/false,
1989 /*ConvertRHS=*/false);
1990 ImplicitConversionKind SecondConv;
1991 switch (Conv) {
1992 case Sema::Compatible:
1993 SecondConv = ICK_C_Only_Conversion;
1994 break;
1995 // For our purposes, discarding qualifiers is just as bad as using an
1996 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1997 // qualifiers, as well.
1998 case Sema::CompatiblePointerDiscardsQualifiers:
1999 case Sema::IncompatiblePointer:
2000 case Sema::IncompatiblePointerSign:
2001 SecondConv = ICK_Incompatible_Pointer_Conversion;
2002 break;
2003 default:
2004 return false;
2005 }
2006
2007 // First can only be an lvalue conversion, so we pretend that this was the
2008 // second conversion. First should already be valid from earlier in the
2009 // function.
2010 SCS.Second = SecondConv;
2011 SCS.setToType(1, ToType);
2012
2013 // Third is Identity, because Second should rank us worse than any other
2014 // conversion. This could also be ICK_Qualification, but it's simpler to just
2015 // lump everything in with the second conversion, and we don't gain anything
2016 // from making this ICK_Qualification.
2017 SCS.Third = ICK_Identity;
2018 SCS.setToType(2, ToType);
2019 return true;
2020}
2021
2022static bool
2023IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2024 QualType &ToType,
2025 bool InOverloadResolution,
2026 StandardConversionSequence &SCS,
2027 bool CStyle) {
2028
2029 const RecordType *UT = ToType->getAsUnionType();
2030 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2031 return false;
2032 // The field to initialize within the transparent union.
2033 RecordDecl *UD = UT->getDecl();
2034 // It's compatible if the expression matches any of the fields.
2035 for (const auto *it : UD->fields()) {
2036 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2037 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2038 ToType = it->getType();
2039 return true;
2040 }
2041 }
2042 return false;
2043}
2044
2045/// IsIntegralPromotion - Determines whether the conversion from the
2046/// expression From (whose potentially-adjusted type is FromType) to
2047/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2048/// sets PromotedType to the promoted type.
2049bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2050 const BuiltinType *To = ToType->getAs<BuiltinType>();
2051 // All integers are built-in.
2052 if (!To) {
2053 return false;
2054 }
2055
2056 // An rvalue of type char, signed char, unsigned char, short int, or
2057 // unsigned short int can be converted to an rvalue of type int if
2058 // int can represent all the values of the source type; otherwise,
2059 // the source rvalue can be converted to an rvalue of type unsigned
2060 // int (C++ 4.5p1).
2061 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2062 !FromType->isEnumeralType()) {
2063 if (// We can promote any signed, promotable integer type to an int
2064 (FromType->isSignedIntegerType() ||
2065 // We can promote any unsigned integer type whose size is
2066 // less than int to an int.
2067 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2068 return To->getKind() == BuiltinType::Int;
2069 }
2070
2071 return To->getKind() == BuiltinType::UInt;
2072 }
2073
2074 // C++11 [conv.prom]p3:
2075 // A prvalue of an unscoped enumeration type whose underlying type is not
2076 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2077 // following types that can represent all the values of the enumeration
2078 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2079 // unsigned int, long int, unsigned long int, long long int, or unsigned
2080 // long long int. If none of the types in that list can represent all the
2081 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2082 // type can be converted to an rvalue a prvalue of the extended integer type
2083 // with lowest integer conversion rank (4.13) greater than the rank of long
2084 // long in which all the values of the enumeration can be represented. If
2085 // there are two such extended types, the signed one is chosen.
2086 // C++11 [conv.prom]p4:
2087 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2088 // can be converted to a prvalue of its underlying type. Moreover, if
2089 // integral promotion can be applied to its underlying type, a prvalue of an
2090 // unscoped enumeration type whose underlying type is fixed can also be
2091 // converted to a prvalue of the promoted underlying type.
2092 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2093 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2094 // provided for a scoped enumeration.
2095 if (FromEnumType->getDecl()->isScoped())
2096 return false;
2097
2098 // We can perform an integral promotion to the underlying type of the enum,
2099 // even if that's not the promoted type. Note that the check for promoting
2100 // the underlying type is based on the type alone, and does not consider
2101 // the bitfield-ness of the actual source expression.
2102 if (FromEnumType->getDecl()->isFixed()) {
2103 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2104 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2105 IsIntegralPromotion(nullptr, Underlying, ToType);
2106 }
2107
2108 // We have already pre-calculated the promotion type, so this is trivial.
2109 if (ToType->isIntegerType() &&
2110 isCompleteType(From->getBeginLoc(), FromType))
2111 return Context.hasSameUnqualifiedType(
2112 ToType, FromEnumType->getDecl()->getPromotionType());
2113
2114 // C++ [conv.prom]p5:
2115 // If the bit-field has an enumerated type, it is treated as any other
2116 // value of that type for promotion purposes.
2117 //
2118 // ... so do not fall through into the bit-field checks below in C++.
2119 if (getLangOpts().CPlusPlus)
2120 return false;
2121 }
2122
2123 // C++0x [conv.prom]p2:
2124 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2125 // to an rvalue a prvalue of the first of the following types that can
2126 // represent all the values of its underlying type: int, unsigned int,
2127 // long int, unsigned long int, long long int, or unsigned long long int.
2128 // If none of the types in that list can represent all the values of its
2129 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2130 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2131 // type.
2132 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2133 ToType->isIntegerType()) {
2134 // Determine whether the type we're converting from is signed or
2135 // unsigned.
2136 bool FromIsSigned = FromType->isSignedIntegerType();
2137 uint64_t FromSize = Context.getTypeSize(FromType);
2138
2139 // The types we'll try to promote to, in the appropriate
2140 // order. Try each of these types.
2141 QualType PromoteTypes[6] = {
2142 Context.IntTy, Context.UnsignedIntTy,
2143 Context.LongTy, Context.UnsignedLongTy ,
2144 Context.LongLongTy, Context.UnsignedLongLongTy
2145 };
2146 for (int Idx = 0; Idx < 6; ++Idx) {
2147 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2148 if (FromSize < ToSize ||
2149 (FromSize == ToSize &&
2150 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2151 // We found the type that we can promote to. If this is the
2152 // type we wanted, we have a promotion. Otherwise, no
2153 // promotion.
2154 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2155 }
2156 }
2157 }
2158
2159 // An rvalue for an integral bit-field (9.6) can be converted to an
2160 // rvalue of type int if int can represent all the values of the
2161 // bit-field; otherwise, it can be converted to unsigned int if
2162 // unsigned int can represent all the values of the bit-field. If
2163 // the bit-field is larger yet, no integral promotion applies to
2164 // it. If the bit-field has an enumerated type, it is treated as any
2165 // other value of that type for promotion purposes (C++ 4.5p3).
2166 // FIXME: We should delay checking of bit-fields until we actually perform the
2167 // conversion.
2168 //
2169 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2170 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2171 // bit-fields and those whose underlying type is larger than int) for GCC
2172 // compatibility.
2173 if (From) {
2174 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2175 llvm::APSInt BitWidth;
2176 if (FromType->isIntegralType(Context) &&
2177 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2178 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2179 ToSize = Context.getTypeSize(ToType);
2180
2181 // Are we promoting to an int from a bitfield that fits in an int?
2182 if (BitWidth < ToSize ||
2183 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2184 return To->getKind() == BuiltinType::Int;
2185 }
2186
2187 // Are we promoting to an unsigned int from an unsigned bitfield
2188 // that fits into an unsigned int?
2189 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2190 return To->getKind() == BuiltinType::UInt;
2191 }
2192
2193 return false;
2194 }
2195 }
2196 }
2197
2198 // An rvalue of type bool can be converted to an rvalue of type int,
2199 // with false becoming zero and true becoming one (C++ 4.5p4).
2200 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2201 return true;
2202 }
2203
2204 return false;
2205}
2206
2207/// IsFloatingPointPromotion - Determines whether the conversion from
2208/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2209/// returns true and sets PromotedType to the promoted type.
2210bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2211 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2212 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2213 /// An rvalue of type float can be converted to an rvalue of type
2214 /// double. (C++ 4.6p1).
2215 if (FromBuiltin->getKind() == BuiltinType::Float &&
2216 ToBuiltin->getKind() == BuiltinType::Double)
2217 return true;
2218
2219 // C99 6.3.1.5p1:
2220 // When a float is promoted to double or long double, or a
2221 // double is promoted to long double [...].
2222 if (!getLangOpts().CPlusPlus &&
2223 (FromBuiltin->getKind() == BuiltinType::Float ||
2224 FromBuiltin->getKind() == BuiltinType::Double) &&
2225 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2226 ToBuiltin->getKind() == BuiltinType::Float128))
2227 return true;
2228
2229 // Half can be promoted to float.
2230 if (!getLangOpts().NativeHalfType &&
2231 FromBuiltin->getKind() == BuiltinType::Half &&
2232 ToBuiltin->getKind() == BuiltinType::Float)
2233 return true;
2234 }
2235
2236 return false;
2237}
2238
2239/// Determine if a conversion is a complex promotion.
2240///
2241/// A complex promotion is defined as a complex -> complex conversion
2242/// where the conversion between the underlying real types is a
2243/// floating-point or integral promotion.
2244bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2245 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2246 if (!FromComplex)
2247 return false;
2248
2249 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2250 if (!ToComplex)
2251 return false;
2252
2253 return IsFloatingPointPromotion(FromComplex->getElementType(),
2254 ToComplex->getElementType()) ||
2255 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2256 ToComplex->getElementType());
2257}
2258
2259/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2260/// the pointer type FromPtr to a pointer to type ToPointee, with the
2261/// same type qualifiers as FromPtr has on its pointee type. ToType,
2262/// if non-empty, will be a pointer to ToType that may or may not have
2263/// the right set of qualifiers on its pointee.
2264///
2265static QualType
2266BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2267 QualType ToPointee, QualType ToType,
2268 ASTContext &Context,
2269 bool StripObjCLifetime = false) {
2270 assert((FromPtr->getTypeClass() == Type::Pointer ||(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 2272, __PRETTY_FUNCTION__))
2271 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 2272, __PRETTY_FUNCTION__))
2272 "Invalid similarly-qualified pointer type")(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 2272, __PRETTY_FUNCTION__))
;
2273
2274 /// Conversions to 'id' subsume cv-qualifier conversions.
2275 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2276 return ToType.getUnqualifiedType();
2277
2278 QualType CanonFromPointee
2279 = Context.getCanonicalType(FromPtr->getPointeeType());
2280 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2281 Qualifiers Quals = CanonFromPointee.getQualifiers();
2282
2283 if (StripObjCLifetime)
2284 Quals.removeObjCLifetime();
2285
2286 // Exact qualifier match -> return the pointer type we're converting to.
2287 if (CanonToPointee.getLocalQualifiers() == Quals) {
2288 // ToType is exactly what we need. Return it.
2289 if (!ToType.isNull())
2290 return ToType.getUnqualifiedType();
2291
2292 // Build a pointer to ToPointee. It has the right qualifiers
2293 // already.
2294 if (isa<ObjCObjectPointerType>(ToType))
2295 return Context.getObjCObjectPointerType(ToPointee);
2296 return Context.getPointerType(ToPointee);
2297 }
2298
2299 // Just build a canonical type that has the right qualifiers.
2300 QualType QualifiedCanonToPointee
2301 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2302
2303 if (isa<ObjCObjectPointerType>(ToType))
2304 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2305 return Context.getPointerType(QualifiedCanonToPointee);
2306}
2307
2308static bool isNullPointerConstantForConversion(Expr *Expr,
2309 bool InOverloadResolution,
2310 ASTContext &Context) {
2311 // Handle value-dependent integral null pointer constants correctly.
2312 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2313 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2314 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2315 return !InOverloadResolution;
2316
2317 return Expr->isNullPointerConstant(Context,
2318 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2319 : Expr::NPC_ValueDependentIsNull);
2320}
2321
2322/// IsPointerConversion - Determines whether the conversion of the
2323/// expression From, which has the (possibly adjusted) type FromType,
2324/// can be converted to the type ToType via a pointer conversion (C++
2325/// 4.10). If so, returns true and places the converted type (that
2326/// might differ from ToType in its cv-qualifiers at some level) into
2327/// ConvertedType.
2328///
2329/// This routine also supports conversions to and from block pointers
2330/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2331/// pointers to interfaces. FIXME: Once we've determined the
2332/// appropriate overloading rules for Objective-C, we may want to
2333/// split the Objective-C checks into a different routine; however,
2334/// GCC seems to consider all of these conversions to be pointer
2335/// conversions, so for now they live here. IncompatibleObjC will be
2336/// set if the conversion is an allowed Objective-C conversion that
2337/// should result in a warning.
2338bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2339 bool InOverloadResolution,
2340 QualType& ConvertedType,
2341 bool &IncompatibleObjC) {
2342 IncompatibleObjC = false;
2343 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2344 IncompatibleObjC))
2345 return true;
2346
2347 // Conversion from a null pointer constant to any Objective-C pointer type.
2348 if (ToType->isObjCObjectPointerType() &&
2349 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2350 ConvertedType = ToType;
2351 return true;
2352 }
2353
2354 // Blocks: Block pointers can be converted to void*.
2355 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2356 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2357 ConvertedType = ToType;
2358 return true;
2359 }
2360 // Blocks: A null pointer constant can be converted to a block
2361 // pointer type.
2362 if (ToType->isBlockPointerType() &&
2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2364 ConvertedType = ToType;
2365 return true;
2366 }
2367
2368 // If the left-hand-side is nullptr_t, the right side can be a null
2369 // pointer constant.
2370 if (ToType->isNullPtrType() &&
2371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2372 ConvertedType = ToType;
2373 return true;
2374 }
2375
2376 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2377 if (!ToTypePtr)
2378 return false;
2379
2380 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2381 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2382 ConvertedType = ToType;
2383 return true;
2384 }
2385
2386 // Beyond this point, both types need to be pointers
2387 // , including objective-c pointers.
2388 QualType ToPointeeType = ToTypePtr->getPointeeType();
2389 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2390 !getLangOpts().ObjCAutoRefCount) {
2391 ConvertedType = BuildSimilarlyQualifiedPointerType(
2392 FromType->getAs<ObjCObjectPointerType>(),
2393 ToPointeeType,
2394 ToType, Context);
2395 return true;
2396 }
2397 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2398 if (!FromTypePtr)
2399 return false;
2400
2401 QualType FromPointeeType = FromTypePtr->getPointeeType();
2402
2403 // If the unqualified pointee types are the same, this can't be a
2404 // pointer conversion, so don't do all of the work below.
2405 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2406 return false;
2407
2408 // An rvalue of type "pointer to cv T," where T is an object type,
2409 // can be converted to an rvalue of type "pointer to cv void" (C++
2410 // 4.10p2).
2411 if (FromPointeeType->isIncompleteOrObjectType() &&
2412 ToPointeeType->isVoidType()) {
2413 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2414 ToPointeeType,
2415 ToType, Context,
2416 /*StripObjCLifetime=*/true);
2417 return true;
2418 }
2419
2420 // MSVC allows implicit function to void* type conversion.
2421 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2422 ToPointeeType->isVoidType()) {
2423 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2424 ToPointeeType,
2425 ToType, Context);
2426 return true;
2427 }
2428
2429 // When we're overloading in C, we allow a special kind of pointer
2430 // conversion for compatible-but-not-identical pointee types.
2431 if (!getLangOpts().CPlusPlus &&
2432 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2433 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2434 ToPointeeType,
2435 ToType, Context);
2436 return true;
2437 }
2438
2439 // C++ [conv.ptr]p3:
2440 //
2441 // An rvalue of type "pointer to cv D," where D is a class type,
2442 // can be converted to an rvalue of type "pointer to cv B," where
2443 // B is a base class (clause 10) of D. If B is an inaccessible
2444 // (clause 11) or ambiguous (10.2) base class of D, a program that
2445 // necessitates this conversion is ill-formed. The result of the
2446 // conversion is a pointer to the base class sub-object of the
2447 // derived class object. The null pointer value is converted to
2448 // the null pointer value of the destination type.
2449 //
2450 // Note that we do not check for ambiguity or inaccessibility
2451 // here. That is handled by CheckPointerConversion.
2452 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2453 ToPointeeType->isRecordType() &&
2454 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2455 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2456 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2457 ToPointeeType,
2458 ToType, Context);
2459 return true;
2460 }
2461
2462 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2463 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2464 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2465 ToPointeeType,
2466 ToType, Context);
2467 return true;
2468 }
2469
2470 return false;
2471}
2472
2473/// Adopt the given qualifiers for the given type.
2474static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2475 Qualifiers TQs = T.getQualifiers();
2476
2477 // Check whether qualifiers already match.
2478 if (TQs == Qs)
2479 return T;
2480
2481 if (Qs.compatiblyIncludes(TQs))
2482 return Context.getQualifiedType(T, Qs);
2483
2484 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2485}
2486
2487/// isObjCPointerConversion - Determines whether this is an
2488/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2489/// with the same arguments and return values.
2490bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2491 QualType& ConvertedType,
2492 bool &IncompatibleObjC) {
2493 if (!getLangOpts().ObjC)
2494 return false;
2495
2496 // The set of qualifiers on the type we're converting from.
2497 Qualifiers FromQualifiers = FromType.getQualifiers();
2498
2499 // First, we handle all conversions on ObjC object pointer types.
2500 const ObjCObjectPointerType* ToObjCPtr =
2501 ToType->getAs<ObjCObjectPointerType>();
2502 const ObjCObjectPointerType *FromObjCPtr =
2503 FromType->getAs<ObjCObjectPointerType>();
2504
2505 if (ToObjCPtr && FromObjCPtr) {
2506 // If the pointee types are the same (ignoring qualifications),
2507 // then this is not a pointer conversion.
2508 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2509 FromObjCPtr->getPointeeType()))
2510 return false;
2511
2512 // Conversion between Objective-C pointers.
2513 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2514 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2515 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2516 if (getLangOpts().CPlusPlus && LHS && RHS &&
2517 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2518 FromObjCPtr->getPointeeType()))
2519 return false;
2520 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2521 ToObjCPtr->getPointeeType(),
2522 ToType, Context);
2523 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2524 return true;
2525 }
2526
2527 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2528 // Okay: this is some kind of implicit downcast of Objective-C
2529 // interfaces, which is permitted. However, we're going to
2530 // complain about it.
2531 IncompatibleObjC = true;
2532 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2533 ToObjCPtr->getPointeeType(),
2534 ToType, Context);
2535 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2536 return true;
2537 }
2538 }
2539 // Beyond this point, both types need to be C pointers or block pointers.
2540 QualType ToPointeeType;
2541 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2542 ToPointeeType = ToCPtr->getPointeeType();
2543 else if (const BlockPointerType *ToBlockPtr =
2544 ToType->getAs<BlockPointerType>()) {
2545 // Objective C++: We're able to convert from a pointer to any object
2546 // to a block pointer type.
2547 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2548 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2549 return true;
2550 }
2551 ToPointeeType = ToBlockPtr->getPointeeType();
2552 }
2553 else if (FromType->getAs<BlockPointerType>() &&
2554 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2555 // Objective C++: We're able to convert from a block pointer type to a
2556 // pointer to any object.
2557 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2558 return true;
2559 }
2560 else
2561 return false;
2562
2563 QualType FromPointeeType;
2564 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2565 FromPointeeType = FromCPtr->getPointeeType();
2566 else if (const BlockPointerType *FromBlockPtr =
2567 FromType->getAs<BlockPointerType>())
2568 FromPointeeType = FromBlockPtr->getPointeeType();
2569 else
2570 return false;
2571
2572 // If we have pointers to pointers, recursively check whether this
2573 // is an Objective-C conversion.
2574 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2575 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2576 IncompatibleObjC)) {
2577 // We always complain about this conversion.
2578 IncompatibleObjC = true;
2579 ConvertedType = Context.getPointerType(ConvertedType);
2580 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2581 return true;
2582 }
2583 // Allow conversion of pointee being objective-c pointer to another one;
2584 // as in I* to id.
2585 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2586 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2587 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2588 IncompatibleObjC)) {
2589
2590 ConvertedType = Context.getPointerType(ConvertedType);
2591 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2592 return true;
2593 }
2594
2595 // If we have pointers to functions or blocks, check whether the only
2596 // differences in the argument and result types are in Objective-C
2597 // pointer conversions. If so, we permit the conversion (but
2598 // complain about it).
2599 const FunctionProtoType *FromFunctionType
2600 = FromPointeeType->getAs<FunctionProtoType>();
2601 const FunctionProtoType *ToFunctionType
2602 = ToPointeeType->getAs<FunctionProtoType>();
2603 if (FromFunctionType && ToFunctionType) {
2604 // If the function types are exactly the same, this isn't an
2605 // Objective-C pointer conversion.
2606 if (Context.getCanonicalType(FromPointeeType)
2607 == Context.getCanonicalType(ToPointeeType))
2608 return false;
2609
2610 // Perform the quick checks that will tell us whether these
2611 // function types are obviously different.
2612 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2613 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2614 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2615 return false;
2616
2617 bool HasObjCConversion = false;
2618 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2619 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2620 // Okay, the types match exactly. Nothing to do.
2621 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2622 ToFunctionType->getReturnType(),
2623 ConvertedType, IncompatibleObjC)) {
2624 // Okay, we have an Objective-C pointer conversion.
2625 HasObjCConversion = true;
2626 } else {
2627 // Function types are too different. Abort.
2628 return false;
2629 }
2630
2631 // Check argument types.
2632 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2633 ArgIdx != NumArgs; ++ArgIdx) {
2634 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2635 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2636 if (Context.getCanonicalType(FromArgType)
2637 == Context.getCanonicalType(ToArgType)) {
2638 // Okay, the types match exactly. Nothing to do.
2639 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2640 ConvertedType, IncompatibleObjC)) {
2641 // Okay, we have an Objective-C pointer conversion.
2642 HasObjCConversion = true;
2643 } else {
2644 // Argument types are too different. Abort.
2645 return false;
2646 }
2647 }
2648
2649 if (HasObjCConversion) {
2650 // We had an Objective-C conversion. Allow this pointer
2651 // conversion, but complain about it.
2652 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2653 IncompatibleObjC = true;
2654 return true;
2655 }
2656 }
2657
2658 return false;
2659}
2660
2661/// Determine whether this is an Objective-C writeback conversion,
2662/// used for parameter passing when performing automatic reference counting.
2663///
2664/// \param FromType The type we're converting form.
2665///
2666/// \param ToType The type we're converting to.
2667///
2668/// \param ConvertedType The type that will be produced after applying
2669/// this conversion.
2670bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2671 QualType &ConvertedType) {
2672 if (!getLangOpts().ObjCAutoRefCount ||
2673 Context.hasSameUnqualifiedType(FromType, ToType))
2674 return false;
2675
2676 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2677 QualType ToPointee;
2678 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2679 ToPointee = ToPointer->getPointeeType();
2680 else
2681 return false;
2682
2683 Qualifiers ToQuals = ToPointee.getQualifiers();
2684 if (!ToPointee->isObjCLifetimeType() ||
2685 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2686 !ToQuals.withoutObjCLifetime().empty())
2687 return false;
2688
2689 // Argument must be a pointer to __strong to __weak.
2690 QualType FromPointee;
2691 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2692 FromPointee = FromPointer->getPointeeType();
2693 else
2694 return false;
2695
2696 Qualifiers FromQuals = FromPointee.getQualifiers();
2697 if (!FromPointee->isObjCLifetimeType() ||
2698 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2699 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2700 return false;
2701
2702 // Make sure that we have compatible qualifiers.
2703 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2704 if (!ToQuals.compatiblyIncludes(FromQuals))
2705 return false;
2706
2707 // Remove qualifiers from the pointee type we're converting from; they
2708 // aren't used in the compatibility check belong, and we'll be adding back
2709 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2710 FromPointee = FromPointee.getUnqualifiedType();
2711
2712 // The unqualified form of the pointee types must be compatible.
2713 ToPointee = ToPointee.getUnqualifiedType();
2714 bool IncompatibleObjC;
2715 if (Context.typesAreCompatible(FromPointee, ToPointee))
2716 FromPointee = ToPointee;
2717 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2718 IncompatibleObjC))
2719 return false;
2720
2721 /// Construct the type we're converting to, which is a pointer to
2722 /// __autoreleasing pointee.
2723 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2724 ConvertedType = Context.getPointerType(FromPointee);
2725 return true;
2726}
2727
2728bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2729 QualType& ConvertedType) {
2730 QualType ToPointeeType;
2731 if (const BlockPointerType *ToBlockPtr =
2732 ToType->getAs<BlockPointerType>())
2733 ToPointeeType = ToBlockPtr->getPointeeType();
2734 else
2735 return false;
2736
2737 QualType FromPointeeType;
2738 if (const BlockPointerType *FromBlockPtr =
2739 FromType->getAs<BlockPointerType>())
2740 FromPointeeType = FromBlockPtr->getPointeeType();
2741 else
2742 return false;
2743 // We have pointer to blocks, check whether the only
2744 // differences in the argument and result types are in Objective-C
2745 // pointer conversions. If so, we permit the conversion.
2746
2747 const FunctionProtoType *FromFunctionType
2748 = FromPointeeType->getAs<FunctionProtoType>();
2749 const FunctionProtoType *ToFunctionType
2750 = ToPointeeType->getAs<FunctionProtoType>();
2751
2752 if (!FromFunctionType || !ToFunctionType)
2753 return false;
2754
2755 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2756 return true;
2757
2758 // Perform the quick checks that will tell us whether these
2759 // function types are obviously different.
2760 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2761 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2762 return false;
2763
2764 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2765 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2766 if (FromEInfo != ToEInfo)
2767 return false;
2768
2769 bool IncompatibleObjC = false;
2770 if (Context.hasSameType(FromFunctionType->getReturnType(),
2771 ToFunctionType->getReturnType())) {
2772 // Okay, the types match exactly. Nothing to do.
2773 } else {
2774 QualType RHS = FromFunctionType->getReturnType();
2775 QualType LHS = ToFunctionType->getReturnType();
2776 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2777 !RHS.hasQualifiers() && LHS.hasQualifiers())
2778 LHS = LHS.getUnqualifiedType();
2779
2780 if (Context.hasSameType(RHS,LHS)) {
2781 // OK exact match.
2782 } else if (isObjCPointerConversion(RHS, LHS,
2783 ConvertedType, IncompatibleObjC)) {
2784 if (IncompatibleObjC)
2785 return false;
2786 // Okay, we have an Objective-C pointer conversion.
2787 }
2788 else
2789 return false;
2790 }
2791
2792 // Check argument types.
2793 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2794 ArgIdx != NumArgs; ++ArgIdx) {
2795 IncompatibleObjC = false;
2796 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2797 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2798 if (Context.hasSameType(FromArgType, ToArgType)) {
2799 // Okay, the types match exactly. Nothing to do.
2800 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2801 ConvertedType, IncompatibleObjC)) {
2802 if (IncompatibleObjC)
2803 return false;
2804 // Okay, we have an Objective-C pointer conversion.
2805 } else
2806 // Argument types are too different. Abort.
2807 return false;
2808 }
2809
2810 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2811 bool CanUseToFPT, CanUseFromFPT;
2812 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2813 CanUseToFPT, CanUseFromFPT,
2814 NewParamInfos))
2815 return false;
2816
2817 ConvertedType = ToType;
2818 return true;
2819}
2820
2821enum {
2822 ft_default,
2823 ft_different_class,
2824 ft_parameter_arity,
2825 ft_parameter_mismatch,
2826 ft_return_type,
2827 ft_qualifer_mismatch,
2828 ft_noexcept
2829};
2830
2831/// Attempts to get the FunctionProtoType from a Type. Handles
2832/// MemberFunctionPointers properly.
2833static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2834 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2835 return FPT;
2836
2837 if (auto *MPT = FromType->getAs<MemberPointerType>())
2838 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2839
2840 return nullptr;
2841}
2842
2843/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2844/// function types. Catches different number of parameter, mismatch in
2845/// parameter types, and different return types.
2846void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2847 QualType FromType, QualType ToType) {
2848 // If either type is not valid, include no extra info.
2849 if (FromType.isNull() || ToType.isNull()) {
2850 PDiag << ft_default;
2851 return;
2852 }
2853
2854 // Get the function type from the pointers.
2855 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2856 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2857 *ToMember = ToType->getAs<MemberPointerType>();
2858 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2859 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2860 << QualType(FromMember->getClass(), 0);
2861 return;
2862 }
2863 FromType = FromMember->getPointeeType();
2864 ToType = ToMember->getPointeeType();
2865 }
2866
2867 if (FromType->isPointerType())
2868 FromType = FromType->getPointeeType();
2869 if (ToType->isPointerType())
2870 ToType = ToType->getPointeeType();
2871
2872 // Remove references.
2873 FromType = FromType.getNonReferenceType();
2874 ToType = ToType.getNonReferenceType();
2875
2876 // Don't print extra info for non-specialized template functions.
2877 if (FromType->isInstantiationDependentType() &&
2878 !FromType->getAs<TemplateSpecializationType>()) {
2879 PDiag << ft_default;
2880 return;
2881 }
2882
2883 // No extra info for same types.
2884 if (Context.hasSameType(FromType, ToType)) {
2885 PDiag << ft_default;
2886 return;
2887 }
2888
2889 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2890 *ToFunction = tryGetFunctionProtoType(ToType);
2891
2892 // Both types need to be function types.
2893 if (!FromFunction || !ToFunction) {
2894 PDiag << ft_default;
2895 return;
2896 }
2897
2898 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2899 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2900 << FromFunction->getNumParams();
2901 return;
2902 }
2903
2904 // Handle different parameter types.
2905 unsigned ArgPos;
2906 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2907 PDiag << ft_parameter_mismatch << ArgPos + 1
2908 << ToFunction->getParamType(ArgPos)
2909 << FromFunction->getParamType(ArgPos);
2910 return;
2911 }
2912
2913 // Handle different return type.
2914 if (!Context.hasSameType(FromFunction->getReturnType(),
2915 ToFunction->getReturnType())) {
2916 PDiag << ft_return_type << ToFunction->getReturnType()
2917 << FromFunction->getReturnType();
2918 return;
2919 }
2920
2921 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2922 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2923 << FromFunction->getMethodQuals();
2924 return;
2925 }
2926
2927 // Handle exception specification differences on canonical type (in C++17
2928 // onwards).
2929 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2930 ->isNothrow() !=
2931 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2932 ->isNothrow()) {
2933 PDiag << ft_noexcept;
2934 return;
2935 }
2936
2937 // Unable to find a difference, so add no extra info.
2938 PDiag << ft_default;
2939}
2940
2941/// FunctionParamTypesAreEqual - This routine checks two function proto types
2942/// for equality of their argument types. Caller has already checked that
2943/// they have same number of arguments. If the parameters are different,
2944/// ArgPos will have the parameter index of the first different parameter.
2945bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2946 const FunctionProtoType *NewType,
2947 unsigned *ArgPos) {
2948 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2949 N = NewType->param_type_begin(),
2950 E = OldType->param_type_end();
2951 O && (O != E); ++O, ++N) {
2952 // Ignore address spaces in pointee type. This is to disallow overloading
2953 // on __ptr32/__ptr64 address spaces.
2954 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2955 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2956
2957 if (!Context.hasSameType(Old, New)) {
2958 if (ArgPos)
2959 *ArgPos = O - OldType->param_type_begin();
2960 return false;
2961 }
2962 }
2963 return true;
2964}
2965
2966/// CheckPointerConversion - Check the pointer conversion from the
2967/// expression From to the type ToType. This routine checks for
2968/// ambiguous or inaccessible derived-to-base pointer
2969/// conversions for which IsPointerConversion has already returned
2970/// true. It returns true and produces a diagnostic if there was an
2971/// error, or returns false otherwise.
2972bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2973 CastKind &Kind,
2974 CXXCastPath& BasePath,
2975 bool IgnoreBaseAccess,
2976 bool Diagnose) {
2977 QualType FromType = From->getType();
2978 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2979
2980 Kind = CK_BitCast;
2981
2982 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2983 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2984 Expr::NPCK_ZeroExpression) {
2985 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2986 DiagRuntimeBehavior(From->getExprLoc(), From,
2987 PDiag(diag::warn_impcast_bool_to_null_pointer)
2988 << ToType << From->getSourceRange());
2989 else if (!isUnevaluatedContext())
2990 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2991 << ToType << From->getSourceRange();
2992 }
2993 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2994 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2995 QualType FromPointeeType = FromPtrType->getPointeeType(),
2996 ToPointeeType = ToPtrType->getPointeeType();
2997
2998 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2999 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3000 // We must have a derived-to-base conversion. Check an
3001 // ambiguous or inaccessible conversion.
3002 unsigned InaccessibleID = 0;
3003 unsigned AmbigiousID = 0;
3004 if (Diagnose) {
3005 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3006 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
3007 }
3008 if (CheckDerivedToBaseConversion(
3009 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
3010 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3011 &BasePath, IgnoreBaseAccess))
3012 return true;
3013
3014 // The conversion was successful.
3015 Kind = CK_DerivedToBase;
3016 }
3017
3018 if (Diagnose && !IsCStyleOrFunctionalCast &&
3019 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3020 assert(getLangOpts().MSVCCompat &&((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3021, __PRETTY_FUNCTION__))
3021 "this should only be possible with MSVCCompat!")((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3021, __PRETTY_FUNCTION__))
;
3022 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3023 << From->getSourceRange();
3024 }
3025 }
3026 } else if (const ObjCObjectPointerType *ToPtrType =
3027 ToType->getAs<ObjCObjectPointerType>()) {
3028 if (const ObjCObjectPointerType *FromPtrType =
3029 FromType->getAs<ObjCObjectPointerType>()) {
3030 // Objective-C++ conversions are always okay.
3031 // FIXME: We should have a different class of conversions for the
3032 // Objective-C++ implicit conversions.
3033 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3034 return false;
3035 } else if (FromType->isBlockPointerType()) {
3036 Kind = CK_BlockPointerToObjCPointerCast;
3037 } else {
3038 Kind = CK_CPointerToObjCPointerCast;
3039 }
3040 } else if (ToType->isBlockPointerType()) {
3041 if (!FromType->isBlockPointerType())
3042 Kind = CK_AnyPointerToBlockPointerCast;
3043 }
3044
3045 // We shouldn't fall into this case unless it's valid for other
3046 // reasons.
3047 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3048 Kind = CK_NullToPointer;
3049
3050 return false;
3051}
3052
3053/// IsMemberPointerConversion - Determines whether the conversion of the
3054/// expression From, which has the (possibly adjusted) type FromType, can be
3055/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3056/// If so, returns true and places the converted type (that might differ from
3057/// ToType in its cv-qualifiers at some level) into ConvertedType.
3058bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3059 QualType ToType,
3060 bool InOverloadResolution,
3061 QualType &ConvertedType) {
3062 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3063 if (!ToTypePtr)
3064 return false;
3065
3066 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3067 if (From->isNullPointerConstant(Context,
3068 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3069 : Expr::NPC_ValueDependentIsNull)) {
3070 ConvertedType = ToType;
3071 return true;
3072 }
3073
3074 // Otherwise, both types have to be member pointers.
3075 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3076 if (!FromTypePtr)
3077 return false;
3078
3079 // A pointer to member of B can be converted to a pointer to member of D,
3080 // where D is derived from B (C++ 4.11p2).
3081 QualType FromClass(FromTypePtr->getClass(), 0);
3082 QualType ToClass(ToTypePtr->getClass(), 0);
3083
3084 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3085 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3086 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3087 ToClass.getTypePtr());
3088 return true;
3089 }
3090
3091 return false;
3092}
3093
3094/// CheckMemberPointerConversion - Check the member pointer conversion from the
3095/// expression From to the type ToType. This routine checks for ambiguous or
3096/// virtual or inaccessible base-to-derived member pointer conversions
3097/// for which IsMemberPointerConversion has already returned true. It returns
3098/// true and produces a diagnostic if there was an error, or returns false
3099/// otherwise.
3100bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3101 CastKind &Kind,
3102 CXXCastPath &BasePath,
3103 bool IgnoreBaseAccess) {
3104 QualType FromType = From->getType();
3105 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3106 if (!FromPtrType) {
3107 // This must be a null pointer to member pointer conversion
3108 assert(From->isNullPointerConstant(Context,((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3110, __PRETTY_FUNCTION__))
3109 Expr::NPC_ValueDependentIsNull) &&((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3110, __PRETTY_FUNCTION__))
3110 "Expr must be null pointer constant!")((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3110, __PRETTY_FUNCTION__))
;
3111 Kind = CK_NullToMemberPointer;
3112 return false;
3113 }
3114
3115 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3116 assert(ToPtrType && "No member pointer cast has a target type "((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3117, __PRETTY_FUNCTION__))
3117 "that is not a member pointer.")((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3117, __PRETTY_FUNCTION__))
;
3118
3119 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3120 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3121
3122 // FIXME: What about dependent types?
3123 assert(FromClass->isRecordType() && "Pointer into non-class.")((FromClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3123, __PRETTY_FUNCTION__))
;
3124 assert(ToClass->isRecordType() && "Pointer into non-class.")((ToClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
;
3125
3126 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3127 /*DetectVirtual=*/true);
3128 bool DerivationOkay =
3129 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3130 assert(DerivationOkay &&((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
3131 "Should not have been called if derivation isn't OK.")((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
;
3132 (void)DerivationOkay;
3133
3134 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3135 getUnqualifiedType())) {
3136 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3137 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3138 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3139 return true;
3140 }
3141
3142 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3143 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3144 << FromClass << ToClass << QualType(VBase, 0)
3145 << From->getSourceRange();
3146 return true;
3147 }
3148
3149 if (!IgnoreBaseAccess)
3150 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3151 Paths.front(),
3152 diag::err_downcast_from_inaccessible_base);
3153
3154 // Must be a base to derived member conversion.
3155 BuildBasePathArray(Paths, BasePath);
3156 Kind = CK_BaseToDerivedMemberPointer;
3157 return false;
3158}
3159
3160/// Determine whether the lifetime conversion between the two given
3161/// qualifiers sets is nontrivial.
3162static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3163 Qualifiers ToQuals) {
3164 // Converting anything to const __unsafe_unretained is trivial.
3165 if (ToQuals.hasConst() &&
3166 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3167 return false;
3168
3169 return true;
3170}
3171
3172/// Perform a single iteration of the loop for checking if a qualification
3173/// conversion is valid.
3174///
3175/// Specifically, check whether any change between the qualifiers of \p
3176/// FromType and \p ToType is permissible, given knowledge about whether every
3177/// outer layer is const-qualified.
3178static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3179 bool CStyle,
3180 bool &PreviousToQualsIncludeConst,
3181 bool &ObjCLifetimeConversion) {
3182 Qualifiers FromQuals = FromType.getQualifiers();
3183 Qualifiers ToQuals = ToType.getQualifiers();
3184
3185 // Ignore __unaligned qualifier if this type is void.
3186 if (ToType.getUnqualifiedType()->isVoidType())
3187 FromQuals.removeUnaligned();
3188
3189 // Objective-C ARC:
3190 // Check Objective-C lifetime conversions.
3191 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3192 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3193 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3194 ObjCLifetimeConversion = true;
3195 FromQuals.removeObjCLifetime();
3196 ToQuals.removeObjCLifetime();
3197 } else {
3198 // Qualification conversions cannot cast between different
3199 // Objective-C lifetime qualifiers.
3200 return false;
3201 }
3202 }
3203
3204 // Allow addition/removal of GC attributes but not changing GC attributes.
3205 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3206 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3207 FromQuals.removeObjCGCAttr();
3208 ToQuals.removeObjCGCAttr();
3209 }
3210
3211 // -- for every j > 0, if const is in cv 1,j then const is in cv
3212 // 2,j, and similarly for volatile.
3213 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3214 return false;
3215
3216 // For a C-style cast, just require the address spaces to overlap.
3217 // FIXME: Does "superset" also imply the representation of a pointer is the
3218 // same? We're assuming that it does here and in compatiblyIncludes.
3219 if (CStyle && !ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3220 !FromQuals.isAddressSpaceSupersetOf(ToQuals))
3221 return false;
3222
3223 // -- if the cv 1,j and cv 2,j are different, then const is in
3224 // every cv for 0 < k < j.
3225 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3226 !PreviousToQualsIncludeConst)
3227 return false;
3228
3229 // Keep track of whether all prior cv-qualifiers in the "to" type
3230 // include const.
3231 PreviousToQualsIncludeConst =
3232 PreviousToQualsIncludeConst && ToQuals.hasConst();
3233 return true;
3234}
3235
3236/// IsQualificationConversion - Determines whether the conversion from
3237/// an rvalue of type FromType to ToType is a qualification conversion
3238/// (C++ 4.4).
3239///
3240/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3241/// when the qualification conversion involves a change in the Objective-C
3242/// object lifetime.
3243bool
3244Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3245 bool CStyle, bool &ObjCLifetimeConversion) {
3246 FromType = Context.getCanonicalType(FromType);
3247 ToType = Context.getCanonicalType(ToType);
3248 ObjCLifetimeConversion = false;
3249
3250 // If FromType and ToType are the same type, this is not a
3251 // qualification conversion.
3252 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3253 return false;
3254
3255 // (C++ 4.4p4):
3256 // A conversion can add cv-qualifiers at levels other than the first
3257 // in multi-level pointers, subject to the following rules: [...]
3258 bool PreviousToQualsIncludeConst = true;
3259 bool UnwrappedAnyPointer = false;
3260 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3261 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3262 PreviousToQualsIncludeConst,
3263 ObjCLifetimeConversion))
3264 return false;
3265 UnwrappedAnyPointer = true;
3266 }
3267
3268 // We are left with FromType and ToType being the pointee types
3269 // after unwrapping the original FromType and ToType the same number
3270 // of times. If we unwrapped any pointers, and if FromType and
3271 // ToType have the same unqualified type (since we checked
3272 // qualifiers above), then this is a qualification conversion.
3273 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3274}
3275
3276/// - Determine whether this is a conversion from a scalar type to an
3277/// atomic type.
3278///
3279/// If successful, updates \c SCS's second and third steps in the conversion
3280/// sequence to finish the conversion.
3281static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3282 bool InOverloadResolution,
3283 StandardConversionSequence &SCS,
3284 bool CStyle) {
3285 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3286 if (!ToAtomic)
3287 return false;
3288
3289 StandardConversionSequence InnerSCS;
3290 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3291 InOverloadResolution, InnerSCS,
3292 CStyle, /*AllowObjCWritebackConversion=*/false))
3293 return false;
3294
3295 SCS.Second = InnerSCS.Second;
3296 SCS.setToType(1, InnerSCS.getToType(1));
3297 SCS.Third = InnerSCS.Third;
3298 SCS.QualificationIncludesObjCLifetime
3299 = InnerSCS.QualificationIncludesObjCLifetime;
3300 SCS.setToType(2, InnerSCS.getToType(2));
3301 return true;
3302}
3303
3304static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3305 CXXConstructorDecl *Constructor,
3306 QualType Type) {
3307 const FunctionProtoType *CtorType =
3308 Constructor->getType()->getAs<FunctionProtoType>();
3309 if (CtorType->getNumParams() > 0) {
3310 QualType FirstArg = CtorType->getParamType(0);
3311 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3312 return true;
3313 }
3314 return false;
3315}
3316
3317static OverloadingResult
3318IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3319 CXXRecordDecl *To,
3320 UserDefinedConversionSequence &User,
3321 OverloadCandidateSet &CandidateSet,
3322 bool AllowExplicit) {
3323 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3324 for (auto *D : S.LookupConstructors(To)) {
3325 auto Info = getConstructorInfo(D);
3326 if (!Info)
3327 continue;
3328
3329 bool Usable = !Info.Constructor->isInvalidDecl() &&
3330 S.isInitListConstructor(Info.Constructor);
3331 if (Usable) {
3332 // If the first argument is (a reference to) the target type,
3333 // suppress conversions.
3334 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3335 S.Context, Info.Constructor, ToType);
3336 if (Info.ConstructorTmpl)
3337 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3338 /*ExplicitArgs*/ nullptr, From,
3339 CandidateSet, SuppressUserConversions,
3340 /*PartialOverloading*/ false,
3341 AllowExplicit);
3342 else
3343 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3344 CandidateSet, SuppressUserConversions,
3345 /*PartialOverloading*/ false, AllowExplicit);
3346 }
3347 }
3348
3349 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3350
3351 OverloadCandidateSet::iterator Best;
3352 switch (auto Result =
3353 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3354 case OR_Deleted:
3355 case OR_Success: {
3356 // Record the standard conversion we used and the conversion function.
3357 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3358 QualType ThisType = Constructor->getThisType();
3359 // Initializer lists don't have conversions as such.
3360 User.Before.setAsIdentityConversion();
3361 User.HadMultipleCandidates = HadMultipleCandidates;
3362 User.ConversionFunction = Constructor;
3363 User.FoundConversionFunction = Best->FoundDecl;
3364 User.After.setAsIdentityConversion();
3365 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3366 User.After.setAllToTypes(ToType);
3367 return Result;
3368 }
3369
3370 case OR_No_Viable_Function:
3371 return OR_No_Viable_Function;
3372 case OR_Ambiguous:
3373 return OR_Ambiguous;
3374 }
3375
3376 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3376)
;
3377}
3378
3379/// Determines whether there is a user-defined conversion sequence
3380/// (C++ [over.ics.user]) that converts expression From to the type
3381/// ToType. If such a conversion exists, User will contain the
3382/// user-defined conversion sequence that performs such a conversion
3383/// and this routine will return true. Otherwise, this routine returns
3384/// false and User is unspecified.
3385///
3386/// \param AllowExplicit true if the conversion should consider C++0x
3387/// "explicit" conversion functions as well as non-explicit conversion
3388/// functions (C++0x [class.conv.fct]p2).
3389///
3390/// \param AllowObjCConversionOnExplicit true if the conversion should
3391/// allow an extra Objective-C pointer conversion on uses of explicit
3392/// constructors. Requires \c AllowExplicit to also be set.
3393static OverloadingResult
3394IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3395 UserDefinedConversionSequence &User,
3396 OverloadCandidateSet &CandidateSet,
3397 bool AllowExplicit,
3398 bool AllowObjCConversionOnExplicit) {
3399 assert(AllowExplicit || !AllowObjCConversionOnExplicit)((AllowExplicit || !AllowObjCConversionOnExplicit) ? static_cast
<void> (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3399, __PRETTY_FUNCTION__))
;
3400 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3401
3402 // Whether we will only visit constructors.
3403 bool ConstructorsOnly = false;
3404
3405 // If the type we are conversion to is a class type, enumerate its
3406 // constructors.
3407 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3408 // C++ [over.match.ctor]p1:
3409 // When objects of class type are direct-initialized (8.5), or
3410 // copy-initialized from an expression of the same or a
3411 // derived class type (8.5), overload resolution selects the
3412 // constructor. [...] For copy-initialization, the candidate
3413 // functions are all the converting constructors (12.3.1) of
3414 // that class. The argument list is the expression-list within
3415 // the parentheses of the initializer.
3416 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3417 (From->getType()->getAs<RecordType>() &&
3418 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3419 ConstructorsOnly = true;
3420
3421 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3422 // We're not going to find any constructors.
3423 } else if (CXXRecordDecl *ToRecordDecl
3424 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3425
3426 Expr **Args = &From;
3427 unsigned NumArgs = 1;
3428 bool ListInitializing = false;
3429 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3430 // But first, see if there is an init-list-constructor that will work.
3431 OverloadingResult Result = IsInitializerListConstructorConversion(
3432 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3433 if (Result != OR_No_Viable_Function)
3434 return Result;
3435 // Never mind.
3436 CandidateSet.clear(
3437 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3438
3439 // If we're list-initializing, we pass the individual elements as
3440 // arguments, not the entire list.
3441 Args = InitList->getInits();
3442 NumArgs = InitList->getNumInits();
3443 ListInitializing = true;
3444 }
3445
3446 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3447 auto Info = getConstructorInfo(D);
3448 if (!Info)
3449 continue;
3450
3451 bool Usable = !Info.Constructor->isInvalidDecl();
3452 if (!ListInitializing)
3453 Usable = Usable && Info.Constructor->isConvertingConstructor(
3454 /*AllowExplicit*/ true);
3455 if (Usable) {
3456 bool SuppressUserConversions = !ConstructorsOnly;
3457 if (SuppressUserConversions && ListInitializing) {
3458 SuppressUserConversions = false;
3459 if (NumArgs == 1) {
3460 // If the first argument is (a reference to) the target type,
3461 // suppress conversions.
3462 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3463 S.Context, Info.Constructor, ToType);
3464 }
3465 }
3466 if (Info.ConstructorTmpl)
3467 S.AddTemplateOverloadCandidate(
3468 Info.ConstructorTmpl, Info.FoundDecl,
3469 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3470 CandidateSet, SuppressUserConversions,
3471 /*PartialOverloading*/ false, AllowExplicit);
3472 else
3473 // Allow one user-defined conversion when user specifies a
3474 // From->ToType conversion via an static cast (c-style, etc).
3475 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3476 llvm::makeArrayRef(Args, NumArgs),
3477 CandidateSet, SuppressUserConversions,
3478 /*PartialOverloading*/ false, AllowExplicit);
3479 }
3480 }
3481 }
3482 }
3483
3484 // Enumerate conversion functions, if we're allowed to.
3485 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3486 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3487 // No conversion functions from incomplete types.
3488 } else if (const RecordType *FromRecordType =
3489 From->getType()->getAs<RecordType>()) {
3490 if (CXXRecordDecl *FromRecordDecl
3491 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3492 // Add all of the conversion functions as candidates.
3493 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3494 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3495 DeclAccessPair FoundDecl = I.getPair();
3496 NamedDecl *D = FoundDecl.getDecl();
3497 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3498 if (isa<UsingShadowDecl>(D))
3499 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3500
3501 CXXConversionDecl *Conv;
3502 FunctionTemplateDecl *ConvTemplate;
3503 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3504 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3505 else
3506 Conv = cast<CXXConversionDecl>(D);
3507
3508 if (ConvTemplate)
3509 S.AddTemplateConversionCandidate(
3510 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3511 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3512 else
3513 S.AddConversionCandidate(
3514 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3515 AllowObjCConversionOnExplicit, AllowExplicit);
3516 }
3517 }
3518 }
3519
3520 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3521
3522 OverloadCandidateSet::iterator Best;
3523 switch (auto Result =
3524 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3525 case OR_Success:
3526 case OR_Deleted:
3527 // Record the standard conversion we used and the conversion function.
3528 if (CXXConstructorDecl *Constructor
3529 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3530 // C++ [over.ics.user]p1:
3531 // If the user-defined conversion is specified by a
3532 // constructor (12.3.1), the initial standard conversion
3533 // sequence converts the source type to the type required by
3534 // the argument of the constructor.
3535 //
3536 QualType ThisType = Constructor->getThisType();
3537 if (isa<InitListExpr>(From)) {
3538 // Initializer lists don't have conversions as such.
3539 User.Before.setAsIdentityConversion();
3540 } else {
3541 if (Best->Conversions[0].isEllipsis())
3542 User.EllipsisConversion = true;
3543 else {
3544 User.Before = Best->Conversions[0].Standard;
3545 User.EllipsisConversion = false;
3546 }
3547 }
3548 User.HadMultipleCandidates = HadMultipleCandidates;
3549 User.ConversionFunction = Constructor;
3550 User.FoundConversionFunction = Best->FoundDecl;
3551 User.After.setAsIdentityConversion();
3552 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3553 User.After.setAllToTypes(ToType);
3554 return Result;
3555 }
3556 if (CXXConversionDecl *Conversion
3557 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3558 // C++ [over.ics.user]p1:
3559 //
3560 // [...] If the user-defined conversion is specified by a
3561 // conversion function (12.3.2), the initial standard
3562 // conversion sequence converts the source type to the
3563 // implicit object parameter of the conversion function.
3564 User.Before = Best->Conversions[0].Standard;
3565 User.HadMultipleCandidates = HadMultipleCandidates;
3566 User.ConversionFunction = Conversion;
3567 User.FoundConversionFunction = Best->FoundDecl;
3568 User.EllipsisConversion = false;
3569
3570 // C++ [over.ics.user]p2:
3571 // The second standard conversion sequence converts the
3572 // result of the user-defined conversion to the target type
3573 // for the sequence. Since an implicit conversion sequence
3574 // is an initialization, the special rules for
3575 // initialization by user-defined conversion apply when
3576 // selecting the best user-defined conversion for a
3577 // user-defined conversion sequence (see 13.3.3 and
3578 // 13.3.3.1).
3579 User.After = Best->FinalConversion;
3580 return Result;
3581 }
3582 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3582)
;
3583
3584 case OR_No_Viable_Function:
3585 return OR_No_Viable_Function;
3586
3587 case OR_Ambiguous:
3588 return OR_Ambiguous;
3589 }
3590
3591 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3591)
;
3592}
3593
3594bool
3595Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3596 ImplicitConversionSequence ICS;
3597 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3598 OverloadCandidateSet::CSK_Normal);
3599 OverloadingResult OvResult =
3600 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3601 CandidateSet, false, false);
3602
3603 if (!(OvResult == OR_Ambiguous ||
3604 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3605 return false;
3606
3607 auto Cands = CandidateSet.CompleteCandidates(
3608 *this,
3609 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3610 From);
3611 if (OvResult == OR_Ambiguous)
3612 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3613 << From->getType() << ToType << From->getSourceRange();
3614 else { // OR_No_Viable_Function && !CandidateSet.empty()
3615 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3616 diag::err_typecheck_nonviable_condition_incomplete,
3617 From->getType(), From->getSourceRange()))
3618 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3619 << false << From->getType() << From->getSourceRange() << ToType;
3620 }
3621
3622 CandidateSet.NoteCandidates(
3623 *this, From, Cands);
3624 return true;
3625}
3626
3627/// Compare the user-defined conversion functions or constructors
3628/// of two user-defined conversion sequences to determine whether any ordering
3629/// is possible.
3630static ImplicitConversionSequence::CompareKind
3631compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3632 FunctionDecl *Function2) {
3633 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3634 return ImplicitConversionSequence::Indistinguishable;
3635
3636 // Objective-C++:
3637 // If both conversion functions are implicitly-declared conversions from
3638 // a lambda closure type to a function pointer and a block pointer,
3639 // respectively, always prefer the conversion to a function pointer,
3640 // because the function pointer is more lightweight and is more likely
3641 // to keep code working.
3642 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3643 if (!Conv1)
3644 return ImplicitConversionSequence::Indistinguishable;
3645
3646 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3647 if (!Conv2)
3648 return ImplicitConversionSequence::Indistinguishable;
3649
3650 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3651 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3652 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3653 if (Block1 != Block2)
3654 return Block1 ? ImplicitConversionSequence::Worse
3655 : ImplicitConversionSequence::Better;
3656 }
3657
3658 return ImplicitConversionSequence::Indistinguishable;
3659}
3660
3661static bool hasDeprecatedStringLiteralToCharPtrConversion(
3662 const ImplicitConversionSequence &ICS) {
3663 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3664 (ICS.isUserDefined() &&
3665 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3666}
3667
3668/// CompareImplicitConversionSequences - Compare two implicit
3669/// conversion sequences to determine whether one is better than the
3670/// other or if they are indistinguishable (C++ 13.3.3.2).
3671static ImplicitConversionSequence::CompareKind
3672CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3673 const ImplicitConversionSequence& ICS1,
3674 const ImplicitConversionSequence& ICS2)
3675{
3676 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3677 // conversion sequences (as defined in 13.3.3.1)
3678 // -- a standard conversion sequence (13.3.3.1.1) is a better
3679 // conversion sequence than a user-defined conversion sequence or
3680 // an ellipsis conversion sequence, and
3681 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3682 // conversion sequence than an ellipsis conversion sequence
3683 // (13.3.3.1.3).
3684 //
3685 // C++0x [over.best.ics]p10:
3686 // For the purpose of ranking implicit conversion sequences as
3687 // described in 13.3.3.2, the ambiguous conversion sequence is
3688 // treated as a user-defined sequence that is indistinguishable
3689 // from any other user-defined conversion sequence.
3690
3691 // String literal to 'char *' conversion has been deprecated in C++03. It has
3692 // been removed from C++11. We still accept this conversion, if it happens at
3693 // the best viable function. Otherwise, this conversion is considered worse
3694 // than ellipsis conversion. Consider this as an extension; this is not in the
3695 // standard. For example:
3696 //
3697 // int &f(...); // #1
3698 // void f(char*); // #2
3699 // void g() { int &r = f("foo"); }
3700 //
3701 // In C++03, we pick #2 as the best viable function.
3702 // In C++11, we pick #1 as the best viable function, because ellipsis
3703 // conversion is better than string-literal to char* conversion (since there
3704 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3705 // convert arguments, #2 would be the best viable function in C++11.
3706 // If the best viable function has this conversion, a warning will be issued
3707 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3708
3709 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3710 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3711 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3712 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3713 ? ImplicitConversionSequence::Worse
3714 : ImplicitConversionSequence::Better;
3715
3716 if (ICS1.getKindRank() < ICS2.getKindRank())
3717 return ImplicitConversionSequence::Better;
3718 if (ICS2.getKindRank() < ICS1.getKindRank())
3719 return ImplicitConversionSequence::Worse;
3720
3721 // The following checks require both conversion sequences to be of
3722 // the same kind.
3723 if (ICS1.getKind() != ICS2.getKind())
3724 return ImplicitConversionSequence::Indistinguishable;
3725
3726 ImplicitConversionSequence::CompareKind Result =
3727 ImplicitConversionSequence::Indistinguishable;
3728
3729 // Two implicit conversion sequences of the same form are
3730 // indistinguishable conversion sequences unless one of the
3731 // following rules apply: (C++ 13.3.3.2p3):
3732
3733 // List-initialization sequence L1 is a better conversion sequence than
3734 // list-initialization sequence L2 if:
3735 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3736 // if not that,
3737 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3738 // and N1 is smaller than N2.,
3739 // even if one of the other rules in this paragraph would otherwise apply.
3740 if (!ICS1.isBad()) {
3741 if (ICS1.isStdInitializerListElement() &&
3742 !ICS2.isStdInitializerListElement())
3743 return ImplicitConversionSequence::Better;
3744 if (!ICS1.isStdInitializerListElement() &&
3745 ICS2.isStdInitializerListElement())
3746 return ImplicitConversionSequence::Worse;
3747 }
3748
3749 if (ICS1.isStandard())
3750 // Standard conversion sequence S1 is a better conversion sequence than
3751 // standard conversion sequence S2 if [...]
3752 Result = CompareStandardConversionSequences(S, Loc,
3753 ICS1.Standard, ICS2.Standard);
3754 else if (ICS1.isUserDefined()) {
3755 // User-defined conversion sequence U1 is a better conversion
3756 // sequence than another user-defined conversion sequence U2 if
3757 // they contain the same user-defined conversion function or
3758 // constructor and if the second standard conversion sequence of
3759 // U1 is better than the second standard conversion sequence of
3760 // U2 (C++ 13.3.3.2p3).
3761 if (ICS1.UserDefined.ConversionFunction ==
3762 ICS2.UserDefined.ConversionFunction)
3763 Result = CompareStandardConversionSequences(S, Loc,
3764 ICS1.UserDefined.After,
3765 ICS2.UserDefined.After);
3766 else
3767 Result = compareConversionFunctions(S,
3768 ICS1.UserDefined.ConversionFunction,
3769 ICS2.UserDefined.ConversionFunction);
3770 }
3771
3772 return Result;
3773}
3774
3775// Per 13.3.3.2p3, compare the given standard conversion sequences to
3776// determine if one is a proper subset of the other.
3777static ImplicitConversionSequence::CompareKind
3778compareStandardConversionSubsets(ASTContext &Context,
3779 const StandardConversionSequence& SCS1,
3780 const StandardConversionSequence& SCS2) {
3781 ImplicitConversionSequence::CompareKind Result
3782 = ImplicitConversionSequence::Indistinguishable;
3783
3784 // the identity conversion sequence is considered to be a subsequence of
3785 // any non-identity conversion sequence
3786 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3787 return ImplicitConversionSequence::Better;
3788 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3789 return ImplicitConversionSequence::Worse;
3790
3791 if (SCS1.Second != SCS2.Second) {
3792 if (SCS1.Second == ICK_Identity)
3793 Result = ImplicitConversionSequence::Better;
3794 else if (SCS2.Second == ICK_Identity)
3795 Result = ImplicitConversionSequence::Worse;
3796 else
3797 return ImplicitConversionSequence::Indistinguishable;
3798 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3799 return ImplicitConversionSequence::Indistinguishable;
3800
3801 if (SCS1.Third == SCS2.Third) {
3802 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3803 : ImplicitConversionSequence::Indistinguishable;
3804 }
3805
3806 if (SCS1.Third == ICK_Identity)
3807 return Result == ImplicitConversionSequence::Worse
3808 ? ImplicitConversionSequence::Indistinguishable
3809 : ImplicitConversionSequence::Better;
3810
3811 if (SCS2.Third == ICK_Identity)
3812 return Result == ImplicitConversionSequence::Better
3813 ? ImplicitConversionSequence::Indistinguishable
3814 : ImplicitConversionSequence::Worse;
3815
3816 return ImplicitConversionSequence::Indistinguishable;
3817}
3818
3819/// Determine whether one of the given reference bindings is better
3820/// than the other based on what kind of bindings they are.
3821static bool
3822isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3823 const StandardConversionSequence &SCS2) {
3824 // C++0x [over.ics.rank]p3b4:
3825 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3826 // implicit object parameter of a non-static member function declared
3827 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3828 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3829 // lvalue reference to a function lvalue and S2 binds an rvalue
3830 // reference*.
3831 //
3832 // FIXME: Rvalue references. We're going rogue with the above edits,
3833 // because the semantics in the current C++0x working paper (N3225 at the
3834 // time of this writing) break the standard definition of std::forward
3835 // and std::reference_wrapper when dealing with references to functions.
3836 // Proposed wording changes submitted to CWG for consideration.
3837 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3838 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3839 return false;
3840
3841 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3842 SCS2.IsLvalueReference) ||
3843 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3844 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3845}
3846
3847enum class FixedEnumPromotion {
3848 None,
3849 ToUnderlyingType,
3850 ToPromotedUnderlyingType
3851};
3852
3853/// Returns kind of fixed enum promotion the \a SCS uses.
3854static FixedEnumPromotion
3855getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3856
3857 if (SCS.Second != ICK_Integral_Promotion)
3858 return FixedEnumPromotion::None;
3859
3860 QualType FromType = SCS.getFromType();
3861 if (!FromType->isEnumeralType())
3862 return FixedEnumPromotion::None;
3863
3864 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3865 if (!Enum->isFixed())
3866 return FixedEnumPromotion::None;
3867
3868 QualType UnderlyingType = Enum->getIntegerType();
3869 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3870 return FixedEnumPromotion::ToUnderlyingType;
3871
3872 return FixedEnumPromotion::ToPromotedUnderlyingType;
3873}
3874
3875/// CompareStandardConversionSequences - Compare two standard
3876/// conversion sequences to determine whether one is better than the
3877/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3878static ImplicitConversionSequence::CompareKind
3879CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3880 const StandardConversionSequence& SCS1,
3881 const StandardConversionSequence& SCS2)
3882{
3883 // Standard conversion sequence S1 is a better conversion sequence
3884 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3885
3886 // -- S1 is a proper subsequence of S2 (comparing the conversion
3887 // sequences in the canonical form defined by 13.3.3.1.1,
3888 // excluding any Lvalue Transformation; the identity conversion
3889 // sequence is considered to be a subsequence of any
3890 // non-identity conversion sequence) or, if not that,
3891 if (ImplicitConversionSequence::CompareKind CK
3892 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3893 return CK;
3894
3895 // -- the rank of S1 is better than the rank of S2 (by the rules
3896 // defined below), or, if not that,
3897 ImplicitConversionRank Rank1 = SCS1.getRank();
3898 ImplicitConversionRank Rank2 = SCS2.getRank();
3899 if (Rank1 < Rank2)
3900 return ImplicitConversionSequence::Better;
3901 else if (Rank2 < Rank1)
3902 return ImplicitConversionSequence::Worse;
3903
3904 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3905 // are indistinguishable unless one of the following rules
3906 // applies:
3907
3908 // A conversion that is not a conversion of a pointer, or
3909 // pointer to member, to bool is better than another conversion
3910 // that is such a conversion.
3911 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3912 return SCS2.isPointerConversionToBool()
3913 ? ImplicitConversionSequence::Better
3914 : ImplicitConversionSequence::Worse;
3915
3916 // C++14 [over.ics.rank]p4b2:
3917 // This is retroactively applied to C++11 by CWG 1601.
3918 //
3919 // A conversion that promotes an enumeration whose underlying type is fixed
3920 // to its underlying type is better than one that promotes to the promoted
3921 // underlying type, if the two are different.
3922 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3923 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3924 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3925 FEP1 != FEP2)
3926 return FEP1 == FixedEnumPromotion::ToUnderlyingType
3927 ? ImplicitConversionSequence::Better
3928 : ImplicitConversionSequence::Worse;
3929
3930 // C++ [over.ics.rank]p4b2:
3931 //
3932 // If class B is derived directly or indirectly from class A,
3933 // conversion of B* to A* is better than conversion of B* to
3934 // void*, and conversion of A* to void* is better than conversion
3935 // of B* to void*.
3936 bool SCS1ConvertsToVoid
3937 = SCS1.isPointerConversionToVoidPointer(S.Context);
3938 bool SCS2ConvertsToVoid
3939 = SCS2.isPointerConversionToVoidPointer(S.Context);
3940 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3941 // Exactly one of the conversion sequences is a conversion to
3942 // a void pointer; it's the worse conversion.
3943 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3944 : ImplicitConversionSequence::Worse;
3945 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3946 // Neither conversion sequence converts to a void pointer; compare
3947 // their derived-to-base conversions.
3948 if (ImplicitConversionSequence::CompareKind DerivedCK
3949 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3950 return DerivedCK;
3951 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3952 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3953 // Both conversion sequences are conversions to void
3954 // pointers. Compare the source types to determine if there's an
3955 // inheritance relationship in their sources.
3956 QualType FromType1 = SCS1.getFromType();
3957 QualType FromType2 = SCS2.getFromType();
3958
3959 // Adjust the types we're converting from via the array-to-pointer
3960 // conversion, if we need to.
3961 if (SCS1.First == ICK_Array_To_Pointer)
3962 FromType1 = S.Context.getArrayDecayedType(FromType1);
3963 if (SCS2.First == ICK_Array_To_Pointer)
3964 FromType2 = S.Context.getArrayDecayedType(FromType2);
3965
3966 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3967 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3968
3969 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3970 return ImplicitConversionSequence::Better;
3971 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3972 return ImplicitConversionSequence::Worse;
3973
3974 // Objective-C++: If one interface is more specific than the
3975 // other, it is the better one.
3976 const ObjCObjectPointerType* FromObjCPtr1
3977 = FromType1->getAs<ObjCObjectPointerType>();
3978 const ObjCObjectPointerType* FromObjCPtr2
3979 = FromType2->getAs<ObjCObjectPointerType>();
3980 if (FromObjCPtr1 && FromObjCPtr2) {
3981 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3982 FromObjCPtr2);
3983 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3984 FromObjCPtr1);
3985 if (AssignLeft != AssignRight) {
3986 return AssignLeft? ImplicitConversionSequence::Better
3987 : ImplicitConversionSequence::Worse;
3988 }
3989 }
3990 }
3991
3992 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3993 // Check for a better reference binding based on the kind of bindings.
3994 if (isBetterReferenceBindingKind(SCS1, SCS2))
3995 return ImplicitConversionSequence::Better;
3996 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3997 return ImplicitConversionSequence::Worse;
3998 }
3999
4000 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4001 // bullet 3).
4002 if (ImplicitConversionSequence::CompareKind QualCK
4003 = CompareQualificationConversions(S, SCS1, SCS2))
4004 return QualCK;
4005
4006 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4007 // C++ [over.ics.rank]p3b4:
4008 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4009 // which the references refer are the same type except for
4010 // top-level cv-qualifiers, and the type to which the reference
4011 // initialized by S2 refers is more cv-qualified than the type
4012 // to which the reference initialized by S1 refers.
4013 QualType T1 = SCS1.getToType(2);
4014 QualType T2 = SCS2.getToType(2);
4015 T1 = S.Context.getCanonicalType(T1);
4016 T2 = S.Context.getCanonicalType(T2);
4017 Qualifiers T1Quals, T2Quals;
4018 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4019 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4020 if (UnqualT1 == UnqualT2) {
4021 // Objective-C++ ARC: If the references refer to objects with different
4022 // lifetimes, prefer bindings that don't change lifetime.
4023 if (SCS1.ObjCLifetimeConversionBinding !=
4024 SCS2.ObjCLifetimeConversionBinding) {
4025 return SCS1.ObjCLifetimeConversionBinding
4026 ? ImplicitConversionSequence::Worse
4027 : ImplicitConversionSequence::Better;
4028 }
4029
4030 // If the type is an array type, promote the element qualifiers to the
4031 // type for comparison.
4032 if (isa<ArrayType>(T1) && T1Quals)
4033 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4034 if (isa<ArrayType>(T2) && T2Quals)
4035 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4036 if (T2.isMoreQualifiedThan(T1))
4037 return ImplicitConversionSequence::Better;
4038 if (T1.isMoreQualifiedThan(T2))
4039 return ImplicitConversionSequence::Worse;
4040 }
4041 }
4042
4043 // In Microsoft mode, prefer an integral conversion to a
4044 // floating-to-integral conversion if the integral conversion
4045 // is between types of the same size.
4046 // For example:
4047 // void f(float);
4048 // void f(int);
4049 // int main {
4050 // long a;
4051 // f(a);
4052 // }
4053 // Here, MSVC will call f(int) instead of generating a compile error
4054 // as clang will do in standard mode.
4055 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4056 SCS2.Second == ICK_Floating_Integral &&
4057 S.Context.getTypeSize(SCS1.getFromType()) ==
4058 S.Context.getTypeSize(SCS1.getToType(2)))
4059 return ImplicitConversionSequence::Better;
4060
4061 // Prefer a compatible vector conversion over a lax vector conversion
4062 // For example:
4063 //
4064 // typedef float __v4sf __attribute__((__vector_size__(16)));
4065 // void f(vector float);
4066 // void f(vector signed int);
4067 // int main() {
4068 // __v4sf a;
4069 // f(a);
4070 // }
4071 // Here, we'd like to choose f(vector float) and not
4072 // report an ambiguous call error
4073 if (SCS1.Second == ICK_Vector_Conversion &&
4074 SCS2.Second == ICK_Vector_Conversion) {
4075 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4076 SCS1.getFromType(), SCS1.getToType(2));
4077 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4078 SCS2.getFromType(), SCS2.getToType(2));
4079
4080 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4081 return SCS1IsCompatibleVectorConversion
4082 ? ImplicitConversionSequence::Better
4083 : ImplicitConversionSequence::Worse;
4084 }
4085
4086 return ImplicitConversionSequence::Indistinguishable;
4087}
4088
4089/// CompareQualificationConversions - Compares two standard conversion
4090/// sequences to determine whether they can be ranked based on their
4091/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4092static ImplicitConversionSequence::CompareKind
4093CompareQualificationConversions(Sema &S,
4094 const StandardConversionSequence& SCS1,
4095 const StandardConversionSequence& SCS2) {
4096 // C++ 13.3.3.2p3:
4097 // -- S1 and S2 differ only in their qualification conversion and
4098 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
4099 // cv-qualification signature of type T1 is a proper subset of
4100 // the cv-qualification signature of type T2, and S1 is not the
4101 // deprecated string literal array-to-pointer conversion (4.2).
4102 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4103 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4104 return ImplicitConversionSequence::Indistinguishable;
4105
4106 // FIXME: the example in the standard doesn't use a qualification
4107 // conversion (!)
4108 QualType T1 = SCS1.getToType(2);
4109 QualType T2 = SCS2.getToType(2);
4110 T1 = S.Context.getCanonicalType(T1);
4111 T2 = S.Context.getCanonicalType(T2);
4112 assert(!T1->isReferenceType() && !T2->isReferenceType())((!T1->isReferenceType() && !T2->isReferenceType
()) ? static_cast<void> (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4112, __PRETTY_FUNCTION__))
;
4113 Qualifiers T1Quals, T2Quals;
4114 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4115 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4116
4117 // If the types are the same, we won't learn anything by unwrapping
4118 // them.
4119 if (UnqualT1 == UnqualT2)
4120 return ImplicitConversionSequence::Indistinguishable;
4121
4122 ImplicitConversionSequence::CompareKind Result
4123 = ImplicitConversionSequence::Indistinguishable;
4124
4125 // Objective-C++ ARC:
4126 // Prefer qualification conversions not involving a change in lifetime
4127 // to qualification conversions that do not change lifetime.
4128 if (SCS1.QualificationIncludesObjCLifetime !=
4129 SCS2.QualificationIncludesObjCLifetime) {
4130 Result = SCS1.QualificationIncludesObjCLifetime
4131 ? ImplicitConversionSequence::Worse
4132 : ImplicitConversionSequence::Better;
4133 }
4134
4135 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4136 // Within each iteration of the loop, we check the qualifiers to
4137 // determine if this still looks like a qualification
4138 // conversion. Then, if all is well, we unwrap one more level of
4139 // pointers or pointers-to-members and do it all again
4140 // until there are no more pointers or pointers-to-members left
4141 // to unwrap. This essentially mimics what
4142 // IsQualificationConversion does, but here we're checking for a
4143 // strict subset of qualifiers.
4144 if (T1.getQualifiers().withoutObjCLifetime() ==
4145 T2.getQualifiers().withoutObjCLifetime())
4146 // The qualifiers are the same, so this doesn't tell us anything
4147 // about how the sequences rank.
4148 // ObjC ownership quals are omitted above as they interfere with
4149 // the ARC overload rule.
4150 ;
4151 else if (T2.isMoreQualifiedThan(T1)) {
4152 // T1 has fewer qualifiers, so it could be the better sequence.
4153 if (Result == ImplicitConversionSequence::Worse)
4154 // Neither has qualifiers that are a subset of the other's
4155 // qualifiers.
4156 return ImplicitConversionSequence::Indistinguishable;
4157
4158 Result = ImplicitConversionSequence::Better;
4159 } else if (T1.isMoreQualifiedThan(T2)) {
4160 // T2 has fewer qualifiers, so it could be the better sequence.
4161 if (Result == ImplicitConversionSequence::Better)
4162 // Neither has qualifiers that are a subset of the other's
4163 // qualifiers.
4164 return ImplicitConversionSequence::Indistinguishable;
4165
4166 Result = ImplicitConversionSequence::Worse;
4167 } else {
4168 // Qualifiers are disjoint.
4169 return ImplicitConversionSequence::Indistinguishable;
4170 }
4171
4172 // If the types after this point are equivalent, we're done.
4173 if (S.Context.hasSameUnqualifiedType(T1, T2))
4174 break;
4175 }
4176
4177 // Check that the winning standard conversion sequence isn't using
4178 // the deprecated string literal array to pointer conversion.
4179 switch (Result) {
4180 case ImplicitConversionSequence::Better:
4181 if (SCS1.DeprecatedStringLiteralToCharPtr)
4182 Result = ImplicitConversionSequence::Indistinguishable;
4183 break;
4184
4185 case ImplicitConversionSequence::Indistinguishable:
4186 break;
4187
4188 case ImplicitConversionSequence::Worse:
4189 if (SCS2.DeprecatedStringLiteralToCharPtr)
4190 Result = ImplicitConversionSequence::Indistinguishable;
4191 break;
4192 }
4193
4194 return Result;
4195}
4196
4197/// CompareDerivedToBaseConversions - Compares two standard conversion
4198/// sequences to determine whether they can be ranked based on their
4199/// various kinds of derived-to-base conversions (C++
4200/// [over.ics.rank]p4b3). As part of these checks, we also look at
4201/// conversions between Objective-C interface types.
4202static ImplicitConversionSequence::CompareKind
4203CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4204 const StandardConversionSequence& SCS1,
4205 const StandardConversionSequence& SCS2) {
4206 QualType FromType1 = SCS1.getFromType();
4207 QualType ToType1 = SCS1.getToType(1);
4208 QualType FromType2 = SCS2.getFromType();
4209 QualType ToType2 = SCS2.getToType(1);
4210
4211 // Adjust the types we're converting from via the array-to-pointer
4212 // conversion, if we need to.
4213 if (SCS1.First == ICK_Array_To_Pointer)
1
Assuming field 'First' is not equal to ICK_Array_To_Pointer
2
Taking false branch
4214 FromType1 = S.Context.getArrayDecayedType(FromType1);
4215 if (SCS2.First == ICK_Array_To_Pointer)
3
Assuming field 'First' is not equal to ICK_Array_To_Pointer
4
Taking false branch
4216 FromType2 = S.Context.getArrayDecayedType(FromType2);
4217
4218 // Canonicalize all of the types.
4219 FromType1 = S.Context.getCanonicalType(FromType1);
4220 ToType1 = S.Context.getCanonicalType(ToType1);
4221 FromType2 = S.Context.getCanonicalType(FromType2);
4222 ToType2 = S.Context.getCanonicalType(ToType2);
4223
4224 // C++ [over.ics.rank]p4b3:
4225 //
4226 // If class B is derived directly or indirectly from class A and
4227 // class C is derived directly or indirectly from B,
4228 //
4229 // Compare based on pointer conversions.
4230 if (SCS1.Second == ICK_Pointer_Conversion &&
5
Assuming field 'Second' is not equal to ICK_Pointer_Conversion
4231 SCS2.Second == ICK_Pointer_Conversion &&
4232 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4233 FromType1->isPointerType() && FromType2->isPointerType() &&
4234 ToType1->isPointerType() && ToType2->isPointerType()) {
4235 QualType FromPointee1 =
4236 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4237 QualType ToPointee1 =
4238 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4239 QualType FromPointee2 =
4240 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4241 QualType ToPointee2 =
4242 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4243
4244 // -- conversion of C* to B* is better than conversion of C* to A*,
4245 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4246 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4247 return ImplicitConversionSequence::Better;
4248 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4249 return ImplicitConversionSequence::Worse;
4250 }
4251
4252 // -- conversion of B* to A* is better than conversion of C* to A*,
4253 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4254 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4255 return ImplicitConversionSequence::Better;
4256 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4257 return ImplicitConversionSequence::Worse;
4258 }
4259 } else if (SCS1.Second
5.1
Field 'Second' is not equal to ICK_Pointer_Conversion
5.1
Field 'Second' is not equal to ICK_Pointer_Conversion
== ICK_Pointer_Conversion &&
4260 SCS2.Second == ICK_Pointer_Conversion) {
4261 const ObjCObjectPointerType *FromPtr1
4262 = FromType1->getAs<ObjCObjectPointerType>();
4263 const ObjCObjectPointerType *FromPtr2
4264 = FromType2->getAs<ObjCObjectPointerType>();
4265 const ObjCObjectPointerType *ToPtr1
4266 = ToType1->getAs<ObjCObjectPointerType>();
4267 const ObjCObjectPointerType *ToPtr2
4268 = ToType2->getAs<ObjCObjectPointerType>();
4269
4270 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4271 // Apply the same conversion ranking rules for Objective-C pointer types
4272 // that we do for C++ pointers to class types. However, we employ the
4273 // Objective-C pseudo-subtyping relationship used for assignment of
4274 // Objective-C pointer types.
4275 bool FromAssignLeft
4276 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4277 bool FromAssignRight
4278 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4279 bool ToAssignLeft
4280 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4281 bool ToAssignRight
4282 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4283
4284 // A conversion to an a non-id object pointer type or qualified 'id'
4285 // type is better than a conversion to 'id'.
4286 if (ToPtr1->isObjCIdType() &&
4287 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4288 return ImplicitConversionSequence::Worse;
4289 if (ToPtr2->isObjCIdType() &&
4290 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4291 return ImplicitConversionSequence::Better;
4292
4293 // A conversion to a non-id object pointer type is better than a
4294 // conversion to a qualified 'id' type
4295 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4296 return ImplicitConversionSequence::Worse;
4297 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4298 return ImplicitConversionSequence::Better;
4299
4300 // A conversion to an a non-Class object pointer type or qualified 'Class'
4301 // type is better than a conversion to 'Class'.
4302 if (ToPtr1->isObjCClassType() &&
4303 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4304 return ImplicitConversionSequence::Worse;
4305 if (ToPtr2->isObjCClassType() &&
4306 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4307 return ImplicitConversionSequence::Better;
4308
4309 // A conversion to a non-Class object pointer type is better than a
4310 // conversion to a qualified 'Class' type.
4311 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4312 return ImplicitConversionSequence::Worse;
4313 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4314 return ImplicitConversionSequence::Better;
4315
4316 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4317 if (S.Context.hasSameType(FromType1, FromType2) &&
4318 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4319 (ToAssignLeft != ToAssignRight)) {
4320 if (FromPtr1->isSpecialized()) {
4321 // "conversion of B<A> * to B * is better than conversion of B * to
4322 // C *.
4323 bool IsFirstSame =
4324 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4325 bool IsSecondSame =
4326 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4327 if (IsFirstSame) {
4328 if (!IsSecondSame)
4329 return ImplicitConversionSequence::Better;
4330 } else if (IsSecondSame)
4331 return ImplicitConversionSequence::Worse;
4332 }
4333 return ToAssignLeft? ImplicitConversionSequence::Worse
4334 : ImplicitConversionSequence::Better;
4335 }
4336
4337 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4338 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4339 (FromAssignLeft != FromAssignRight))
4340 return FromAssignLeft? ImplicitConversionSequence::Better
4341 : ImplicitConversionSequence::Worse;
4342 }
4343 }
4344
4345 // Ranking of member-pointer types.
4346 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
6
Assuming field 'Second' is equal to ICK_Pointer_Member
7
Assuming field 'Second' is equal to ICK_Pointer_Member
24
Taking true branch
4347 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
8
Calling 'Type::isMemberPointerType'
11
Returning from 'Type::isMemberPointerType'
12
Calling 'Type::isMemberPointerType'
15
Returning from 'Type::isMemberPointerType'
4348 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
16
Calling 'Type::isMemberPointerType'
19
Returning from 'Type::isMemberPointerType'
20
Calling 'Type::isMemberPointerType'
23
Returning from 'Type::isMemberPointerType'
4349 const MemberPointerType * FromMemPointer1 =
4350 FromType1->getAs<MemberPointerType>();
25
Assuming the object is a 'MemberPointerType'
4351 const MemberPointerType * ToMemPointer1 =
27
'ToMemPointer1' initialized to a null pointer value
4352 ToType1->getAs<MemberPointerType>();
26
Assuming the object is not a 'MemberPointerType'
4353 const MemberPointerType * FromMemPointer2 =
4354 FromType2->getAs<MemberPointerType>();
28
Assuming the object is not a 'MemberPointerType'
4355 const MemberPointerType * ToMemPointer2 =
4356 ToType2->getAs<MemberPointerType>();
29
Assuming the object is not a 'MemberPointerType'
4357 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4358 const Type *ToPointeeType1 = ToMemPointer1->getClass();
30
Called C++ object pointer is null
4359 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4360 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4361 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4362 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4363 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4364 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4365 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4366 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4367 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4368 return ImplicitConversionSequence::Worse;
4369 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4370 return ImplicitConversionSequence::Better;
4371 }
4372 // conversion of B::* to C::* is better than conversion of A::* to C::*
4373 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4374 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4375 return ImplicitConversionSequence::Better;
4376 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4377 return ImplicitConversionSequence::Worse;
4378 }
4379 }
4380
4381 if (SCS1.Second == ICK_Derived_To_Base) {
4382 // -- conversion of C to B is better than conversion of C to A,
4383 // -- binding of an expression of type C to a reference of type
4384 // B& is better than binding an expression of type C to a
4385 // reference of type A&,
4386 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4387 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4388 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4389 return ImplicitConversionSequence::Better;
4390 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4391 return ImplicitConversionSequence::Worse;
4392 }
4393
4394 // -- conversion of B to A is better than conversion of C to A.
4395 // -- binding of an expression of type B to a reference of type
4396 // A& is better than binding an expression of type C to a
4397 // reference of type A&,
4398 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4399 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4400 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4401 return ImplicitConversionSequence::Better;
4402 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4403 return ImplicitConversionSequence::Worse;
4404 }
4405 }
4406
4407 return ImplicitConversionSequence::Indistinguishable;
4408}
4409
4410/// Determine whether the given type is valid, e.g., it is not an invalid
4411/// C++ class.
4412static bool isTypeValid(QualType T) {
4413 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4414 return !Record->isInvalidDecl();
4415
4416 return true;
4417}
4418
4419static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4420 if (!T.getQualifiers().hasUnaligned())
4421 return T;
4422
4423 Qualifiers Q;
4424 T = Ctx.getUnqualifiedArrayType(T, Q);
4425 Q.removeUnaligned();
4426 return Ctx.getQualifiedType(T, Q);
4427}
4428
4429/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4430/// determine whether they are reference-compatible,
4431/// reference-related, or incompatible, for use in C++ initialization by
4432/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4433/// type, and the first type (T1) is the pointee type of the reference
4434/// type being initialized.
4435Sema::ReferenceCompareResult
4436Sema::CompareReferenceRelationship(SourceLocation Loc,
4437 QualType OrigT1, QualType OrigT2,
4438 ReferenceConversions *ConvOut) {
4439 assert(!OrigT1->isReferenceType() &&((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4440, __PRETTY_FUNCTION__))
4440 "T1 must be the pointee type of the reference type")((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4440, __PRETTY_FUNCTION__))
;
4441 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")((!OrigT2->isReferenceType() && "T2 cannot be a reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4441, __PRETTY_FUNCTION__))
;
4442
4443 QualType T1 = Context.getCanonicalType(OrigT1);
4444 QualType T2 = Context.getCanonicalType(OrigT2);
4445 Qualifiers T1Quals, T2Quals;
4446 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4447 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4448
4449 ReferenceConversions ConvTmp;
4450 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4451 Conv = ReferenceConversions();
4452
4453 // C++2a [dcl.init.ref]p4:
4454 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4455 // reference-related to "cv2 T2" if T1 is similar to T2, or
4456 // T1 is a base class of T2.
4457 // "cv1 T1" is reference-compatible with "cv2 T2" if
4458 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4459 // "pointer to cv1 T1" via a standard conversion sequence.
4460
4461 // Check for standard conversions we can apply to pointers: derived-to-base
4462 // conversions, ObjC pointer conversions, and function pointer conversions.
4463 // (Qualification conversions are checked last.)
4464 QualType ConvertedT2;
4465 if (UnqualT1 == UnqualT2) {
4466 // Nothing to do.
4467 } else if (isCompleteType(Loc, OrigT2) &&
4468 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4469 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4470 Conv |= ReferenceConversions::DerivedToBase;
4471 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4472 UnqualT2->isObjCObjectOrInterfaceType() &&
4473 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4474 Conv |= ReferenceConversions::ObjC;
4475 else if (UnqualT2->isFunctionType() &&
4476 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4477 Conv |= ReferenceConversions::Function;
4478 // No need to check qualifiers; function types don't have them.
4479 return Ref_Compatible;
4480 }
4481 bool ConvertedReferent = Conv != 0;
4482
4483 // We can have a qualification conversion. Compute whether the types are
4484 // similar at the same time.
4485 bool PreviousToQualsIncludeConst = true;
4486 bool TopLevel = true;
4487 do {
4488 if (T1 == T2)
4489 break;
4490
4491 // We will need a qualification conversion.
4492 Conv |= ReferenceConversions::Qualification;
4493
4494 // Track whether we performed a qualification conversion anywhere other
4495 // than the top level. This matters for ranking reference bindings in
4496 // overload resolution.
4497 if (!TopLevel)
4498 Conv |= ReferenceConversions::NestedQualification;
4499
4500 // MS compiler ignores __unaligned qualifier for references; do the same.
4501 T1 = withoutUnaligned(Context, T1);
4502 T2 = withoutUnaligned(Context, T2);
4503
4504 // If we find a qualifier mismatch, the types are not reference-compatible,
4505 // but are still be reference-related if they're similar.
4506 bool ObjCLifetimeConversion = false;
4507 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false,
4508 PreviousToQualsIncludeConst,
4509 ObjCLifetimeConversion))
4510 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4511 ? Ref_Related
4512 : Ref_Incompatible;
4513
4514 // FIXME: Should we track this for any level other than the first?
4515 if (ObjCLifetimeConversion)
4516 Conv |= ReferenceConversions::ObjCLifetime;
4517
4518 TopLevel = false;
4519 } while (Context.UnwrapSimilarTypes(T1, T2));
4520
4521 // At this point, if the types are reference-related, we must either have the
4522 // same inner type (ignoring qualifiers), or must have already worked out how
4523 // to convert the referent.
4524 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4525 ? Ref_Compatible
4526 : Ref_Incompatible;
4527}
4528
4529/// Look for a user-defined conversion to a value reference-compatible
4530/// with DeclType. Return true if something definite is found.
4531static bool
4532FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4533 QualType DeclType, SourceLocation DeclLoc,
4534 Expr *Init, QualType T2, bool AllowRvalues,
4535 bool AllowExplicit) {
4536 assert(T2->isRecordType() && "Can only find conversions of record types.")((T2->isRecordType() && "Can only find conversions of record types."
) ? static_cast<void> (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4536, __PRETTY_FUNCTION__))
;
4537 CXXRecordDecl *T2RecordDecl
4538 = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4539
4540 OverloadCandidateSet CandidateSet(
4541 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4542 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4543 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4544 NamedDecl *D = *I;
4545 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4546 if (isa<UsingShadowDecl>(D))
4547 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4548
4549 FunctionTemplateDecl *ConvTemplate
4550 = dyn_cast<FunctionTemplateDecl>(D);
4551 CXXConversionDecl *Conv;
4552 if (ConvTemplate)
4553 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4554 else
4555 Conv = cast<CXXConversionDecl>(D);
4556
4557 if (AllowRvalues) {
4558 // If we are initializing an rvalue reference, don't permit conversion
4559 // functions that return lvalues.
4560 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4561 const ReferenceType *RefType
4562 = Conv->getConversionType()->getAs<LValueReferenceType>();
4563 if (RefType && !RefType->getPointeeType()->isFunctionType())
4564 continue;
4565 }
4566
4567 if (!ConvTemplate &&
4568 S.CompareReferenceRelationship(
4569 DeclLoc,
4570 Conv->getConversionType()
4571 .getNonReferenceType()
4572 .getUnqualifiedType(),
4573 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4574 Sema::Ref_Incompatible)
4575 continue;
4576 } else {
4577 // If the conversion function doesn't return a reference type,
4578 // it can't be considered for this conversion. An rvalue reference
4579 // is only acceptable if its referencee is a function type.
4580
4581 const ReferenceType *RefType =
4582 Conv->getConversionType()->getAs<ReferenceType>();
4583 if (!RefType ||
4584 (!RefType->isLValueReferenceType() &&
4585 !RefType->getPointeeType()->isFunctionType()))
4586 continue;
4587 }
4588
4589 if (ConvTemplate)
4590 S.AddTemplateConversionCandidate(
4591 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4592 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4593 else
4594 S.AddConversionCandidate(
4595 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4596 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4597 }
4598
4599 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4600
4601 OverloadCandidateSet::iterator Best;
4602 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4603 case OR_Success:
4604 // C++ [over.ics.ref]p1:
4605 //
4606 // [...] If the parameter binds directly to the result of
4607 // applying a conversion function to the argument
4608 // expression, the implicit conversion sequence is a
4609 // user-defined conversion sequence (13.3.3.1.2), with the
4610 // second standard conversion sequence either an identity
4611 // conversion or, if the conversion function returns an
4612 // entity of a type that is a derived class of the parameter
4613 // type, a derived-to-base Conversion.
4614 if (!Best->FinalConversion.DirectBinding)
4615 return false;
4616
4617 ICS.setUserDefined();
4618 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4619 ICS.UserDefined.After = Best->FinalConversion;
4620 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4621 ICS.UserDefined.ConversionFunction = Best->Function;
4622 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4623 ICS.UserDefined.EllipsisConversion = false;
4624 assert(ICS.UserDefined.After.ReferenceBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4626, __PRETTY_FUNCTION__))
4625 ICS.UserDefined.After.DirectBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4626, __PRETTY_FUNCTION__))
4626 "Expected a direct reference binding!")((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4626, __PRETTY_FUNCTION__))
;
4627 return true;
4628
4629 case OR_Ambiguous:
4630 ICS.setAmbiguous();
4631 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4632 Cand != CandidateSet.end(); ++Cand)
4633 if (Cand->Best)
4634 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4635 return true;
4636
4637 case OR_No_Viable_Function:
4638 case OR_Deleted:
4639 // There was no suitable conversion, or we found a deleted
4640 // conversion; continue with other checks.
4641 return false;
4642 }
4643
4644 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4644)
;
4645}
4646
4647/// Compute an implicit conversion sequence for reference
4648/// initialization.
4649static ImplicitConversionSequence
4650TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4651 SourceLocation DeclLoc,
4652 bool SuppressUserConversions,
4653 bool AllowExplicit) {
4654 assert(DeclType->isReferenceType() && "Reference init needs a reference")((DeclType->isReferenceType() && "Reference init needs a reference"
) ? static_cast<void> (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4654, __PRETTY_FUNCTION__))
;
4655
4656 // Most paths end in a failed conversion.
4657 ImplicitConversionSequence ICS;
4658 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4659
4660 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4661 QualType T2 = Init->getType();
4662
4663 // If the initializer is the address of an overloaded function, try
4664 // to resolve the overloaded function. If all goes well, T2 is the
4665 // type of the resulting function.
4666 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4667 DeclAccessPair Found;
4668 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4669 false, Found))
4670 T2 = Fn->getType();
4671 }
4672
4673 // Compute some basic properties of the types and the initializer.
4674 bool isRValRef = DeclType->isRValueReferenceType();
4675 Expr::Classification InitCategory = Init->Classify(S.Context);
4676
4677 Sema::ReferenceConversions RefConv;
4678 Sema::ReferenceCompareResult RefRelationship =
4679 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4680
4681 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4682 ICS.setStandard();
4683 ICS.Standard.First = ICK_Identity;
4684 // FIXME: A reference binding can be a function conversion too. We should
4685 // consider that when ordering reference-to-function bindings.
4686 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4687 ? ICK_Derived_To_Base
4688 : (RefConv & Sema::ReferenceConversions::ObjC)
4689 ? ICK_Compatible_Conversion
4690 : ICK_Identity;
4691 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4692 // a reference binding that performs a non-top-level qualification
4693 // conversion as a qualification conversion, not as an identity conversion.
4694 ICS.Standard.Third = (RefConv &
4695 Sema::ReferenceConversions::NestedQualification)
4696 ? ICK_Qualification
4697 : ICK_Identity;
4698 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4699 ICS.Standard.setToType(0, T2);
4700 ICS.Standard.setToType(1, T1);
4701 ICS.Standard.setToType(2, T1);
4702 ICS.Standard.ReferenceBinding = true;
4703 ICS.Standard.DirectBinding = BindsDirectly;
4704 ICS.Standard.IsLvalueReference = !isRValRef;
4705 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4706 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4707 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4708 ICS.Standard.ObjCLifetimeConversionBinding =
4709 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4710 ICS.Standard.CopyConstructor = nullptr;
4711 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4712 };
4713
4714 // C++0x [dcl.init.ref]p5:
4715 // A reference to type "cv1 T1" is initialized by an expression
4716 // of type "cv2 T2" as follows:
4717
4718 // -- If reference is an lvalue reference and the initializer expression
4719 if (!isRValRef) {
4720 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4721 // reference-compatible with "cv2 T2," or
4722 //
4723 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4724 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4725 // C++ [over.ics.ref]p1:
4726 // When a parameter of reference type binds directly (8.5.3)
4727 // to an argument expression, the implicit conversion sequence
4728 // is the identity conversion, unless the argument expression
4729 // has a type that is a derived class of the parameter type,
4730 // in which case the implicit conversion sequence is a
4731 // derived-to-base Conversion (13.3.3.1).
4732 SetAsReferenceBinding(/*BindsDirectly=*/true);
4733
4734 // Nothing more to do: the inaccessibility/ambiguity check for
4735 // derived-to-base conversions is suppressed when we're
4736 // computing the implicit conversion sequence (C++
4737 // [over.best.ics]p2).
4738 return ICS;
4739 }
4740
4741 // -- has a class type (i.e., T2 is a class type), where T1 is
4742 // not reference-related to T2, and can be implicitly
4743 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4744 // is reference-compatible with "cv3 T3" 92) (this
4745 // conversion is selected by enumerating the applicable
4746 // conversion functions (13.3.1.6) and choosing the best
4747 // one through overload resolution (13.3)),
4748 if (!SuppressUserConversions && T2->isRecordType() &&
4749 S.isCompleteType(DeclLoc, T2) &&
4750 RefRelationship == Sema::Ref_Incompatible) {
4751 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4752 Init, T2, /*AllowRvalues=*/false,
4753 AllowExplicit))
4754 return ICS;
4755 }
4756 }
4757
4758 // -- Otherwise, the reference shall be an lvalue reference to a
4759 // non-volatile const type (i.e., cv1 shall be const), or the reference
4760 // shall be an rvalue reference.
4761 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4762 return ICS;
4763
4764 // -- If the initializer expression
4765 //
4766 // -- is an xvalue, class prvalue, array prvalue or function
4767 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4768 if (RefRelationship == Sema::Ref_Compatible &&
4769 (InitCategory.isXValue() ||
4770 (InitCategory.isPRValue() &&
4771 (T2->isRecordType() || T2->isArrayType())) ||
4772 (InitCategory.isLValue() && T2->isFunctionType()))) {
4773 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4774 // binding unless we're binding to a class prvalue.
4775 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4776 // allow the use of rvalue references in C++98/03 for the benefit of
4777 // standard library implementors; therefore, we need the xvalue check here.
4778 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4779 !(InitCategory.isPRValue() || T2->isRecordType()));
4780 return ICS;
4781 }
4782
4783 // -- has a class type (i.e., T2 is a class type), where T1 is not
4784 // reference-related to T2, and can be implicitly converted to
4785 // an xvalue, class prvalue, or function lvalue of type
4786 // "cv3 T3", where "cv1 T1" is reference-compatible with
4787 // "cv3 T3",
4788 //
4789 // then the reference is bound to the value of the initializer
4790 // expression in the first case and to the result of the conversion
4791 // in the second case (or, in either case, to an appropriate base
4792 // class subobject).
4793 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4794 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4795 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4796 Init, T2, /*AllowRvalues=*/true,
4797 AllowExplicit)) {
4798 // In the second case, if the reference is an rvalue reference
4799 // and the second standard conversion sequence of the
4800 // user-defined conversion sequence includes an lvalue-to-rvalue
4801 // conversion, the program is ill-formed.
4802 if (ICS.isUserDefined() && isRValRef &&
4803 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4804 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4805
4806 return ICS;
4807 }
4808
4809 // A temporary of function type cannot be created; don't even try.
4810 if (T1->isFunctionType())
4811 return ICS;
4812
4813 // -- Otherwise, a temporary of type "cv1 T1" is created and
4814 // initialized from the initializer expression using the
4815 // rules for a non-reference copy initialization (8.5). The
4816 // reference is then bound to the temporary. If T1 is
4817 // reference-related to T2, cv1 must be the same
4818 // cv-qualification as, or greater cv-qualification than,
4819 // cv2; otherwise, the program is ill-formed.
4820 if (RefRelationship == Sema::Ref_Related) {
4821 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4822 // we would be reference-compatible or reference-compatible with
4823 // added qualification. But that wasn't the case, so the reference
4824 // initialization fails.
4825 //
4826 // Note that we only want to check address spaces and cvr-qualifiers here.
4827 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4828 Qualifiers T1Quals = T1.getQualifiers();
4829 Qualifiers T2Quals = T2.getQualifiers();
4830 T1Quals.removeObjCGCAttr();
4831 T1Quals.removeObjCLifetime();
4832 T2Quals.removeObjCGCAttr();
4833 T2Quals.removeObjCLifetime();
4834 // MS compiler ignores __unaligned qualifier for references; do the same.
4835 T1Quals.removeUnaligned();
4836 T2Quals.removeUnaligned();
4837 if (!T1Quals.compatiblyIncludes(T2Quals))
4838 return ICS;
4839 }
4840
4841 // If at least one of the types is a class type, the types are not
4842 // related, and we aren't allowed any user conversions, the
4843 // reference binding fails. This case is important for breaking
4844 // recursion, since TryImplicitConversion below will attempt to
4845 // create a temporary through the use of a copy constructor.
4846 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4847 (T1->isRecordType() || T2->isRecordType()))
4848 return ICS;
4849
4850 // If T1 is reference-related to T2 and the reference is an rvalue
4851 // reference, the initializer expression shall not be an lvalue.
4852 if (RefRelationship >= Sema::Ref_Related &&
4853 isRValRef && Init->Classify(S.Context).isLValue())
4854 return ICS;
4855
4856 // C++ [over.ics.ref]p2:
4857 // When a parameter of reference type is not bound directly to
4858 // an argument expression, the conversion sequence is the one
4859 // required to convert the argument expression to the
4860 // underlying type of the reference according to
4861 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4862 // to copy-initializing a temporary of the underlying type with
4863 // the argument expression. Any difference in top-level
4864 // cv-qualification is subsumed by the initialization itself
4865 // and does not constitute a conversion.
4866 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4867 /*AllowExplicit=*/false,
4868 /*InOverloadResolution=*/false,
4869 /*CStyle=*/false,
4870 /*AllowObjCWritebackConversion=*/false,
4871 /*AllowObjCConversionOnExplicit=*/false);
4872
4873 // Of course, that's still a reference binding.
4874 if (ICS.isStandard()) {
4875 ICS.Standard.ReferenceBinding = true;
4876 ICS.Standard.IsLvalueReference = !isRValRef;
4877 ICS.Standard.BindsToFunctionLvalue = false;
4878 ICS.Standard.BindsToRvalue = true;
4879 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4880 ICS.Standard.ObjCLifetimeConversionBinding = false;
4881 } else if (ICS.isUserDefined()) {
4882 const ReferenceType *LValRefType =
4883 ICS.UserDefined.ConversionFunction->getReturnType()
4884 ->getAs<LValueReferenceType>();
4885
4886 // C++ [over.ics.ref]p3:
4887 // Except for an implicit object parameter, for which see 13.3.1, a
4888 // standard conversion sequence cannot be formed if it requires [...]
4889 // binding an rvalue reference to an lvalue other than a function
4890 // lvalue.
4891 // Note that the function case is not possible here.
4892 if (DeclType->isRValueReferenceType() && LValRefType) {
4893 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4894 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4895 // reference to an rvalue!
4896 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4897 return ICS;
4898 }
4899
4900 ICS.UserDefined.After.ReferenceBinding = true;
4901 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4902 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4903 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4904 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4905 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4906 }
4907
4908 return ICS;
4909}
4910
4911static ImplicitConversionSequence
4912TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4913 bool SuppressUserConversions,
4914 bool InOverloadResolution,
4915 bool AllowObjCWritebackConversion,
4916 bool AllowExplicit = false);
4917
4918/// TryListConversion - Try to copy-initialize a value of type ToType from the
4919/// initializer list From.
4920static ImplicitConversionSequence
4921TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4922 bool SuppressUserConversions,
4923 bool InOverloadResolution,
4924 bool AllowObjCWritebackConversion) {
4925 // C++11 [over.ics.list]p1:
4926 // When an argument is an initializer list, it is not an expression and
4927 // special rules apply for converting it to a parameter type.
4928
4929 ImplicitConversionSequence Result;
4930 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4931
4932 // We need a complete type for what follows. Incomplete types can never be
4933 // initialized from init lists.
4934 if (!S.isCompleteType(From->getBeginLoc(), ToType))
4935 return Result;
4936
4937 // Per DR1467:
4938 // If the parameter type is a class X and the initializer list has a single
4939 // element of type cv U, where U is X or a class derived from X, the
4940 // implicit conversion sequence is the one required to convert the element
4941 // to the parameter type.
4942 //
4943 // Otherwise, if the parameter type is a character array [... ]
4944 // and the initializer list has a single element that is an
4945 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4946 // implicit conversion sequence is the identity conversion.
4947 if (From->getNumInits() == 1) {
4948 if (ToType->isRecordType()) {
4949 QualType InitType = From->getInit(0)->getType();
4950 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4951 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4952 return TryCopyInitialization(S, From->getInit(0), ToType,
4953 SuppressUserConversions,
4954 InOverloadResolution,
4955 AllowObjCWritebackConversion);
4956 }
4957 // FIXME: Check the other conditions here: array of character type,
4958 // initializer is a string literal.
4959 if (ToType->isArrayType()) {
4960 InitializedEntity Entity =
4961 InitializedEntity::InitializeParameter(S.Context, ToType,
4962 /*Consumed=*/false);
4963 if (S.CanPerformCopyInitialization(Entity, From)) {
4964 Result.setStandard();
4965 Result.Standard.setAsIdentityConversion();
4966 Result.Standard.setFromType(ToType);
4967 Result.Standard.setAllToTypes(ToType);
4968 return Result;
4969 }
4970 }
4971 }
4972
4973 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4974 // C++11 [over.ics.list]p2:
4975 // If the parameter type is std::initializer_list<X> or "array of X" and
4976 // all the elements can be implicitly converted to X, the implicit
4977 // conversion sequence is the worst conversion necessary to convert an
4978 // element of the list to X.
4979 //
4980 // C++14 [over.ics.list]p3:
4981 // Otherwise, if the parameter type is "array of N X", if the initializer
4982 // list has exactly N elements or if it has fewer than N elements and X is
4983 // default-constructible, and if all the elements of the initializer list
4984 // can be implicitly converted to X, the implicit conversion sequence is
4985 // the worst conversion necessary to convert an element of the list to X.
4986 //
4987 // FIXME: We're missing a lot of these checks.
4988 bool toStdInitializerList = false;
4989 QualType X;
4990 if (ToType->isArrayType())
4991 X = S.Context.getAsArrayType(ToType)->getElementType();
4992 else
4993 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4994 if (!X.isNull()) {
4995 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4996 Expr *Init = From->getInit(i);
4997 ImplicitConversionSequence ICS =
4998 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4999 InOverloadResolution,
5000 AllowObjCWritebackConversion);
5001 // If a single element isn't convertible, fail.
5002 if (ICS.isBad()) {
5003 Result = ICS;
5004 break;
5005 }
5006 // Otherwise, look for the worst conversion.
5007 if (Result.isBad() || CompareImplicitConversionSequences(
5008 S, From->getBeginLoc(), ICS, Result) ==
5009 ImplicitConversionSequence::Worse)
5010 Result = ICS;
5011 }
5012
5013 // For an empty list, we won't have computed any conversion sequence.
5014 // Introduce the identity conversion sequence.
5015 if (From->getNumInits() == 0) {
5016 Result.setStandard();
5017 Result.Standard.setAsIdentityConversion();
5018 Result.Standard.setFromType(ToType);
5019 Result.Standard.setAllToTypes(ToType);
5020 }
5021
5022 Result.setStdInitializerListElement(toStdInitializerList);
5023 return Result;
5024 }
5025
5026 // C++14 [over.ics.list]p4:
5027 // C++11 [over.ics.list]p3:
5028 // Otherwise, if the parameter is a non-aggregate class X and overload
5029 // resolution chooses a single best constructor [...] the implicit
5030 // conversion sequence is a user-defined conversion sequence. If multiple
5031 // constructors are viable but none is better than the others, the
5032 // implicit conversion sequence is a user-defined conversion sequence.
5033 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5034 // This function can deal with initializer lists.
5035 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5036 /*AllowExplicit=*/false,
5037 InOverloadResolution, /*CStyle=*/false,
5038 AllowObjCWritebackConversion,
5039 /*AllowObjCConversionOnExplicit=*/false);
5040 }
5041
5042 // C++14 [over.ics.list]p5:
5043 // C++11 [over.ics.list]p4:
5044 // Otherwise, if the parameter has an aggregate type which can be
5045 // initialized from the initializer list [...] the implicit conversion
5046 // sequence is a user-defined conversion sequence.
5047 if (ToType->isAggregateType()) {
5048 // Type is an aggregate, argument is an init list. At this point it comes
5049 // down to checking whether the initialization works.
5050 // FIXME: Find out whether this parameter is consumed or not.
5051 InitializedEntity Entity =
5052 InitializedEntity::InitializeParameter(S.Context, ToType,
5053 /*Consumed=*/false);
5054 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5055 From)) {
5056 Result.setUserDefined();
5057 Result.UserDefined.Before.setAsIdentityConversion();
5058 // Initializer lists don't have a type.
5059 Result.UserDefined.Before.setFromType(QualType());
5060 Result.UserDefined.Before.setAllToTypes(QualType());
5061
5062 Result.UserDefined.After.setAsIdentityConversion();
5063 Result.UserDefined.After.setFromType(ToType);
5064 Result.UserDefined.After.setAllToTypes(ToType);
5065 Result.UserDefined.ConversionFunction = nullptr;
5066 }
5067 return Result;
5068 }
5069
5070 // C++14 [over.ics.list]p6:
5071 // C++11 [over.ics.list]p5:
5072 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5073 if (ToType->isReferenceType()) {
5074 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5075 // mention initializer lists in any way. So we go by what list-
5076 // initialization would do and try to extrapolate from that.
5077
5078 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5079
5080 // If the initializer list has a single element that is reference-related
5081 // to the parameter type, we initialize the reference from that.
5082 if (From->getNumInits() == 1) {
5083 Expr *Init = From->getInit(0);
5084
5085 QualType T2 = Init->getType();
5086
5087 // If the initializer is the address of an overloaded function, try
5088 // to resolve the overloaded function. If all goes well, T2 is the
5089 // type of the resulting function.
5090 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5091 DeclAccessPair Found;
5092 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5093 Init, ToType, false, Found))
5094 T2 = Fn->getType();
5095 }
5096
5097 // Compute some basic properties of the types and the initializer.
5098 Sema::ReferenceCompareResult RefRelationship =
5099 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5100
5101 if (RefRelationship >= Sema::Ref_Related) {
5102 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5103 SuppressUserConversions,
5104 /*AllowExplicit=*/false);
5105 }
5106 }
5107
5108 // Otherwise, we bind the reference to a temporary created from the
5109 // initializer list.
5110 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5111 InOverloadResolution,
5112 AllowObjCWritebackConversion);
5113 if (Result.isFailure())
5114 return Result;
5115 assert(!Result.isEllipsis() &&((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5116, __PRETTY_FUNCTION__))
5116 "Sub-initialization cannot result in ellipsis conversion.")((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5116, __PRETTY_FUNCTION__))
;
5117
5118 // Can we even bind to a temporary?
5119 if (ToType->isRValueReferenceType() ||
5120 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5121 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5122 Result.UserDefined.After;
5123 SCS.ReferenceBinding = true;
5124 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5125 SCS.BindsToRvalue = true;
5126 SCS.BindsToFunctionLvalue = false;
5127 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5128 SCS.ObjCLifetimeConversionBinding = false;
5129 } else
5130 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5131 From, ToType);
5132 return Result;
5133 }
5134
5135 // C++14 [over.ics.list]p7:
5136 // C++11 [over.ics.list]p6:
5137 // Otherwise, if the parameter type is not a class:
5138 if (!ToType->isRecordType()) {
5139 // - if the initializer list has one element that is not itself an
5140 // initializer list, the implicit conversion sequence is the one
5141 // required to convert the element to the parameter type.
5142 unsigned NumInits = From->getNumInits();
5143 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5144 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5145 SuppressUserConversions,
5146 InOverloadResolution,
5147 AllowObjCWritebackConversion);
5148 // - if the initializer list has no elements, the implicit conversion
5149 // sequence is the identity conversion.
5150 else if (NumInits == 0) {
5151 Result.setStandard();
5152 Result.Standard.setAsIdentityConversion();
5153 Result.Standard.setFromType(ToType);
5154 Result.Standard.setAllToTypes(ToType);
5155 }
5156 return Result;
5157 }
5158
5159 // C++14 [over.ics.list]p8:
5160 // C++11 [over.ics.list]p7:
5161 // In all cases other than those enumerated above, no conversion is possible
5162 return Result;
5163}
5164
5165/// TryCopyInitialization - Try to copy-initialize a value of type
5166/// ToType from the expression From. Return the implicit conversion
5167/// sequence required to pass this argument, which may be a bad
5168/// conversion sequence (meaning that the argument cannot be passed to
5169/// a parameter of this type). If @p SuppressUserConversions, then we
5170/// do not permit any user-defined conversion sequences.
5171static ImplicitConversionSequence
5172TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5173 bool SuppressUserConversions,
5174 bool InOverloadResolution,
5175 bool AllowObjCWritebackConversion,
5176 bool AllowExplicit) {
5177 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5178 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5179 InOverloadResolution,AllowObjCWritebackConversion);
5180
5181 if (ToType->isReferenceType())
5182 return TryReferenceInit(S, From, ToType,
5183 /*FIXME:*/ From->getBeginLoc(),
5184 SuppressUserConversions, AllowExplicit);
5185
5186 return TryImplicitConversion(S, From, ToType,
5187 SuppressUserConversions,
5188 /*AllowExplicit=*/false,
5189 InOverloadResolution,
5190 /*CStyle=*/false,
5191 AllowObjCWritebackConversion,
5192 /*AllowObjCConversionOnExplicit=*/false);
5193}
5194
5195static bool TryCopyInitialization(const CanQualType FromQTy,
5196 const CanQualType ToQTy,
5197 Sema &S,
5198 SourceLocation Loc,
5199 ExprValueKind FromVK) {
5200 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5201 ImplicitConversionSequence ICS =
5202 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5203
5204 return !ICS.isBad();
5205}
5206
5207/// TryObjectArgumentInitialization - Try to initialize the object
5208/// parameter of the given member function (@c Method) from the
5209/// expression @p From.
5210static ImplicitConversionSequence
5211TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5212 Expr::Classification FromClassification,
5213 CXXMethodDecl *Method,
5214 CXXRecordDecl *ActingContext) {
5215 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5216 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5217 // const volatile object.
5218 Qualifiers Quals = Method->getMethodQualifiers();
5219 if (isa<CXXDestructorDecl>(Method)) {
5220 Quals.addConst();
5221 Quals.addVolatile();
5222 }
5223
5224 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5225
5226 // Set up the conversion sequence as a "bad" conversion, to allow us
5227 // to exit early.
5228 ImplicitConversionSequence ICS;
5229
5230 // We need to have an object of class type.
5231 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5232 FromType = PT->getPointeeType();
5233
5234 // When we had a pointer, it's implicitly dereferenced, so we
5235 // better have an lvalue.
5236 assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0
) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5236, __PRETTY_FUNCTION__))
;
5237 }
5238
5239 assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) :
__assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5239, __PRETTY_FUNCTION__))
;
5240
5241 // C++0x [over.match.funcs]p4:
5242 // For non-static member functions, the type of the implicit object
5243 // parameter is
5244 //
5245 // - "lvalue reference to cv X" for functions declared without a
5246 // ref-qualifier or with the & ref-qualifier
5247 // - "rvalue reference to cv X" for functions declared with the &&
5248 // ref-qualifier
5249 //
5250 // where X is the class of which the function is a member and cv is the
5251 // cv-qualification on the member function declaration.
5252 //
5253 // However, when finding an implicit conversion sequence for the argument, we
5254 // are not allowed to perform user-defined conversions
5255 // (C++ [over.match.funcs]p5). We perform a simplified version of
5256 // reference binding here, that allows class rvalues to bind to
5257 // non-constant references.
5258
5259 // First check the qualifiers.
5260 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5261 if (ImplicitParamType.getCVRQualifiers()
5262 != FromTypeCanon.getLocalCVRQualifiers() &&
5263 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5264 ICS.setBad(BadConversionSequence::bad_qualifiers,
5265 FromType, ImplicitParamType);
5266 return ICS;
5267 }
5268
5269 if (FromTypeCanon.hasAddressSpace()) {
5270 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5271 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5272 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5273 ICS.setBad(BadConversionSequence::bad_qualifiers,
5274 FromType, ImplicitParamType);
5275 return ICS;
5276 }
5277 }
5278
5279 // Check that we have either the same type or a derived type. It
5280 // affects the conversion rank.
5281 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5282 ImplicitConversionKind SecondKind;
5283 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5284 SecondKind = ICK_Identity;
5285 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5286 SecondKind = ICK_Derived_To_Base;
5287 else {
5288 ICS.setBad(BadConversionSequence::unrelated_class,
5289 FromType, ImplicitParamType);
5290 return ICS;
5291 }
5292
5293 // Check the ref-qualifier.
5294 switch (Method->getRefQualifier()) {
5295 case RQ_None:
5296 // Do nothing; we don't care about lvalueness or rvalueness.
5297 break;
5298
5299 case RQ_LValue:
5300 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5301 // non-const lvalue reference cannot bind to an rvalue
5302 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5303 ImplicitParamType);
5304 return ICS;
5305 }
5306 break;
5307
5308 case RQ_RValue:
5309 if (!FromClassification.isRValue()) {
5310 // rvalue reference cannot bind to an lvalue
5311 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5312 ImplicitParamType);
5313 return ICS;
5314 }
5315 break;
5316 }
5317
5318 // Success. Mark this as a reference binding.
5319 ICS.setStandard();
5320 ICS.Standard.setAsIdentityConversion();
5321 ICS.Standard.Second = SecondKind;
5322 ICS.Standard.setFromType(FromType);
5323 ICS.Standard.setAllToTypes(ImplicitParamType);
5324 ICS.Standard.ReferenceBinding = true;
5325 ICS.Standard.DirectBinding = true;
5326 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5327 ICS.Standard.BindsToFunctionLvalue = false;
5328 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5329 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5330 = (Method->getRefQualifier() == RQ_None);
5331 return ICS;
5332}
5333
5334/// PerformObjectArgumentInitialization - Perform initialization of
5335/// the implicit object parameter for the given Method with the given
5336/// expression.
5337ExprResult
5338Sema::PerformObjectArgumentInitialization(Expr *From,
5339 NestedNameSpecifier *Qualifier,
5340 NamedDecl *FoundDecl,
5341 CXXMethodDecl *Method) {
5342 QualType FromRecordType, DestType;
5343 QualType ImplicitParamRecordType =
5344 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5345
5346 Expr::Classification FromClassification;
5347 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5348 FromRecordType = PT->getPointeeType();
5349 DestType = Method->getThisType();
5350 FromClassification = Expr::Classification::makeSimpleLValue();
5351 } else {
5352 FromRecordType = From->getType();
5353 DestType = ImplicitParamRecordType;
5354 FromClassification = From->Classify(Context);
5355
5356 // When performing member access on an rvalue, materialize a temporary.
5357 if (From->isRValue()) {
5358 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5359 Method->getRefQualifier() !=
5360 RefQualifierKind::RQ_RValue);
5361 }
5362 }
5363
5364 // Note that we always use the true parent context when performing
5365 // the actual argument initialization.
5366 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5367 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5368 Method->getParent());
5369 if (ICS.isBad()) {
5370 switch (ICS.Bad.Kind) {
5371 case BadConversionSequence::bad_qualifiers: {
5372 Qualifiers FromQs = FromRecordType.getQualifiers();
5373 Qualifiers ToQs = DestType.getQualifiers();
5374 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5375 if (CVR) {
5376 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5377 << Method->getDeclName() << FromRecordType << (CVR - 1)
5378 << From->getSourceRange();
5379 Diag(Method->getLocation(), diag::note_previous_decl)
5380 << Method->getDeclName();
5381 return ExprError();
5382 }
5383 break;
5384 }
5385
5386 case BadConversionSequence::lvalue_ref_to_rvalue:
5387 case BadConversionSequence::rvalue_ref_to_lvalue: {
5388 bool IsRValueQualified =
5389 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5390 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5391 << Method->getDeclName() << FromClassification.isRValue()
5392 << IsRValueQualified;
5393 Diag(Method->getLocation(), diag::note_previous_decl)
5394 << Method->getDeclName();
5395 return ExprError();
5396 }
5397
5398 case BadConversionSequence::no_conversion:
5399 case BadConversionSequence::unrelated_class:
5400 break;
5401 }
5402
5403 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5404 << ImplicitParamRecordType << FromRecordType
5405 << From->getSourceRange();
5406 }
5407
5408 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5409 ExprResult FromRes =
5410 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5411 if (FromRes.isInvalid())
5412 return ExprError();
5413 From = FromRes.get();
5414 }
5415
5416 if (!Context.hasSameType(From->getType(), DestType)) {
5417 CastKind CK;
5418 QualType PteeTy = DestType->getPointeeType();
5419 LangAS DestAS =
5420 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5421 if (FromRecordType.getAddressSpace() != DestAS)
5422 CK = CK_AddressSpaceConversion;
5423 else
5424 CK = CK_NoOp;
5425 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5426 }
5427 return From;
5428}
5429
5430/// TryContextuallyConvertToBool - Attempt to contextually convert the
5431/// expression From to bool (C++0x [conv]p3).
5432static ImplicitConversionSequence
5433TryContextuallyConvertToBool(Sema &S, Expr *From) {
5434 return TryImplicitConversion(S, From, S.Context.BoolTy,
5435 /*SuppressUserConversions=*/false,
5436 /*AllowExplicit=*/true,
5437 /*InOverloadResolution=*/false,
5438 /*CStyle=*/false,
5439 /*AllowObjCWritebackConversion=*/false,
5440 /*AllowObjCConversionOnExplicit=*/false);
5441}
5442
5443/// PerformContextuallyConvertToBool - Perform a contextual conversion
5444/// of the expression From to bool (C++0x [conv]p3).
5445ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5446 if (checkPlaceholderForOverload(*this, From))
5447 return ExprError();
5448
5449 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5450 if (!ICS.isBad())
5451 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5452
5453 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5454 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5455 << From->getType() << From->getSourceRange();
5456 return ExprError();
5457}
5458
5459/// Check that the specified conversion is permitted in a converted constant
5460/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5461/// is acceptable.
5462static bool CheckConvertedConstantConversions(Sema &S,
5463 StandardConversionSequence &SCS) {
5464 // Since we know that the target type is an integral or unscoped enumeration
5465 // type, most conversion kinds are impossible. All possible First and Third
5466 // conversions are fine.
5467 switch (SCS.Second) {
5468 case ICK_Identity:
5469 case ICK_Function_Conversion:
5470 case ICK_Integral_Promotion:
5471 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5472 case ICK_Zero_Queue_Conversion:
5473 return true;
5474
5475 case ICK_Boolean_Conversion:
5476 // Conversion from an integral or unscoped enumeration type to bool is
5477 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5478 // conversion, so we allow it in a converted constant expression.
5479 //
5480 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5481 // a lot of popular code. We should at least add a warning for this
5482 // (non-conforming) extension.
5483 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5484 SCS.getToType(2)->isBooleanType();
5485
5486 case ICK_Pointer_Conversion:
5487 case ICK_Pointer_Member:
5488 // C++1z: null pointer conversions and null member pointer conversions are
5489 // only permitted if the source type is std::nullptr_t.
5490 return SCS.getFromType()->isNullPtrType();
5491
5492 case ICK_Floating_Promotion:
5493 case ICK_Complex_Promotion:
5494 case ICK_Floating_Conversion:
5495 case ICK_Complex_Conversion:
5496 case ICK_Floating_Integral:
5497 case ICK_Compatible_Conversion:
5498 case ICK_Derived_To_Base:
5499 case ICK_Vector_Conversion:
5500 case ICK_Vector_Splat:
5501 case ICK_Complex_Real:
5502 case ICK_Block_Pointer_Conversion:
5503 case ICK_TransparentUnionConversion:
5504 case ICK_Writeback_Conversion:
5505 case ICK_Zero_Event_Conversion:
5506 case ICK_C_Only_Conversion:
5507 case ICK_Incompatible_Pointer_Conversion:
5508 return false;
5509
5510 case ICK_Lvalue_To_Rvalue:
5511 case ICK_Array_To_Pointer:
5512 case ICK_Function_To_Pointer:
5513 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5513)
;
5514
5515 case ICK_Qualification:
5516 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5516)
;
5517
5518 case ICK_Num_Conversion_Kinds:
5519 break;
5520 }
5521
5522 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5522)
;
5523}
5524
5525/// CheckConvertedConstantExpression - Check that the expression From is a
5526/// converted constant expression of type T, perform the conversion and produce
5527/// the converted expression, per C++11 [expr.const]p3.
5528static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5529 QualType T, APValue &Value,
5530 Sema::CCEKind CCE,
5531 bool RequireInt) {
5532 assert(S.getLangOpts().CPlusPlus11 &&((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5533, __PRETTY_FUNCTION__))
5533 "converted constant expression outside C++11")((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5533, __PRETTY_FUNCTION__))
;
5534
5535 if (checkPlaceholderForOverload(S, From))
5536 return ExprError();
5537
5538 // C++1z [expr.const]p3:
5539 // A converted constant expression of type T is an expression,
5540 // implicitly converted to type T, where the converted
5541 // expression is a constant expression and the implicit conversion
5542 // sequence contains only [... list of conversions ...].
5543 // C++1z [stmt.if]p2:
5544 // If the if statement is of the form if constexpr, the value of the
5545 // condition shall be a contextually converted constant expression of type
5546 // bool.
5547 ImplicitConversionSequence ICS =
5548 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5549 ? TryContextuallyConvertToBool(S, From)
5550 : TryCopyInitialization(S, From, T,
5551 /*SuppressUserConversions=*/false,
5552 /*InOverloadResolution=*/false,
5553 /*AllowObjCWritebackConversion=*/false,
5554 /*AllowExplicit=*/false);
5555 StandardConversionSequence *SCS = nullptr;
5556 switch (ICS.getKind()) {
5557 case ImplicitConversionSequence::StandardConversion:
5558 SCS = &ICS.Standard;
5559 break;
5560 case ImplicitConversionSequence::UserDefinedConversion:
5561 // We are converting to a non-class type, so the Before sequence
5562 // must be trivial.
5563 SCS = &ICS.UserDefined.After;
5564 break;
5565 case ImplicitConversionSequence::AmbiguousConversion:
5566 case ImplicitConversionSequence::BadConversion:
5567 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5568 return S.Diag(From->getBeginLoc(),
5569 diag::err_typecheck_converted_constant_expression)
5570 << From->getType() << From->getSourceRange() << T;
5571 return ExprError();
5572
5573 case ImplicitConversionSequence::EllipsisConversion:
5574 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5574)
;
5575 }
5576
5577 // Check that we would only use permitted conversions.
5578 if (!CheckConvertedConstantConversions(S, *SCS)) {
5579 return S.Diag(From->getBeginLoc(),
5580 diag::err_typecheck_converted_constant_expression_disallowed)
5581 << From->getType() << From->getSourceRange() << T;
5582 }
5583 // [...] and where the reference binding (if any) binds directly.
5584 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5585 return S.Diag(From->getBeginLoc(),
5586 diag::err_typecheck_converted_constant_expression_indirect)
5587 << From->getType() << From->getSourceRange() << T;
5588 }
5589
5590 ExprResult Result =
5591 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5592 if (Result.isInvalid())
5593 return Result;
5594
5595 // C++2a [intro.execution]p5:
5596 // A full-expression is [...] a constant-expression [...]
5597 Result =
5598 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5599 /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5600 if (Result.isInvalid())
5601 return Result;
5602
5603 // Check for a narrowing implicit conversion.
5604 APValue PreNarrowingValue;
5605 QualType PreNarrowingType;
5606 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5607 PreNarrowingType)) {
5608 case NK_Dependent_Narrowing:
5609 // Implicit conversion to a narrower type, but the expression is
5610 // value-dependent so we can't tell whether it's actually narrowing.
5611 case NK_Variable_Narrowing:
5612 // Implicit conversion to a narrower type, and the value is not a constant
5613 // expression. We'll diagnose this in a moment.
5614 case NK_Not_Narrowing:
5615 break;
5616
5617 case NK_Constant_Narrowing:
5618 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5619 << CCE << /*Constant*/ 1
5620 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5621 break;
5622
5623 case NK_Type_Narrowing:
5624 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5625 << CCE << /*Constant*/ 0 << From->getType() << T;
5626 break;
5627 }
5628
5629 if (Result.get()->isValueDependent()) {
5630 Value = APValue();
5631 return Result;
5632 }
5633
5634 // Check the expression is a constant expression.
5635 SmallVector<PartialDiagnosticAt, 8> Notes;
5636 Expr::EvalResult Eval;
5637 Eval.Diag = &Notes;
5638 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5639 ? Expr::EvaluateForMangling
5640 : Expr::EvaluateForCodeGen;
5641
5642 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5643 (RequireInt && !Eval.Val.isInt())) {
5644 // The expression can't be folded, so we can't keep it at this position in
5645 // the AST.
5646 Result = ExprError();
5647 } else {
5648 Value = Eval.Val;
5649
5650 if (Notes.empty()) {
5651 // It's a constant expression.
5652 return ConstantExpr::Create(S.Context, Result.get(), Value);
5653 }
5654 }
5655
5656 // It's not a constant expression. Produce an appropriate diagnostic.
5657 if (Notes.size() == 1 &&
5658 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5659 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5660 else {
5661 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5662 << CCE << From->getSourceRange();
5663 for (unsigned I = 0; I < Notes.size(); ++I)
5664 S.Diag(Notes[I].first, Notes[I].second);
5665 }
5666 return ExprError();
5667}
5668
5669ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5670 APValue &Value, CCEKind CCE) {
5671 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5672}
5673
5674ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5675 llvm::APSInt &Value,
5676 CCEKind CCE) {
5677 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")((T->isIntegralOrEnumerationType() && "unexpected converted const type"
) ? static_cast<void> (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5677, __PRETTY_FUNCTION__))
;
5678
5679 APValue V;
5680 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5681 if (!R.isInvalid() && !R.get()->isValueDependent())
5682 Value = V.getInt();
5683 return R;
5684}
5685
5686
5687/// dropPointerConversions - If the given standard conversion sequence
5688/// involves any pointer conversions, remove them. This may change
5689/// the result type of the conversion sequence.
5690static void dropPointerConversion(StandardConversionSequence &SCS) {
5691 if (SCS.Second == ICK_Pointer_Conversion) {
5692 SCS.Second = ICK_Identity;
5693 SCS.Third = ICK_Identity;
5694 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5695 }
5696}
5697
5698/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5699/// convert the expression From to an Objective-C pointer type.
5700static ImplicitConversionSequence
5701TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5702 // Do an implicit conversion to 'id'.
5703 QualType Ty = S.Context.getObjCIdType();
5704 ImplicitConversionSequence ICS
5705 = TryImplicitConversion(S, From, Ty,
5706 // FIXME: Are these flags correct?
5707 /*SuppressUserConversions=*/false,
5708 /*AllowExplicit=*/true,
5709 /*InOverloadResolution=*/false,
5710 /*CStyle=*/false,
5711 /*AllowObjCWritebackConversion=*/false,
5712 /*AllowObjCConversionOnExplicit=*/true);
5713
5714 // Strip off any final conversions to 'id'.
5715 switch (ICS.getKind()) {
5716 case ImplicitConversionSequence::BadConversion:
5717 case ImplicitConversionSequence::AmbiguousConversion:
5718 case ImplicitConversionSequence::EllipsisConversion:
5719 break;
5720
5721 case ImplicitConversionSequence::UserDefinedConversion:
5722 dropPointerConversion(ICS.UserDefined.After);
5723 break;
5724
5725 case ImplicitConversionSequence::StandardConversion:
5726 dropPointerConversion(ICS.Standard);
5727 break;
5728 }
5729
5730 return ICS;
5731}
5732
5733/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5734/// conversion of the expression From to an Objective-C pointer type.
5735/// Returns a valid but null ExprResult if no conversion sequence exists.
5736ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5737 if (checkPlaceholderForOverload(*this, From))
5738 return ExprError();
5739
5740 QualType Ty = Context.getObjCIdType();
5741 ImplicitConversionSequence ICS =
5742 TryContextuallyConvertToObjCPointer(*this, From);
5743 if (!ICS.isBad())
5744 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5745 return ExprResult();
5746}
5747
5748/// Determine whether the provided type is an integral type, or an enumeration
5749/// type of a permitted flavor.
5750bool Sema::ICEConvertDiagnoser::match(QualType T) {
5751 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5752 : T->isIntegralOrUnscopedEnumerationType();
5753}
5754
5755static ExprResult
5756diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5757 Sema::ContextualImplicitConverter &Converter,
5758 QualType T, UnresolvedSetImpl &ViableConversions) {
5759
5760 if (Converter.Suppress)
5761 return ExprError();
5762
5763 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5764 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5765 CXXConversionDecl *Conv =
5766 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5767 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5768 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5769 }
5770 return From;
5771}
5772
5773static bool
5774diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5775 Sema::ContextualImplicitConverter &Converter,
5776 QualType T, bool HadMultipleCandidates,
5777 UnresolvedSetImpl &ExplicitConversions) {
5778 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5779 DeclAccessPair Found = ExplicitConversions[0];
5780 CXXConversionDecl *Conversion =
5781 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5782
5783 // The user probably meant to invoke the given explicit
5784 // conversion; use it.
5785 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5786 std::string TypeStr;
5787 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5788
5789 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5790 << FixItHint::CreateInsertion(From->getBeginLoc(),
5791 "static_cast<" + TypeStr + ">(")
5792 << FixItHint::CreateInsertion(
5793 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5794 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5795
5796 // If we aren't in a SFINAE context, build a call to the
5797 // explicit conversion function.
5798 if (SemaRef.isSFINAEContext())
5799 return true;
5800
5801 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5802 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5803 HadMultipleCandidates);
5804 if (Result.isInvalid())
5805 return true;
5806 // Record usage of conversion in an implicit cast.
5807 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5808 CK_UserDefinedConversion, Result.get(),
5809 nullptr, Result.get()->getValueKind());
5810 }
5811 return false;
5812}
5813
5814static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5815 Sema::ContextualImplicitConverter &Converter,
5816 QualType T, bool HadMultipleCandidates,
5817 DeclAccessPair &Found) {
5818 CXXConversionDecl *Conversion =
5819 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5820 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5821
5822 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5823 if (!Converter.SuppressConversion) {
5824 if (SemaRef.isSFINAEContext())
5825 return true;
5826
5827 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5828 << From->getSourceRange();
5829 }
5830
5831 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5832 HadMultipleCandidates);
5833 if (Result.isInvalid())
5834 return true;
5835 // Record usage of conversion in an implicit cast.
5836 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5837 CK_UserDefinedConversion, Result.get(),
5838 nullptr, Result.get()->getValueKind());
5839 return false;
5840}
5841
5842static ExprResult finishContextualImplicitConversion(
5843 Sema &SemaRef, SourceLocation Loc, Expr *From,
5844 Sema::ContextualImplicitConverter &Converter) {
5845 if (!Converter.match(From->getType()) && !Converter.Suppress)
5846 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5847 << From->getSourceRange();
5848
5849 return SemaRef.DefaultLvalueConversion(From);
5850}
5851
5852static void
5853collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5854 UnresolvedSetImpl &ViableConversions,
5855 OverloadCandidateSet &CandidateSet) {
5856 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5857 DeclAccessPair FoundDecl = ViableConversions[I];
5858 NamedDecl *D = FoundDecl.getDecl();
5859 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5860 if (isa<UsingShadowDecl>(D))
5861 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5862
5863 CXXConversionDecl *Conv;
5864 FunctionTemplateDecl *ConvTemplate;
5865 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5866 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5867 else
5868 Conv = cast<CXXConversionDecl>(D);
5869
5870 if (ConvTemplate)
5871 SemaRef.AddTemplateConversionCandidate(
5872 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5873 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5874 else
5875 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5876 ToType, CandidateSet,
5877 /*AllowObjCConversionOnExplicit=*/false,
5878 /*AllowExplicit*/ true);
5879 }
5880}
5881
5882/// Attempt to convert the given expression to a type which is accepted
5883/// by the given converter.
5884///
5885/// This routine will attempt to convert an expression of class type to a
5886/// type accepted by the specified converter. In C++11 and before, the class
5887/// must have a single non-explicit conversion function converting to a matching
5888/// type. In C++1y, there can be multiple such conversion functions, but only
5889/// one target type.
5890///
5891/// \param Loc The source location of the construct that requires the
5892/// conversion.
5893///
5894/// \param From The expression we're converting from.
5895///
5896/// \param Converter Used to control and diagnose the conversion process.
5897///
5898/// \returns The expression, converted to an integral or enumeration type if
5899/// successful.
5900ExprResult Sema::PerformContextualImplicitConversion(
5901 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5902 // We can't perform any more checking for type-dependent expressions.
5903 if (From->isTypeDependent())
5904 return From;
5905
5906 // Process placeholders immediately.
5907 if (From->hasPlaceholderType()) {
5908 ExprResult result = CheckPlaceholderExpr(From);
5909 if (result.isInvalid())
5910 return result;
5911 From = result.get();
5912 }
5913
5914 // If the expression already has a matching type, we're golden.
5915 QualType T = From->getType();
5916 if (Converter.match(T))
5917 return DefaultLvalueConversion(From);
5918
5919 // FIXME: Check for missing '()' if T is a function type?
5920
5921 // We can only perform contextual implicit conversions on objects of class
5922 // type.
5923 const RecordType *RecordTy = T->getAs<RecordType>();
5924 if (!RecordTy || !getLangOpts().CPlusPlus) {
5925 if (!Converter.Suppress)
5926 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5927 return From;
5928 }
5929
5930 // We must have a complete class type.
5931 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5932 ContextualImplicitConverter &Converter;
5933 Expr *From;
5934
5935 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5936 : Converter(Converter), From(From) {}
5937
5938 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5939 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5940 }
5941 } IncompleteDiagnoser(Converter, From);
5942
5943 if (Converter.Suppress ? !isCompleteType(Loc, T)
5944 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5945 return From;
5946
5947 // Look for a conversion to an integral or enumeration type.
5948 UnresolvedSet<4>
5949 ViableConversions; // These are *potentially* viable in C++1y.
5950 UnresolvedSet<4> ExplicitConversions;
5951 const auto &Conversions =
5952 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5953
5954 bool HadMultipleCandidates =
5955 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5956
5957 // To check that there is only one target type, in C++1y:
5958 QualType ToType;
5959 bool HasUniqueTargetType = true;
5960
5961 // Collect explicit or viable (potentially in C++1y) conversions.
5962 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5963 NamedDecl *D = (*I)->getUnderlyingDecl();
5964 CXXConversionDecl *Conversion;
5965 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5966 if (ConvTemplate) {
5967 if (getLangOpts().CPlusPlus14)
5968 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5969 else
5970 continue; // C++11 does not consider conversion operator templates(?).
5971 } else
5972 Conversion = cast<CXXConversionDecl>(D);
5973
5974 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5976, __PRETTY_FUNCTION__))
5975 "Conversion operator templates are considered potentially "(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5976, __PRETTY_FUNCTION__))
5976 "viable in C++1y")(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5976, __PRETTY_FUNCTION__))
;
5977
5978 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5979 if (Converter.match(CurToType) || ConvTemplate) {
5980
5981 if (Conversion->isExplicit()) {
5982 // FIXME: For C++1y, do we need this restriction?
5983 // cf. diagnoseNoViableConversion()
5984 if (!ConvTemplate)
5985 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5986 } else {
5987 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5988 if (ToType.isNull())
5989 ToType = CurToType.getUnqualifiedType();
5990 else if (HasUniqueTargetType &&
5991 (CurToType.getUnqualifiedType() != ToType))
5992 HasUniqueTargetType = false;
5993 }
5994 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5995 }
5996 }
5997 }
5998
5999 if (getLangOpts().CPlusPlus14) {
6000 // C++1y [conv]p6:
6001 // ... An expression e of class type E appearing in such a context
6002 // is said to be contextually implicitly converted to a specified
6003 // type T and is well-formed if and only if e can be implicitly
6004 // converted to a type T that is determined as follows: E is searched
6005 // for conversion functions whose return type is cv T or reference to
6006 // cv T such that T is allowed by the context. There shall be
6007 // exactly one such T.
6008
6009 // If no unique T is found:
6010 if (ToType.isNull()) {
6011 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6012 HadMultipleCandidates,
6013 ExplicitConversions))
6014 return ExprError();
6015 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6016 }
6017
6018 // If more than one unique Ts are found:
6019 if (!HasUniqueTargetType)
6020 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6021 ViableConversions);
6022
6023 // If one unique T is found:
6024 // First, build a candidate set from the previously recorded
6025 // potentially viable conversions.
6026 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6027 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6028 CandidateSet);
6029
6030 // Then, perform overload resolution over the candidate set.
6031 OverloadCandidateSet::iterator Best;
6032 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6033 case OR_Success: {
6034 // Apply this conversion.
6035 DeclAccessPair Found =
6036 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6037 if (recordConversion(*this, Loc, From, Converter, T,
6038 HadMultipleCandidates, Found))
6039 return ExprError();
6040 break;
6041 }
6042 case OR_Ambiguous:
6043 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6044 ViableConversions);
6045 case OR_No_Viable_Function:
6046 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6047 HadMultipleCandidates,
6048 ExplicitConversions))
6049 return ExprError();
6050 LLVM_FALLTHROUGH[[gnu::fallthrough]];
6051 case OR_Deleted:
6052 // We'll complain below about a non-integral condition type.
6053 break;
6054 }
6055 } else {
6056 switch (ViableConversions.size()) {
6057 case 0: {
6058 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6059 HadMultipleCandidates,
6060 ExplicitConversions))
6061 return ExprError();
6062
6063 // We'll complain below about a non-integral condition type.
6064 break;
6065 }
6066 case 1: {
6067 // Apply this conversion.
6068 DeclAccessPair Found = ViableConversions[0];
6069 if (recordConversion(*this, Loc, From, Converter, T,
6070 HadMultipleCandidates, Found))
6071 return ExprError();
6072 break;
6073 }
6074 default:
6075 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6076 ViableConversions);
6077 }
6078 }
6079
6080 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6081}
6082
6083/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6084/// an acceptable non-member overloaded operator for a call whose
6085/// arguments have types T1 (and, if non-empty, T2). This routine
6086/// implements the check in C++ [over.match.oper]p3b2 concerning
6087/// enumeration types.
6088static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6089 FunctionDecl *Fn,
6090 ArrayRef<Expr *> Args) {
6091 QualType T1 = Args[0]->getType();
6092 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6093
6094 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6095 return true;
6096
6097 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6098 return true;
6099
6100 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
6101 if (Proto->getNumParams() < 1)
6102 return false;
6103
6104 if (T1->isEnumeralType()) {
6105 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6106 if (Context.hasSameUnqualifiedType(T1, ArgType))
6107 return true;
6108 }
6109
6110 if (Proto->getNumParams() < 2)
6111 return false;
6112
6113 if (!T2.isNull() && T2->isEnumeralType()) {
6114 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6115 if (Context.hasSameUnqualifiedType(T2, ArgType))
6116 return true;
6117 }
6118
6119 return false;
6120}
6121
6122/// AddOverloadCandidate - Adds the given function to the set of
6123/// candidate functions, using the given function call arguments. If
6124/// @p SuppressUserConversions, then don't allow user-defined
6125/// conversions via constructors or conversion operators.
6126///
6127/// \param PartialOverloading true if we are performing "partial" overloading
6128/// based on an incomplete set of function arguments. This feature is used by
6129/// code completion.
6130void Sema::AddOverloadCandidate(
6131 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6132 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6133 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6134 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6135 OverloadCandidateParamOrder PO) {
6136 const FunctionProtoType *Proto
6137 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6138 assert(Proto && "Functions without a prototype cannot be overloaded")((Proto && "Functions without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6138, __PRETTY_FUNCTION__))
;
6139 assert(!Function->getDescribedFunctionTemplate() &&((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6140, __PRETTY_FUNCTION__))
6140 "Use AddTemplateOverloadCandidate for function templates")((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6140, __PRETTY_FUNCTION__))
;
6141
6142 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6143 if (!isa<CXXConstructorDecl>(Method)) {
6144 // If we get here, it's because we're calling a member function
6145 // that is named without a member access expression (e.g.,
6146 // "this->f") that was either written explicitly or created
6147 // implicitly. This can happen with a qualified call to a member
6148 // function, e.g., X::f(). We use an empty type for the implied
6149 // object argument (C++ [over.call.func]p3), and the acting context
6150 // is irrelevant.
6151 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6152 Expr::Classification::makeSimpleLValue(), Args,
6153 CandidateSet, SuppressUserConversions,
6154 PartialOverloading, EarlyConversions, PO);
6155 return;
6156 }
6157 // We treat a constructor like a non-member function, since its object
6158 // argument doesn't participate in overload resolution.
6159 }
6160
6161 if (!CandidateSet.isNewCandidate(Function, PO))
6162 return;
6163
6164 // C++11 [class.copy]p11: [DR1402]
6165 // A defaulted move constructor that is defined as deleted is ignored by
6166 // overload resolution.
6167 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6168 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6169 Constructor->isMoveConstructor())
6170 return;
6171
6172 // Overload resolution is always an unevaluated context.
6173 EnterExpressionEvaluationContext Unevaluated(
6174 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6175
6176 // C++ [over.match.oper]p3:
6177 // if no operand has a class type, only those non-member functions in the
6178 // lookup set that have a first parameter of type T1 or "reference to
6179 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6180 // is a right operand) a second parameter of type T2 or "reference to
6181 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6182 // candidate functions.
6183 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6184 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6185 return;
6186
6187 // Add this candidate
6188 OverloadCandidate &Candidate =
6189 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6190 Candidate.FoundDecl = FoundDecl;
6191 Candidate.Function = Function;
6192 Candidate.Viable = true;
6193 Candidate.RewriteKind =
6194 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6195 Candidate.IsSurrogate = false;
6196 Candidate.IsADLCandidate = IsADLCandidate;
6197 Candidate.IgnoreObjectArgument = false;
6198 Candidate.ExplicitCallArguments = Args.size();
6199
6200 // Explicit functions are not actually candidates at all if we're not
6201 // allowing them in this context, but keep them around so we can point
6202 // to them in diagnostics.
6203 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6204 Candidate.Viable = false;
6205 Candidate.FailureKind = ovl_fail_explicit;
6206 return;
6207 }
6208
6209 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6210 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6211 Candidate.Viable = false;
6212 Candidate.FailureKind = ovl_non_default_multiversion_function;
6213 return;
6214 }
6215
6216 if (Constructor) {
6217 // C++ [class.copy]p3:
6218 // A member function template is never instantiated to perform the copy
6219 // of a class object to an object of its class type.
6220 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6221 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6222 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6223 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6224 ClassType))) {
6225 Candidate.Viable = false;
6226 Candidate.FailureKind = ovl_fail_illegal_constructor;
6227 return;
6228 }
6229
6230 // C++ [over.match.funcs]p8: (proposed DR resolution)
6231 // A constructor inherited from class type C that has a first parameter
6232 // of type "reference to P" (including such a constructor instantiated
6233 // from a template) is excluded from the set of candidate functions when
6234 // constructing an object of type cv D if the argument list has exactly
6235 // one argument and D is reference-related to P and P is reference-related
6236 // to C.
6237 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6238 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6239 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6240 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6241 QualType C = Context.getRecordType(Constructor->getParent());
6242 QualType D = Context.getRecordType(Shadow->getParent());
6243 SourceLocation Loc = Args.front()->getExprLoc();
6244 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6245 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6246 Candidate.Viable = false;
6247 Candidate.FailureKind = ovl_fail_inhctor_slice;
6248 return;
6249 }
6250 }
6251
6252 // Check that the constructor is capable of constructing an object in the
6253 // destination address space.
6254 if (!Qualifiers::isAddressSpaceSupersetOf(
6255 Constructor->getMethodQualifiers().getAddressSpace(),
6256 CandidateSet.getDestAS())) {
6257 Candidate.Viable = false;
6258 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6259 }
6260 }
6261
6262 unsigned NumParams = Proto->getNumParams();
6263
6264 // (C++ 13.3.2p2): A candidate function having fewer than m
6265 // parameters is viable only if it has an ellipsis in its parameter
6266 // list (8.3.5).
6267 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6268 !Proto->isVariadic()) {
6269 Candidate.Viable = false;
6270 Candidate.FailureKind = ovl_fail_too_many_arguments;
6271 return;
6272 }
6273
6274 // (C++ 13.3.2p2): A candidate function having more than m parameters
6275 // is viable only if the (m+1)st parameter has a default argument
6276 // (8.3.6). For the purposes of overload resolution, the
6277 // parameter list is truncated on the right, so that there are
6278 // exactly m parameters.
6279 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6280 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6281 // Not enough arguments.
6282 Candidate.Viable = false;
6283 Candidate.FailureKind = ovl_fail_too_few_arguments;
6284 return;
6285 }
6286
6287 // (CUDA B.1): Check for invalid calls between targets.
6288 if (getLangOpts().CUDA)
6289 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6290 // Skip the check for callers that are implicit members, because in this
6291 // case we may not yet know what the member's target is; the target is
6292 // inferred for the member automatically, based on the bases and fields of
6293 // the class.
6294 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6295 Candidate.Viable = false;
6296 Candidate.FailureKind = ovl_fail_bad_target;
6297 return;
6298 }
6299
6300 if (Expr *RequiresClause = Function->getTrailingRequiresClause()) {
6301 ConstraintSatisfaction Satisfaction;
6302 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) ||
6303 !Satisfaction.IsSatisfied) {
6304 Candidate.Viable = false;
6305 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6306 return;
6307 }
6308 }
6309
6310 // Determine the implicit conversion sequences for each of the
6311 // arguments.
6312 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6313 unsigned ConvIdx =
6314 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6315 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6316 // We already formed a conversion sequence for this parameter during
6317 // template argument deduction.
6318 } else if (ArgIdx < NumParams) {
6319 // (C++ 13.3.2p3): for F to be a viable function, there shall
6320 // exist for each argument an implicit conversion sequence
6321 // (13.3.3.1) that converts that argument to the corresponding
6322 // parameter of F.
6323 QualType ParamType = Proto->getParamType(ArgIdx);
6324 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6325 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6326 /*InOverloadResolution=*/true,
6327 /*AllowObjCWritebackConversion=*/
6328 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6329 if (Candidate.Conversions[ConvIdx].isBad()) {
6330 Candidate.Viable = false;
6331 Candidate.FailureKind = ovl_fail_bad_conversion;
6332 return;
6333 }
6334 } else {
6335 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6336 // argument for which there is no corresponding parameter is
6337 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6338 Candidate.Conversions[ConvIdx].setEllipsis();
6339 }
6340 }
6341
6342 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6343 Candidate.Viable = false;
6344 Candidate.FailureKind = ovl_fail_enable_if;
6345 Candidate.DeductionFailure.Data = FailedAttr;
6346 return;
6347 }
6348
6349 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6350 Candidate.Viable = false;
6351 Candidate.FailureKind = ovl_fail_ext_disabled;
6352 return;
6353 }
6354}
6355
6356ObjCMethodDecl *
6357Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6358 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6359 if (Methods.size() <= 1)
6360 return nullptr;
6361
6362 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6363 bool Match = true;
6364 ObjCMethodDecl *Method = Methods[b];
6365 unsigned NumNamedArgs = Sel.getNumArgs();
6366 // Method might have more arguments than selector indicates. This is due
6367 // to addition of c-style arguments in method.
6368 if (Method->param_size() > NumNamedArgs)
6369 NumNamedArgs = Method->param_size();
6370 if (Args.size() < NumNamedArgs)
6371 continue;
6372
6373 for (unsigned i = 0; i < NumNamedArgs; i++) {
6374 // We can't do any type-checking on a type-dependent argument.
6375 if (Args[i]->isTypeDependent()) {
6376 Match = false;
6377 break;
6378 }
6379
6380 ParmVarDecl *param = Method->parameters()[i];
6381 Expr *argExpr = Args[i];
6382 assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6382, __PRETTY_FUNCTION__))
;
6383
6384 // Strip the unbridged-cast placeholder expression off unless it's
6385 // a consumed argument.
6386 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6387 !param->hasAttr<CFConsumedAttr>())
6388 argExpr = stripARCUnbridgedCast(argExpr);
6389
6390 // If the parameter is __unknown_anytype, move on to the next method.
6391 if (param->getType() == Context.UnknownAnyTy) {
6392 Match = false;
6393 break;
6394 }
6395
6396 ImplicitConversionSequence ConversionState
6397 = TryCopyInitialization(*this, argExpr, param->getType(),
6398 /*SuppressUserConversions*/false,
6399 /*InOverloadResolution=*/true,
6400 /*AllowObjCWritebackConversion=*/
6401 getLangOpts().ObjCAutoRefCount,
6402 /*AllowExplicit*/false);
6403 // This function looks for a reasonably-exact match, so we consider
6404 // incompatible pointer conversions to be a failure here.
6405 if (ConversionState.isBad() ||
6406 (ConversionState.isStandard() &&
6407 ConversionState.Standard.Second ==
6408 ICK_Incompatible_Pointer_Conversion)) {
6409 Match = false;
6410 break;
6411 }
6412 }
6413 // Promote additional arguments to variadic methods.
6414 if (Match && Method->isVariadic()) {
6415 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6416 if (Args[i]->isTypeDependent()) {
6417 Match = false;
6418 break;
6419 }
6420 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6421 nullptr);
6422 if (Arg.isInvalid()) {
6423 Match = false;
6424 break;
6425 }
6426 }
6427 } else {
6428 // Check for extra arguments to non-variadic methods.
6429 if (Args.size() != NumNamedArgs)
6430 Match = false;
6431 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6432 // Special case when selectors have no argument. In this case, select
6433 // one with the most general result type of 'id'.
6434 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6435 QualType ReturnT = Methods[b]->getReturnType();
6436 if (ReturnT->isObjCIdType())
6437 return Methods[b];
6438 }
6439 }
6440 }
6441
6442 if (Match)
6443 return Method;
6444 }
6445 return nullptr;
6446}
6447
6448static bool
6449convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6450 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6451 bool MissingImplicitThis, Expr *&ConvertedThis,
6452 SmallVectorImpl<Expr *> &ConvertedArgs) {
6453 if (ThisArg) {
6454 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6455 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6456, __PRETTY_FUNCTION__))
6456 "Shouldn't have `this` for ctors!")((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6456, __PRETTY_FUNCTION__))
;
6457 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")((!Method->isStatic() && "Shouldn't have `this` for static methods!"
) ? static_cast<void> (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6457, __PRETTY_FUNCTION__))
;
6458 ExprResult R = S.PerformObjectArgumentInitialization(
6459 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6460 if (R.isInvalid())
6461 return false;
6462 ConvertedThis = R.get();
6463 } else {
6464 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6465 (void)MD;
6466 assert((MissingImplicitThis || MD->isStatic() ||(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6468, __PRETTY_FUNCTION__))
6467 isa<CXXConstructorDecl>(MD)) &&(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6468, __PRETTY_FUNCTION__))
6468 "Expected `this` for non-ctor instance methods")(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6468, __PRETTY_FUNCTION__))
;
6469 }
6470 ConvertedThis = nullptr;
6471 }
6472
6473 // Ignore any variadic arguments. Converting them is pointless, since the
6474 // user can't refer to them in the function condition.
6475 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6476
6477 // Convert the arguments.
6478 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6479 ExprResult R;
6480 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6481 S.Context, Function->getParamDecl(I)),
6482 SourceLocation(), Args[I]);
6483
6484 if (R.isInvalid())
6485 return false;
6486
6487 ConvertedArgs.push_back(R.get());
6488 }
6489
6490 if (Trap.hasErrorOccurred())
6491 return false;
6492
6493 // Push default arguments if needed.
6494 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6495 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6496 ParmVarDecl *P = Function->getParamDecl(i);
6497 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6498 ? P->getUninstantiatedDefaultArg()
6499 : P->getDefaultArg();
6500 // This can only happen in code completion, i.e. when PartialOverloading
6501 // is true.
6502 if (!DefArg)
6503 return false;
6504 ExprResult R =
6505 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6506 S.Context, Function->getParamDecl(i)),
6507 SourceLocation(), DefArg);
6508 if (R.isInvalid())
6509 return false;
6510 ConvertedArgs.push_back(R.get());
6511 }
6512
6513 if (Trap.hasErrorOccurred())
6514 return false;
6515 }
6516 return true;
6517}
6518
6519EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6520 bool MissingImplicitThis) {
6521 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6522 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6523 return nullptr;
6524
6525 SFINAETrap Trap(*this);
6526 SmallVector<Expr *, 16> ConvertedArgs;
6527 // FIXME: We should look into making enable_if late-parsed.
6528 Expr *DiscardedThis;
6529 if (!convertArgsForAvailabilityChecks(
6530 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6531 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6532 return *EnableIfAttrs.begin();
6533
6534 for (auto *EIA : EnableIfAttrs) {
6535 APValue Result;
6536 // FIXME: This doesn't consider value-dependent cases, because doing so is
6537 // very difficult. Ideally, we should handle them more gracefully.
6538 if (EIA->getCond()->isValueDependent() ||
6539 !EIA->getCond()->EvaluateWithSubstitution(
6540 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6541 return EIA;
6542
6543 if (!Result.isInt() || !Result.getInt().getBoolValue())
6544 return EIA;
6545 }
6546 return nullptr;
6547}
6548
6549template <typename CheckFn>
6550static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6551 bool ArgDependent, SourceLocation Loc,
6552 CheckFn &&IsSuccessful) {
6553 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6554 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6555 if (ArgDependent == DIA->getArgDependent())
6556 Attrs.push_back(DIA);
6557 }
6558
6559 // Common case: No diagnose_if attributes, so we can quit early.
6560 if (Attrs.empty())
6561 return false;
6562
6563 auto WarningBegin = std::stable_partition(
6564 Attrs.begin(), Attrs.end(),
6565 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6566
6567 // Note that diagnose_if attributes are late-parsed, so they appear in the
6568 // correct order (unlike enable_if attributes).
6569 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6570 IsSuccessful);
6571 if (ErrAttr != WarningBegin) {
6572 const DiagnoseIfAttr *DIA = *ErrAttr;
6573 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6574 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6575 << DIA->getParent() << DIA->getCond()->getSourceRange();
6576 return true;
6577 }
6578
6579 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6580 if (IsSuccessful(DIA)) {
6581 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6582 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6583 << DIA->getParent() << DIA->getCond()->getSourceRange();
6584 }
6585
6586 return false;
6587}
6588
6589bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6590 const Expr *ThisArg,
6591 ArrayRef<const Expr *> Args,
6592 SourceLocation Loc) {
6593 return diagnoseDiagnoseIfAttrsWith(
6594 *this, Function, /*ArgDependent=*/true, Loc,
6595 [&](const DiagnoseIfAttr *DIA) {
6596 APValue Result;
6597 // It's sane to use the same Args for any redecl of this function, since
6598 // EvaluateWithSubstitution only cares about the position of each
6599 // argument in the arg list, not the ParmVarDecl* it maps to.
6600 if (!DIA->getCond()->EvaluateWithSubstitution(
6601 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6602 return false;
6603 return Result.isInt() && Result.getInt().getBoolValue();
6604 });
6605}
6606
6607bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6608 SourceLocation Loc) {
6609 return diagnoseDiagnoseIfAttrsWith(
6610 *this, ND, /*ArgDependent=*/false, Loc,
6611 [&](const DiagnoseIfAttr *DIA) {
6612 bool Result;
6613 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6614 Result;
6615 });
6616}
6617
6618/// Add all of the function declarations in the given function set to
6619/// the overload candidate set.
6620void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6621 ArrayRef<Expr *> Args,
6622 OverloadCandidateSet &CandidateSet,
6623 TemplateArgumentListInfo *ExplicitTemplateArgs,
6624 bool SuppressUserConversions,
6625 bool PartialOverloading,
6626 bool FirstArgumentIsBase) {
6627 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6628 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6629 ArrayRef<Expr *> FunctionArgs = Args;
6630
6631 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6632 FunctionDecl *FD =
6633 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6634
6635 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6636 QualType ObjectType;
6637 Expr::Classification ObjectClassification;
6638 if (Args.size() > 0) {
6639 if (Expr *E = Args[0]) {
6640 // Use the explicit base to restrict the lookup:
6641 ObjectType = E->getType();
6642 // Pointers in the object arguments are implicitly dereferenced, so we
6643 // always classify them as l-values.
6644 if (!ObjectType.isNull() && ObjectType->isPointerType())
6645 ObjectClassification = Expr::Classification::makeSimpleLValue();
6646 else
6647 ObjectClassification = E->Classify(Context);
6648 } // .. else there is an implicit base.
6649 FunctionArgs = Args.slice(1);
6650 }
6651 if (FunTmpl) {
6652 AddMethodTemplateCandidate(
6653 FunTmpl, F.getPair(),
6654 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6655 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6656 FunctionArgs, CandidateSet, SuppressUserConversions,
6657 PartialOverloading);
6658 } else {
6659 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6660 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6661 ObjectClassification, FunctionArgs, CandidateSet,
6662 SuppressUserConversions, PartialOverloading);
6663 }
6664 } else {
6665 // This branch handles both standalone functions and static methods.
6666
6667 // Slice the first argument (which is the base) when we access
6668 // static method as non-static.
6669 if (Args.size() > 0 &&
6670 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6671 !isa<CXXConstructorDecl>(FD)))) {
6672 assert(cast<CXXMethodDecl>(FD)->isStatic())((cast<CXXMethodDecl>(FD)->isStatic()) ? static_cast
<void> (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6672, __PRETTY_FUNCTION__))
;
6673 FunctionArgs = Args.slice(1);
6674 }
6675 if (FunTmpl) {
6676 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6677 ExplicitTemplateArgs, FunctionArgs,
6678 CandidateSet, SuppressUserConversions,
6679 PartialOverloading);
6680 } else {
6681 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6682 SuppressUserConversions, PartialOverloading);
6683 }
6684 }
6685 }
6686}
6687
6688/// AddMethodCandidate - Adds a named decl (which is some kind of
6689/// method) as a method candidate to the given overload set.
6690void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6691 Expr::Classification ObjectClassification,
6692 ArrayRef<Expr *> Args,
6693 OverloadCandidateSet &CandidateSet,
6694 bool SuppressUserConversions,
6695 OverloadCandidateParamOrder PO) {
6696 NamedDecl *Decl = FoundDecl.getDecl();
6697 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6698
6699 if (isa<UsingShadowDecl>(Decl))
6700 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6701
6702 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6703 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6704, __PRETTY_FUNCTION__))
6704 "Expected a member function template")((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6704, __PRETTY_FUNCTION__))
;
6705 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6706 /*ExplicitArgs*/ nullptr, ObjectType,
6707 ObjectClassification, Args, CandidateSet,
6708 SuppressUserConversions, false, PO);
6709 } else {
6710 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6711 ObjectType, ObjectClassification, Args, CandidateSet,
6712 SuppressUserConversions, false, None, PO);
6713 }
6714}
6715
6716/// AddMethodCandidate - Adds the given C++ member function to the set
6717/// of candidate functions, using the given function call arguments
6718/// and the object argument (@c Object). For example, in a call
6719/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6720/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6721/// allow user-defined conversions via constructors or conversion
6722/// operators.
6723void
6724Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6725 CXXRecordDecl *ActingContext, QualType ObjectType,
6726 Expr::Classification ObjectClassification,
6727 ArrayRef<Expr *> Args,
6728 OverloadCandidateSet &CandidateSet,
6729 bool SuppressUserConversions,
6730 bool PartialOverloading,
6731 ConversionSequenceList EarlyConversions,
6732 OverloadCandidateParamOrder PO) {
6733 const FunctionProtoType *Proto
6734 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6735 assert(Proto && "Methods without a prototype cannot be overloaded")((Proto && "Methods without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6735, __PRETTY_FUNCTION__))
;
6736 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6737, __PRETTY_FUNCTION__))
6737 "Use AddOverloadCandidate for constructors")((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6737, __PRETTY_FUNCTION__))
;
6738
6739 if (!CandidateSet.isNewCandidate(Method, PO))
6740 return;
6741
6742 // C++11 [class.copy]p23: [DR1402]
6743 // A defaulted move assignment operator that is defined as deleted is
6744 // ignored by overload resolution.
6745 if (Method->isDefaulted() && Method->isDeleted() &&
6746 Method->isMoveAssignmentOperator())
6747 return;
6748
6749 // Overload resolution is always an unevaluated context.
6750 EnterExpressionEvaluationContext Unevaluated(
6751 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6752
6753 // Add this candidate
6754 OverloadCandidate &Candidate =
6755 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6756 Candidate.FoundDecl = FoundDecl;
6757 Candidate.Function = Method;
6758 Candidate.RewriteKind =
6759 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6760 Candidate.IsSurrogate = false;
6761 Candidate.IgnoreObjectArgument = false;
6762 Candidate.ExplicitCallArguments = Args.size();
6763
6764 unsigned NumParams = Proto->getNumParams();
6765
6766 // (C++ 13.3.2p2): A candidate function having fewer than m
6767 // parameters is viable only if it has an ellipsis in its parameter
6768 // list (8.3.5).
6769 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6770 !Proto->isVariadic()) {
6771 Candidate.Viable = false;
6772 Candidate.FailureKind = ovl_fail_too_many_arguments;
6773 return;
6774 }
6775
6776 // (C++ 13.3.2p2): A candidate function having more than m parameters
6777 // is viable only if the (m+1)st parameter has a default argument
6778 // (8.3.6). For the purposes of overload resolution, the
6779 // parameter list is truncated on the right, so that there are
6780 // exactly m parameters.
6781 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6782 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6783 // Not enough arguments.
6784 Candidate.Viable = false;
6785 Candidate.FailureKind = ovl_fail_too_few_arguments;
6786 return;
6787 }
6788
6789 Candidate.Viable = true;
6790
6791 if (Method->isStatic() || ObjectType.isNull())
6792 // The implicit object argument is ignored.
6793 Candidate.IgnoreObjectArgument = true;
6794 else {
6795 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6796 // Determine the implicit conversion sequence for the object
6797 // parameter.
6798 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6799 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6800 Method, ActingContext);
6801 if (Candidate.Conversions[ConvIdx].isBad()) {
6802 Candidate.Viable = false;
6803 Candidate.FailureKind = ovl_fail_bad_conversion;
6804 return;
6805 }
6806 }
6807
6808 // (CUDA B.1): Check for invalid calls between targets.
6809 if (getLangOpts().CUDA)
6810 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6811 if (!IsAllowedCUDACall(Caller, Method)) {
6812 Candidate.Viable = false;
6813 Candidate.FailureKind = ovl_fail_bad_target;
6814 return;
6815 }
6816
6817 if (Expr *RequiresClause = Method->getTrailingRequiresClause()) {
6818 ConstraintSatisfaction Satisfaction;
6819 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) ||
6820 !Satisfaction.IsSatisfied) {
6821 Candidate.Viable = false;
6822 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6823 return;
6824 }
6825 }
6826
6827 // Determine the implicit conversion sequences for each of the
6828 // arguments.
6829 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6830 unsigned ConvIdx =
6831 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6832 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6833 // We already formed a conversion sequence for this parameter during
6834 // template argument deduction.
6835 } else if (ArgIdx < NumParams) {
6836 // (C++ 13.3.2p3): for F to be a viable function, there shall
6837 // exist for each argument an implicit conversion sequence
6838 // (13.3.3.1) that converts that argument to the corresponding
6839 // parameter of F.
6840 QualType ParamType = Proto->getParamType(ArgIdx);
6841 Candidate.Conversions[ConvIdx]
6842 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6843 SuppressUserConversions,
6844 /*InOverloadResolution=*/true,
6845 /*AllowObjCWritebackConversion=*/
6846 getLangOpts().ObjCAutoRefCount);
6847 if (Candidate.Conversions[ConvIdx].isBad()) {
6848 Candidate.Viable = false;
6849 Candidate.FailureKind = ovl_fail_bad_conversion;
6850 return;
6851 }
6852 } else {
6853 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6854 // argument for which there is no corresponding parameter is
6855 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6856 Candidate.Conversions[ConvIdx].setEllipsis();
6857 }
6858 }
6859
6860 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6861 Candidate.Viable = false;
6862 Candidate.FailureKind = ovl_fail_enable_if;
6863 Candidate.DeductionFailure.Data = FailedAttr;
6864 return;
6865 }
6866
6867 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6868 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6869 Candidate.Viable = false;
6870 Candidate.FailureKind = ovl_non_default_multiversion_function;
6871 }
6872}
6873
6874/// Add a C++ member function template as a candidate to the candidate
6875/// set, using template argument deduction to produce an appropriate member
6876/// function template specialization.
6877void Sema::AddMethodTemplateCandidate(
6878 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6879 CXXRecordDecl *ActingContext,
6880 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6881 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6882 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6883 bool PartialOverloading, OverloadCandidateParamOrder PO) {
6884 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6885 return;
6886
6887 // C++ [over.match.funcs]p7:
6888 // In each case where a candidate is a function template, candidate
6889 // function template specializations are generated using template argument
6890 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6891 // candidate functions in the usual way.113) A given name can refer to one
6892 // or more function templates and also to a set of overloaded non-template
6893 // functions. In such a case, the candidate functions generated from each
6894 // function template are combined with the set of non-template candidate
6895 // functions.
6896 TemplateDeductionInfo Info(CandidateSet.getLocation());
6897 FunctionDecl *Specialization = nullptr;
6898 ConversionSequenceList Conversions;
6899 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6900 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6901 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6902 return CheckNonDependentConversions(
6903 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6904 SuppressUserConversions, ActingContext, ObjectType,
6905 ObjectClassification, PO);
6906 })) {
6907 OverloadCandidate &Candidate =
6908 CandidateSet.addCandidate(Conversions.size(), Conversions);
6909 Candidate.FoundDecl = FoundDecl;
6910 Candidate.Function = MethodTmpl->getTemplatedDecl();
6911 Candidate.Viable = false;
6912 Candidate.RewriteKind =
6913 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6914 Candidate.IsSurrogate = false;
6915 Candidate.IgnoreObjectArgument =
6916 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6917 ObjectType.isNull();
6918 Candidate.ExplicitCallArguments = Args.size();
6919 if (Result == TDK_NonDependentConversionFailure)
6920 Candidate.FailureKind = ovl_fail_bad_conversion;
6921 else {
6922 Candidate.FailureKind = ovl_fail_bad_deduction;
6923 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6924 Info);
6925 }
6926 return;
6927 }
6928
6929 // Add the function template specialization produced by template argument
6930 // deduction as a candidate.
6931 assert(Specialization && "Missing member function template specialization?")((Specialization && "Missing member function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6931, __PRETTY_FUNCTION__))
;
6932 assert(isa<CXXMethodDecl>(Specialization) &&((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6933, __PRETTY_FUNCTION__))
6933 "Specialization is not a member function?")((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6933, __PRETTY_FUNCTION__))
;
6934 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6935 ActingContext, ObjectType, ObjectClassification, Args,
6936 CandidateSet, SuppressUserConversions, PartialOverloading,
6937 Conversions, PO);
6938}
6939
6940/// Determine whether a given function template has a simple explicit specifier
6941/// or a non-value-dependent explicit-specification that evaluates to true.
6942static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6943 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6944}
6945
6946/// Add a C++ function template specialization as a candidate
6947/// in the candidate set, using template argument deduction to produce
6948/// an appropriate function template specialization.
6949void Sema::AddTemplateOverloadCandidate(
6950 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6951 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6952 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6953 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6954 OverloadCandidateParamOrder PO) {
6955 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6956 return;
6957
6958 // If the function template has a non-dependent explicit specification,
6959 // exclude it now if appropriate; we are not permitted to perform deduction
6960 // and substitution in this case.
6961 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6962 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6963 Candidate.FoundDecl = FoundDecl;
6964 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6965 Candidate.Viable = false;
6966 Candidate.FailureKind = ovl_fail_explicit;
6967 return;
6968 }
6969
6970 // C++ [over.match.funcs]p7:
6971 // In each case where a candidate is a function template, candidate
6972 // function template specializations are generated using template argument
6973 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6974 // candidate functions in the usual way.113) A given name can refer to one
6975 // or more function templates and also to a set of overloaded non-template
6976 // functions. In such a case, the candidate functions generated from each
6977 // function template are combined with the set of non-template candidate
6978 // functions.
6979 TemplateDeductionInfo Info(CandidateSet.getLocation());
6980 FunctionDecl *Specialization = nullptr;
6981 ConversionSequenceList Conversions;
6982 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6983 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6984 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6985 return CheckNonDependentConversions(
6986 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
6987 SuppressUserConversions, nullptr, QualType(), {}, PO);
6988 })) {
6989 OverloadCandidate &Candidate =
6990 CandidateSet.addCandidate(Conversions.size(), Conversions);
6991 Candidate.FoundDecl = FoundDecl;
6992 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6993 Candidate.Viable = false;
6994 Candidate.RewriteKind =
6995 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6996 Candidate.IsSurrogate = false;
6997 Candidate.IsADLCandidate = IsADLCandidate;
6998 // Ignore the object argument if there is one, since we don't have an object
6999 // type.
7000 Candidate.IgnoreObjectArgument =
7001 isa<CXXMethodDecl>(Candidate.Function) &&
7002 !isa<CXXConstructorDecl>(Candidate.Function);
7003 Candidate.ExplicitCallArguments = Args.size();
7004 if (Result == TDK_NonDependentConversionFailure)
7005 Candidate.FailureKind = ovl_fail_bad_conversion;
7006 else {
7007 Candidate.FailureKind = ovl_fail_bad_deduction;
7008 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7009 Info);
7010 }
7011 return;
7012 }
7013
7014 // Add the function template specialization produced by template argument
7015 // deduction as a candidate.
7016 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7016, __PRETTY_FUNCTION__))
;
7017 AddOverloadCandidate(
7018 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7019 PartialOverloading, AllowExplicit,
7020 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7021}
7022
7023/// Check that implicit conversion sequences can be formed for each argument
7024/// whose corresponding parameter has a non-dependent type, per DR1391's
7025/// [temp.deduct.call]p10.
7026bool Sema::CheckNonDependentConversions(
7027 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7028 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7029 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7030 CXXRecordDecl *ActingContext, QualType ObjectType,
7031 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7032 // FIXME: The cases in which we allow explicit conversions for constructor
7033 // arguments never consider calling a constructor template. It's not clear
7034 // that is correct.
7035 const bool AllowExplicit = false;
7036
7037 auto *FD = FunctionTemplate->getTemplatedDecl();
7038 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7039 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7040 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7041
7042 Conversions =
7043 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7044
7045 // Overload resolution is always an unevaluated context.
7046 EnterExpressionEvaluationContext Unevaluated(
7047 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7048
7049 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7050 // require that, but this check should never result in a hard error, and
7051 // overload resolution is permitted to sidestep instantiations.
7052 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7053 !ObjectType.isNull()) {
7054 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7055 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7056 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7057 Method, ActingContext);
7058 if (Conversions[ConvIdx].isBad())
7059 return true;
7060 }
7061
7062 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7063 ++I) {
7064 QualType ParamType = ParamTypes[I];
7065 if (!ParamType->isDependentType()) {
7066 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7067 ? 0
7068 : (ThisConversions + I);
7069 Conversions[ConvIdx]
7070 = TryCopyInitialization(*this, Args[I], ParamType,
7071 SuppressUserConversions,
7072 /*InOverloadResolution=*/true,
7073 /*AllowObjCWritebackConversion=*/
7074 getLangOpts().ObjCAutoRefCount,
7075 AllowExplicit);
7076 if (Conversions[ConvIdx].isBad())
7077 return true;
7078 }
7079 }
7080
7081 return false;
7082}
7083
7084/// Determine whether this is an allowable conversion from the result
7085/// of an explicit conversion operator to the expected type, per C++
7086/// [over.match.conv]p1 and [over.match.ref]p1.
7087///
7088/// \param ConvType The return type of the conversion function.
7089///
7090/// \param ToType The type we are converting to.
7091///
7092/// \param AllowObjCPointerConversion Allow a conversion from one
7093/// Objective-C pointer to another.
7094///
7095/// \returns true if the conversion is allowable, false otherwise.
7096static bool isAllowableExplicitConversion(Sema &S,
7097 QualType ConvType, QualType ToType,
7098 bool AllowObjCPointerConversion) {
7099 QualType ToNonRefType = ToType.getNonReferenceType();
7100
7101 // Easy case: the types are the same.
7102 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7103 return true;
7104
7105 // Allow qualification conversions.
7106 bool ObjCLifetimeConversion;
7107 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7108 ObjCLifetimeConversion))
7109 return true;
7110
7111 // If we're not allowed to consider Objective-C pointer conversions,
7112 // we're done.
7113 if (!AllowObjCPointerConversion)
7114 return false;
7115
7116 // Is this an Objective-C pointer conversion?
7117 bool IncompatibleObjC = false;
7118 QualType ConvertedType;
7119 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7120 IncompatibleObjC);
7121}
7122
7123/// AddConversionCandidate - Add a C++ conversion function as a
7124/// candidate in the candidate set (C++ [over.match.conv],
7125/// C++ [over.match.copy]). From is the expression we're converting from,
7126/// and ToType is the type that we're eventually trying to convert to
7127/// (which may or may not be the same type as the type that the
7128/// conversion function produces).
7129void Sema::AddConversionCandidate(
7130 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7131 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7132 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7133 bool AllowExplicit, bool AllowResultConversion) {
7134 assert(!Conversion->getDescribedFunctionTemplate() &&((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7135, __PRETTY_FUNCTION__))
7135 "Conversion function templates use AddTemplateConversionCandidate")((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7135, __PRETTY_FUNCTION__))
;
7136 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7137 if (!CandidateSet.isNewCandidate(Conversion))
7138 return;
7139
7140 // If the conversion function has an undeduced return type, trigger its
7141 // deduction now.
7142 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7143 if (DeduceReturnType(Conversion, From->getExprLoc()))
7144 return;
7145 ConvType = Conversion->getConversionType().getNonReferenceType();
7146 }
7147
7148 // If we don't allow any conversion of the result type, ignore conversion
7149 // functions that don't convert to exactly (possibly cv-qualified) T.
7150 if (!AllowResultConversion &&
7151 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7152 return;
7153
7154 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7155 // operator is only a candidate if its return type is the target type or
7156 // can be converted to the target type with a qualification conversion.
7157 //
7158 // FIXME: Include such functions in the candidate list and explain why we
7159 // can't select them.
7160 if (Conversion->isExplicit() &&
7161 !isAllowableExplicitConversion(*this, ConvType, ToType,
7162 AllowObjCConversionOnExplicit))
7163 return;
7164
7165 // Overload resolution is always an unevaluated context.
7166 EnterExpressionEvaluationContext Unevaluated(
7167 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7168
7169 // Add this candidate
7170 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7171 Candidate.FoundDecl = FoundDecl;
7172 Candidate.Function = Conversion;
7173 Candidate.IsSurrogate = false;
7174 Candidate.IgnoreObjectArgument = false;
7175 Candidate.FinalConversion.setAsIdentityConversion();
7176 Candidate.FinalConversion.setFromType(ConvType);
7177 Candidate.FinalConversion.setAllToTypes(ToType);
7178 Candidate.Viable = true;
7179 Candidate.ExplicitCallArguments = 1;
7180
7181 // Explicit functions are not actually candidates at all if we're not
7182 // allowing them in this context, but keep them around so we can point
7183 // to them in diagnostics.
7184 if (!AllowExplicit && Conversion->isExplicit()) {
7185 Candidate.Viable = false;
7186 Candidate.FailureKind = ovl_fail_explicit;
7187 return;
7188 }
7189
7190 // C++ [over.match.funcs]p4:
7191 // For conversion functions, the function is considered to be a member of
7192 // the class of the implicit implied object argument for the purpose of
7193 // defining the type of the implicit object parameter.
7194 //
7195 // Determine the implicit conversion sequence for the implicit
7196 // object parameter.
7197 QualType ImplicitParamType = From->getType();
7198 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7199 ImplicitParamType = FromPtrType->getPointeeType();
7200 CXXRecordDecl *ConversionContext
7201 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7202
7203 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7204 *this, CandidateSet.getLocation(), From->getType(),
7205 From->Classify(Context), Conversion, ConversionContext);
7206
7207 if (Candidate.Conversions[0].isBad()) {
7208 Candidate.Viable = false;
7209 Candidate.FailureKind = ovl_fail_bad_conversion;
7210 return;
7211 }
7212
7213 Expr *RequiresClause = Conversion->getTrailingRequiresClause();
7214 if (RequiresClause) {
7215 ConstraintSatisfaction Satisfaction;
7216 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) ||
7217 !Satisfaction.IsSatisfied) {
7218 Candidate.Viable = false;
7219 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7220 return;
7221 }
7222 }
7223
7224 // We won't go through a user-defined type conversion function to convert a
7225 // derived to base as such conversions are given Conversion Rank. They only
7226 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7227 QualType FromCanon
7228 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7229 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7230 if (FromCanon == ToCanon ||
7231 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7232 Candidate.Viable = false;
7233 Candidate.FailureKind = ovl_fail_trivial_conversion;
7234 return;
7235 }
7236
7237 // To determine what the conversion from the result of calling the
7238 // conversion function to the type we're eventually trying to
7239 // convert to (ToType), we need to synthesize a call to the
7240 // conversion function and attempt copy initialization from it. This
7241 // makes sure that we get the right semantics with respect to
7242 // lvalues/rvalues and the type. Fortunately, we can allocate this
7243 // call on the stack and we don't need its arguments to be
7244 // well-formed.
7245 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7246 VK_LValue, From->getBeginLoc());
7247 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7248 Context.getPointerType(Conversion->getType()),
7249 CK_FunctionToPointerDecay,
7250 &ConversionRef, VK_RValue);
7251
7252 QualType ConversionType = Conversion->getConversionType();
7253 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7254 Candidate.Viable = false;
7255 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7256 return;
7257 }
7258
7259 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7260
7261 // Note that it is safe to allocate CallExpr on the stack here because
7262 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7263 // allocator).
7264 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7265
7266 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7267 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7268 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7269
7270 ImplicitConversionSequence ICS =
7271 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7272 /*SuppressUserConversions=*/true,
7273 /*InOverloadResolution=*/false,
7274 /*AllowObjCWritebackConversion=*/false);
7275
7276 switch (ICS.getKind()) {
7277 case ImplicitConversionSequence::StandardConversion:
7278 Candidate.FinalConversion = ICS.Standard;
7279
7280 // C++ [over.ics.user]p3:
7281 // If the user-defined conversion is specified by a specialization of a
7282 // conversion function template, the second standard conversion sequence
7283 // shall have exact match rank.
7284 if (Conversion->getPrimaryTemplate() &&
7285 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7286 Candidate.Viable = false;
7287 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7288 return;
7289 }
7290
7291 // C++0x [dcl.init.ref]p5:
7292 // In the second case, if the reference is an rvalue reference and
7293 // the second standard conversion sequence of the user-defined
7294 // conversion sequence includes an lvalue-to-rvalue conversion, the
7295 // program is ill-formed.
7296 if (ToType->isRValueReferenceType() &&
7297 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7298 Candidate.Viable = false;
7299 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7300 return;
7301 }
7302 break;
7303
7304 case ImplicitConversionSequence::BadConversion:
7305 Candidate.Viable = false;
7306 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7307 return;
7308
7309 default:
7310 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7311)
7311 "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7311)
;
7312 }
7313
7314 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7315 Candidate.Viable = false;
7316 Candidate.FailureKind = ovl_fail_enable_if;
7317 Candidate.DeductionFailure.Data = FailedAttr;
7318 return;
7319 }
7320
7321 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7322 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7323 Candidate.Viable = false;
7324 Candidate.FailureKind = ovl_non_default_multiversion_function;
7325 }
7326}
7327
7328/// Adds a conversion function template specialization
7329/// candidate to the overload set, using template argument deduction
7330/// to deduce the template arguments of the conversion function
7331/// template from the type that we are converting to (C++
7332/// [temp.deduct.conv]).
7333void Sema::AddTemplateConversionCandidate(
7334 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7335 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7336 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7337 bool AllowExplicit, bool AllowResultConversion) {
7338 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7339, __PRETTY_FUNCTION__))
7339 "Only conversion function templates permitted here")((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7339, __PRETTY_FUNCTION__))
;
7340
7341 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7342 return;
7343
7344 // If the function template has a non-dependent explicit specification,
7345 // exclude it now if appropriate; we are not permitted to perform deduction
7346 // and substitution in this case.
7347 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7348 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7349 Candidate.FoundDecl = FoundDecl;
7350 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7351 Candidate.Viable = false;
7352 Candidate.FailureKind = ovl_fail_explicit;
7353 return;
7354 }
7355
7356 TemplateDeductionInfo Info(CandidateSet.getLocation());
7357 CXXConversionDecl *Specialization = nullptr;
7358 if (TemplateDeductionResult Result
7359 = DeduceTemplateArguments(FunctionTemplate, ToType,
7360 Specialization, Info)) {
7361 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7362 Candidate.FoundDecl = FoundDecl;
7363 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7364 Candidate.Viable = false;
7365 Candidate.FailureKind = ovl_fail_bad_deduction;
7366 Candidate.IsSurrogate = false;
7367 Candidate.IgnoreObjectArgument = false;
7368 Candidate.ExplicitCallArguments = 1;
7369 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7370 Info);
7371 return;
7372 }
7373
7374 // Add the conversion function template specialization produced by
7375 // template argument deduction as a candidate.
7376 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7376, __PRETTY_FUNCTION__))
;
7377 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7378 CandidateSet, AllowObjCConversionOnExplicit,
7379 AllowExplicit, AllowResultConversion);
7380}
7381
7382/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7383/// converts the given @c Object to a function pointer via the
7384/// conversion function @c Conversion, and then attempts to call it
7385/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7386/// the type of function that we'll eventually be calling.
7387void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7388 DeclAccessPair FoundDecl,
7389 CXXRecordDecl *ActingContext,
7390 const FunctionProtoType *Proto,
7391 Expr *Object,
7392 ArrayRef<Expr *> Args,
7393 OverloadCandidateSet& CandidateSet) {
7394 if (!CandidateSet.isNewCandidate(Conversion))
7395 return;
7396
7397 // Overload resolution is always an unevaluated context.
7398 EnterExpressionEvaluationContext Unevaluated(
7399 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7400
7401 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7402 Candidate.FoundDecl = FoundDecl;
7403 Candidate.Function = nullptr;
7404 Candidate.Surrogate = Conversion;
7405 Candidate.Viable = true;
7406 Candidate.IsSurrogate = true;
7407 Candidate.IgnoreObjectArgument = false;
7408 Candidate.ExplicitCallArguments = Args.size();
7409
7410 // Determine the implicit conversion sequence for the implicit
7411 // object parameter.
7412 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7413 *this, CandidateSet.getLocation(), Object->getType(),
7414 Object->Classify(Context), Conversion, ActingContext);
7415 if (ObjectInit.isBad()) {
7416 Candidate.Viable = false;
7417 Candidate.FailureKind = ovl_fail_bad_conversion;
7418 Candidate.Conversions[0] = ObjectInit;
7419 return;
7420 }
7421
7422 // The first conversion is actually a user-defined conversion whose
7423 // first conversion is ObjectInit's standard conversion (which is
7424 // effectively a reference binding). Record it as such.
7425 Candidate.Conversions[0].setUserDefined();
7426 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7427 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7428 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7429 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7430 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7431 Candidate.Conversions[0].UserDefined.After
7432 = Candidate.Conversions[0].UserDefined.Before;
7433 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7434
7435 // Find the
7436 unsigned NumParams = Proto->getNumParams();
7437
7438 // (C++ 13.3.2p2): A candidate function having fewer than m
7439 // parameters is viable only if it has an ellipsis in its parameter
7440 // list (8.3.5).
7441 if (Args.size() > NumParams && !Proto->isVariadic()) {
7442 Candidate.Viable = false;
7443 Candidate.FailureKind = ovl_fail_too_many_arguments;
7444 return;
7445 }
7446
7447 // Function types don't have any default arguments, so just check if
7448 // we have enough arguments.
7449 if (Args.size() < NumParams) {
7450 // Not enough arguments.
7451 Candidate.Viable = false;
7452 Candidate.FailureKind = ovl_fail_too_few_arguments;
7453 return;
7454 }
7455
7456 // Determine the implicit conversion sequences for each of the
7457 // arguments.
7458 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7459 if (ArgIdx < NumParams) {
7460 // (C++ 13.3.2p3): for F to be a viable function, there shall
7461 // exist for each argument an implicit conversion sequence
7462 // (13.3.3.1) that converts that argument to the corresponding
7463 // parameter of F.
7464 QualType ParamType = Proto->getParamType(ArgIdx);
7465 Candidate.Conversions[ArgIdx + 1]
7466 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7467 /*SuppressUserConversions=*/false,
7468 /*InOverloadResolution=*/false,
7469 /*AllowObjCWritebackConversion=*/
7470 getLangOpts().ObjCAutoRefCount);
7471 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7472 Candidate.Viable = false;
7473 Candidate.FailureKind = ovl_fail_bad_conversion;
7474 return;
7475 }
7476 } else {
7477 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7478 // argument for which there is no corresponding parameter is
7479 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7480 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7481 }
7482 }
7483
7484 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7485 Candidate.Viable = false;
7486 Candidate.FailureKind = ovl_fail_enable_if;
7487 Candidate.DeductionFailure.Data = FailedAttr;
7488 return;
7489 }
7490}
7491
7492/// Add all of the non-member operator function declarations in the given
7493/// function set to the overload candidate set.
7494void Sema::AddNonMemberOperatorCandidates(
7495 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7496 OverloadCandidateSet &CandidateSet,
7497 TemplateArgumentListInfo *ExplicitTemplateArgs) {
7498 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7499 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7500 ArrayRef<Expr *> FunctionArgs = Args;
7501
7502 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7503 FunctionDecl *FD =
7504 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7505
7506 // Don't consider rewritten functions if we're not rewriting.
7507 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7508 continue;
7509
7510 assert(!isa<CXXMethodDecl>(FD) &&((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7511, __PRETTY_FUNCTION__))
7511 "unqualified operator lookup found a member function")((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7511, __PRETTY_FUNCTION__))
;
7512
7513 if (FunTmpl) {
7514 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7515 FunctionArgs, CandidateSet);
7516 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7517 AddTemplateOverloadCandidate(
7518 FunTmpl, F.getPair(), ExplicitTemplateArgs,
7519 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7520 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7521 } else {
7522 if (ExplicitTemplateArgs)
7523 continue;
7524 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7525 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7526 AddOverloadCandidate(FD, F.getPair(),
7527 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7528 false, false, true, false, ADLCallKind::NotADL,
7529 None, OverloadCandidateParamOrder::Reversed);
7530 }
7531 }
7532}
7533
7534/// Add overload candidates for overloaded operators that are
7535/// member functions.
7536///
7537/// Add the overloaded operator candidates that are member functions
7538/// for the operator Op that was used in an operator expression such
7539/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7540/// CandidateSet will store the added overload candidates. (C++
7541/// [over.match.oper]).
7542void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7543 SourceLocation OpLoc,
7544 ArrayRef<Expr *> Args,
7545 OverloadCandidateSet &CandidateSet,
7546 OverloadCandidateParamOrder PO) {
7547 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7548
7549 // C++ [over.match.oper]p3:
7550 // For a unary operator @ with an operand of a type whose
7551 // cv-unqualified version is T1, and for a binary operator @ with
7552 // a left operand of a type whose cv-unqualified version is T1 and
7553 // a right operand of a type whose cv-unqualified version is T2,
7554 // three sets of candidate functions, designated member
7555 // candidates, non-member candidates and built-in candidates, are
7556 // constructed as follows:
7557 QualType T1 = Args[0]->getType();
7558
7559 // -- If T1 is a complete class type or a class currently being
7560 // defined, the set of member candidates is the result of the
7561 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7562 // the set of member candidates is empty.
7563 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7564 // Complete the type if it can be completed.
7565 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7566 return;
7567 // If the type is neither complete nor being defined, bail out now.
7568 if (!T1Rec->getDecl()->getDefinition())
7569 return;
7570
7571 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7572 LookupQualifiedName(Operators, T1Rec->getDecl());
7573 Operators.suppressDiagnostics();
7574
7575 for (LookupResult::iterator Oper = Operators.begin(),
7576 OperEnd = Operators.end();
7577 Oper != OperEnd;
7578 ++Oper)
7579 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7580 Args[0]->Classify(Context), Args.slice(1),
7581 CandidateSet, /*SuppressUserConversion=*/false, PO);
7582 }
7583}
7584
7585/// AddBuiltinCandidate - Add a candidate for a built-in
7586/// operator. ResultTy and ParamTys are the result and parameter types
7587/// of the built-in candidate, respectively. Args and NumArgs are the
7588/// arguments being passed to the candidate. IsAssignmentOperator
7589/// should be true when this built-in candidate is an assignment
7590/// operator. NumContextualBoolArguments is the number of arguments
7591/// (at the beginning of the argument list) that will be contextually
7592/// converted to bool.
7593void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7594 OverloadCandidateSet& CandidateSet,
7595 bool IsAssignmentOperator,
7596 unsigned NumContextualBoolArguments) {
7597 // Overload resolution is always an unevaluated context.
7598 EnterExpressionEvaluationContext Unevaluated(
7599 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7600
7601 // Add this candidate
7602 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7603 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7604 Candidate.Function = nullptr;
7605 Candidate.IsSurrogate = false;
7606 Candidate.IgnoreObjectArgument = false;
7607 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7608
7609 // Determine the implicit conversion sequences for each of the
7610 // arguments.
7611 Candidate.Viable = true;
7612 Candidate.ExplicitCallArguments = Args.size();
7613 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7614 // C++ [over.match.oper]p4:
7615 // For the built-in assignment operators, conversions of the
7616 // left operand are restricted as follows:
7617 // -- no temporaries are introduced to hold the left operand, and
7618 // -- no user-defined conversions are applied to the left
7619 // operand to achieve a type match with the left-most
7620 // parameter of a built-in candidate.
7621 //
7622 // We block these conversions by turning off user-defined
7623 // conversions, since that is the only way that initialization of
7624 // a reference to a non-class type can occur from something that
7625 // is not of the same type.
7626 if (ArgIdx < NumContextualBoolArguments) {
7627 assert(ParamTys[ArgIdx] == Context.BoolTy &&((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7628, __PRETTY_FUNCTION__))
7628 "Contextual conversion to bool requires bool type")((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7628, __PRETTY_FUNCTION__))
;
7629 Candidate.Conversions[ArgIdx]
7630 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7631 } else {
7632 Candidate.Conversions[ArgIdx]
7633 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7634 ArgIdx == 0 && IsAssignmentOperator,
7635 /*InOverloadResolution=*/false,
7636 /*AllowObjCWritebackConversion=*/
7637 getLangOpts().ObjCAutoRefCount);
7638 }
7639 if (Candidate.Conversions[ArgIdx].isBad()) {
7640 Candidate.Viable = false;
7641 Candidate.FailureKind = ovl_fail_bad_conversion;
7642 break;
7643 }
7644 }
7645}
7646
7647namespace {
7648
7649/// BuiltinCandidateTypeSet - A set of types that will be used for the
7650/// candidate operator functions for built-in operators (C++
7651/// [over.built]). The types are separated into pointer types and
7652/// enumeration types.
7653class BuiltinCandidateTypeSet {
7654 /// TypeSet - A set of types.
7655 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7656 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7657
7658 /// PointerTypes - The set of pointer types that will be used in the
7659 /// built-in candidates.
7660 TypeSet PointerTypes;
7661
7662 /// MemberPointerTypes - The set of member pointer types that will be
7663 /// used in the built-in candidates.
7664 TypeSet MemberPointerTypes;
7665
7666 /// EnumerationTypes - The set of enumeration types that will be
7667 /// used in the built-in candidates.
7668 TypeSet EnumerationTypes;
7669
7670 /// The set of vector types that will be used in the built-in
7671 /// candidates.
7672 TypeSet VectorTypes;
7673
7674 /// A flag indicating non-record types are viable candidates
7675 bool HasNonRecordTypes;
7676
7677 /// A flag indicating whether either arithmetic or enumeration types
7678 /// were present in the candidate set.
7679 bool HasArithmeticOrEnumeralTypes;
7680
7681 /// A flag indicating whether the nullptr type was present in the
7682 /// candidate set.
7683 bool HasNullPtrType;
7684
7685 /// Sema - The semantic analysis instance where we are building the
7686 /// candidate type set.
7687 Sema &SemaRef;
7688
7689 /// Context - The AST context in which we will build the type sets.
7690 ASTContext &Context;
7691
7692 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7693 const Qualifiers &VisibleQuals);
7694 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7695
7696public:
7697 /// iterator - Iterates through the types that are part of the set.
7698 typedef TypeSet::iterator iterator;
7699
7700 BuiltinCandidateTypeSet(Sema &SemaRef)
7701 : HasNonRecordTypes(false),
7702 HasArithmeticOrEnumeralTypes(false),
7703 HasNullPtrType(false),
7704 SemaRef(SemaRef),
7705 Context(SemaRef.Context) { }
7706
7707 void AddTypesConvertedFrom(QualType Ty,
7708 SourceLocation Loc,
7709 bool AllowUserConversions,
7710 bool AllowExplicitConversions,
7711 const Qualifiers &VisibleTypeConversionsQuals);
7712
7713 /// pointer_begin - First pointer type found;
7714 iterator pointer_begin() { return PointerTypes.begin(); }
7715
7716 /// pointer_end - Past the last pointer type found;
7717 iterator pointer_end() { return PointerTypes.end(); }
7718
7719 /// member_pointer_begin - First member pointer type found;
7720 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7721
7722 /// member_pointer_end - Past the last member pointer type found;
7723 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7724
7725 /// enumeration_begin - First enumeration type found;
7726 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7727
7728 /// enumeration_end - Past the last enumeration type found;
7729 iterator enumeration_end() { return EnumerationTypes.end(); }
7730
7731 iterator vector_begin() { return VectorTypes.begin(); }
7732 iterator vector_end() { return VectorTypes.end(); }
7733
7734 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7735 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7736 bool hasNullPtrType() const { return HasNullPtrType; }
7737};
7738
7739} // end anonymous namespace
7740
7741/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7742/// the set of pointer types along with any more-qualified variants of
7743/// that type. For example, if @p Ty is "int const *", this routine
7744/// will add "int const *", "int const volatile *", "int const
7745/// restrict *", and "int const volatile restrict *" to the set of
7746/// pointer types. Returns true if the add of @p Ty itself succeeded,
7747/// false otherwise.
7748///
7749/// FIXME: what to do about extended qualifiers?
7750bool
7751BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7752 const Qualifiers &VisibleQuals) {
7753
7754 // Insert this type.
7755 if (!PointerTypes.insert(Ty))
7756 return false;
7757
7758 QualType PointeeTy;
7759 const PointerType *PointerTy = Ty->getAs<PointerType>();
7760 bool buildObjCPtr = false;
7761 if (!PointerTy) {
7762 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7763 PointeeTy = PTy->getPointeeType();
7764 buildObjCPtr = true;
7765 } else {
7766 PointeeTy = PointerTy->getPointeeType();
7767 }
7768
7769 // Don't add qualified variants of arrays. For one, they're not allowed
7770 // (the qualifier would sink to the element type), and for another, the
7771 // only overload situation where it matters is subscript or pointer +- int,
7772 // and those shouldn't have qualifier variants anyway.
7773 if (PointeeTy->isArrayType())
7774 return true;
7775
7776 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7777 bool hasVolatile = VisibleQuals.hasVolatile();
7778 bool hasRestrict = VisibleQuals.hasRestrict();
7779
7780 // Iterate through all strict supersets of BaseCVR.
7781 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7782 if ((CVR | BaseCVR) != CVR) continue;
7783 // Skip over volatile if no volatile found anywhere in the types.
7784 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7785
7786 // Skip over restrict if no restrict found anywhere in the types, or if
7787 // the type cannot be restrict-qualified.
7788 if ((CVR & Qualifiers::Restrict) &&
7789 (!hasRestrict ||
7790 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7791 continue;
7792
7793 // Build qualified pointee type.
7794 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7795
7796 // Build qualified pointer type.
7797 QualType QPointerTy;
7798 if (!buildObjCPtr)
7799 QPointerTy = Context.getPointerType(QPointeeTy);
7800 else
7801 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7802
7803 // Insert qualified pointer type.
7804 PointerTypes.insert(QPointerTy);
7805 }
7806
7807 return true;
7808}
7809
7810/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7811/// to the set of pointer types along with any more-qualified variants of
7812/// that type. For example, if @p Ty is "int const *", this routine
7813/// will add "int const *", "int const volatile *", "int const
7814/// restrict *", and "int const volatile restrict *" to the set of
7815/// pointer types. Returns true if the add of @p Ty itself succeeded,
7816/// false otherwise.
7817///
7818/// FIXME: what to do about extended qualifiers?
7819bool
7820BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7821 QualType Ty) {
7822 // Insert this type.
7823 if (!MemberPointerTypes.insert(Ty))
7824 return false;
7825
7826 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7827 assert(PointerTy && "type was not a member pointer type!")((PointerTy && "type was not a member pointer type!")
? static_cast<void> (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7827, __PRETTY_FUNCTION__))
;
7828
7829 QualType PointeeTy = PointerTy->getPointeeType();
7830 // Don't add qualified variants of arrays. For one, they're not allowed
7831 // (the qualifier would sink to the element type), and for another, the
7832 // only overload situation where it matters is subscript or pointer +- int,
7833 // and those shouldn't have qualifier variants anyway.
7834 if (PointeeTy->isArrayType())
7835 return true;
7836 const Type *ClassTy = PointerTy->getClass();
7837
7838 // Iterate through all strict supersets of the pointee type's CVR
7839 // qualifiers.
7840 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7841 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7842 if ((CVR | BaseCVR) != CVR) continue;
7843
7844 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7845 MemberPointerTypes.insert(
7846 Context.getMemberPointerType(QPointeeTy, ClassTy));
7847 }
7848
7849 return true;
7850}
7851
7852/// AddTypesConvertedFrom - Add each of the types to which the type @p
7853/// Ty can be implicit converted to the given set of @p Types. We're
7854/// primarily interested in pointer types and enumeration types. We also
7855/// take member pointer types, for the conditional operator.
7856/// AllowUserConversions is true if we should look at the conversion
7857/// functions of a class type, and AllowExplicitConversions if we
7858/// should also include the explicit conversion functions of a class
7859/// type.
7860void
7861BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7862 SourceLocation Loc,
7863 bool AllowUserConversions,
7864 bool AllowExplicitConversions,
7865 const Qualifiers &VisibleQuals) {
7866 // Only deal with canonical types.
7867 Ty = Context.getCanonicalType(Ty);
7868
7869 // Look through reference types; they aren't part of the type of an
7870 // expression for the purposes of conversions.
7871 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7872 Ty = RefTy->getPointeeType();
7873
7874 // If we're dealing with an array type, decay to the pointer.
7875 if (Ty->isArrayType())
7876 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7877
7878 // Otherwise, we don't care about qualifiers on the type.
7879 Ty = Ty.getLocalUnqualifiedType();
7880
7881 // Flag if we ever add a non-record type.
7882 const RecordType *TyRec = Ty->getAs<RecordType>();
7883 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7884
7885 // Flag if we encounter an arithmetic type.
7886 HasArithmeticOrEnumeralTypes =
7887 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7888
7889 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7890 PointerTypes.insert(Ty);
7891 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7892 // Insert our type, and its more-qualified variants, into the set
7893 // of types.
7894 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7895 return;
7896 } else if (Ty->isMemberPointerType()) {
7897 // Member pointers are far easier, since the pointee can't be converted.
7898 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7899 return;
7900 } else if (Ty->isEnumeralType()) {
7901 HasArithmeticOrEnumeralTypes = true;
7902 EnumerationTypes.insert(Ty);
7903 } else if (Ty->isVectorType()) {
7904 // We treat vector types as arithmetic types in many contexts as an
7905 // extension.
7906 HasArithmeticOrEnumeralTypes = true;
7907 VectorTypes.insert(Ty);
7908 } else if (Ty->isNullPtrType()) {
7909 HasNullPtrType = true;
7910 } else if (AllowUserConversions && TyRec) {
7911 // No conversion functions in incomplete types.
7912 if (!SemaRef.isCompleteType(Loc, Ty))
7913 return;
7914
7915 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7916 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7917 if (isa<UsingShadowDecl>(D))
7918 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7919
7920 // Skip conversion function templates; they don't tell us anything
7921 // about which builtin types we can convert to.
7922 if (isa<FunctionTemplateDecl>(D))
7923 continue;
7924
7925 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7926 if (AllowExplicitConversions || !Conv->isExplicit()) {
7927 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7928 VisibleQuals);
7929 }
7930 }
7931 }
7932}
7933/// Helper function for adjusting address spaces for the pointer or reference
7934/// operands of builtin operators depending on the argument.
7935static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7936 Expr *Arg) {
7937 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7938}
7939
7940/// Helper function for AddBuiltinOperatorCandidates() that adds
7941/// the volatile- and non-volatile-qualified assignment operators for the
7942/// given type to the candidate set.
7943static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7944 QualType T,
7945 ArrayRef<Expr *> Args,
7946 OverloadCandidateSet &CandidateSet) {
7947 QualType ParamTypes[2];
7948
7949 // T& operator=(T&, T)
7950 ParamTypes[0] = S.Context.getLValueReferenceType(
7951 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7952 ParamTypes[1] = T;
7953 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7954 /*IsAssignmentOperator=*/true);
7955
7956 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7957 // volatile T& operator=(volatile T&, T)
7958 ParamTypes[0] = S.Context.getLValueReferenceType(
7959 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7960 Args[0]));
7961 ParamTypes[1] = T;
7962 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7963 /*IsAssignmentOperator=*/true);
7964 }
7965}
7966
7967/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7968/// if any, found in visible type conversion functions found in ArgExpr's type.
7969static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7970 Qualifiers VRQuals;
7971 const RecordType *TyRec;
7972 if (const MemberPointerType *RHSMPType =
7973 ArgExpr->getType()->getAs<MemberPointerType>())
7974 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7975 else
7976 TyRec = ArgExpr->getType()->getAs<RecordType>();
7977 if (!TyRec) {
7978 // Just to be safe, assume the worst case.
7979 VRQuals.addVolatile();
7980 VRQuals.addRestrict();
7981 return VRQuals;
7982 }
7983
7984 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7985 if (!ClassDecl->hasDefinition())
7986 return VRQuals;
7987
7988 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7989 if (isa<UsingShadowDecl>(D))
7990 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7991 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7992 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7993 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7994 CanTy = ResTypeRef->getPointeeType();
7995 // Need to go down the pointer/mempointer chain and add qualifiers
7996 // as see them.
7997 bool done = false;
7998 while (!done) {
7999 if (CanTy.isRestrictQualified())
8000 VRQuals.addRestrict();
8001 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8002 CanTy = ResTypePtr->getPointeeType();
8003 else if (const MemberPointerType *ResTypeMPtr =
8004 CanTy->getAs<MemberPointerType>())
8005 CanTy = ResTypeMPtr->getPointeeType();
8006 else
8007 done = true;
8008 if (CanTy.isVolatileQualified())
8009 VRQuals.addVolatile();
8010 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8011 return VRQuals;
8012 }
8013 }
8014 }
8015 return VRQuals;
8016}
8017
8018namespace {
8019
8020/// Helper class to manage the addition of builtin operator overload
8021/// candidates. It provides shared state and utility methods used throughout
8022/// the process, as well as a helper method to add each group of builtin
8023/// operator overloads from the standard to a candidate set.
8024class BuiltinOperatorOverloadBuilder {
8025 // Common instance state available to all overload candidate addition methods.
8026 Sema &S;
8027 ArrayRef<Expr *> Args;
8028 Qualifiers VisibleTypeConversionsQuals;
8029 bool HasArithmeticOrEnumeralCandidateType;
8030 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8031 OverloadCandidateSet &CandidateSet;
8032
8033 static constexpr int ArithmeticTypesCap = 24;
8034 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8035
8036 // Define some indices used to iterate over the arithmetic types in
8037 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8038 // types are that preserved by promotion (C++ [over.built]p2).
8039 unsigned FirstIntegralType,
8040 LastIntegralType;
8041 unsigned FirstPromotedIntegralType,
8042 LastPromotedIntegralType;
8043 unsigned FirstPromotedArithmeticType,
8044 LastPromotedArithmeticType;
8045 unsigned NumArithmeticTypes;
8046
8047 void InitArithmeticTypes() {
8048 // Start of promoted types.
8049 FirstPromotedArithmeticType = 0;
8050 ArithmeticTypes.push_back(S.Context.FloatTy);
8051 ArithmeticTypes.push_back(S.Context.DoubleTy);
8052 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8053 if (S.Context.getTargetInfo().hasFloat128Type())
8054 ArithmeticTypes.push_back(S.Context.Float128Ty);
8055
8056 // Start of integral types.
8057 FirstIntegralType = ArithmeticTypes.size();
8058 FirstPromotedIntegralType = ArithmeticTypes.size();
8059 ArithmeticTypes.push_back(S.Context.IntTy);
8060 ArithmeticTypes.push_back(S.Context.LongTy);
8061 ArithmeticTypes.push_back(S.Context.LongLongTy);
8062 if (S.Context.getTargetInfo().hasInt128Type())
8063 ArithmeticTypes.push_back(S.Context.Int128Ty);
8064 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8065 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8066 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8067 if (S.Context.getTargetInfo().hasInt128Type())
8068 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8069 LastPromotedIntegralType = ArithmeticTypes.size();
8070 LastPromotedArithmeticType = ArithmeticTypes.size();
8071 // End of promoted types.
8072
8073 ArithmeticTypes.push_back(S.Context.BoolTy);
8074 ArithmeticTypes.push_back(S.Context.CharTy);
8075 ArithmeticTypes.push_back(S.Context.WCharTy);
8076 if (S.Context.getLangOpts().Char8)
8077 ArithmeticTypes.push_back(S.Context.Char8Ty);
8078 ArithmeticTypes.push_back(S.Context.Char16Ty);
8079 ArithmeticTypes.push_back(S.Context.Char32Ty);
8080 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8081 ArithmeticTypes.push_back(S.Context.ShortTy);
8082 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8083 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8084 LastIntegralType = ArithmeticTypes.size();
8085 NumArithmeticTypes = ArithmeticTypes.size();
8086 // End of integral types.
8087 // FIXME: What about complex? What about half?
8088
8089 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types."
) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 8090, __PRETTY_FUNCTION__))
8090 "Enough inline storage for all arithmetic types.")((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types."
) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 8090, __PRETTY_FUNCTION__))
;
8091 }
8092
8093 /// Helper method to factor out the common pattern of adding overloads
8094 /// for '++' and '--' builtin operators.
8095 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8096 bool HasVolatile,
8097 bool HasRestrict) {
8098 QualType ParamTypes[2] = {
8099 S.Context.getLValueReferenceType(CandidateTy),
8100 S.Context.IntTy
8101 };
8102
8103 // Non-volatile version.
8104 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8105
8106 // Use a heuristic to reduce number of builtin candidates in the set:
8107 // add volatile version only if there are conversions to a volatile type.
8108 if (HasVolatile) {
8109 ParamTypes[0] =
8110 S.Context.getLValueReferenceType(
8111 S.Context.getVolatileType(CandidateTy));
8112 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8113 }
8114
8115 // Add restrict version only if there are conversions to a restrict type
8116 // and our candidate type is a non-restrict-qualified pointer.
8117 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8118 !CandidateTy.isRestrictQualified()) {
8119 ParamTypes[0]
8120 = S.Context.getLValueReferenceType(
8121 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8122 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8123
8124 if (HasVolatile) {
8125 ParamTypes[0]
8126 = S.Context.getLValueReferenceType(
8127 S.Context.getCVRQualifiedType(CandidateTy,
8128 (Qualifiers::Volatile |
8129 Qualifiers::Restrict)));
8130 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8131 }
8132 }
8133
8134 }
8135
8136public:
8137 BuiltinOperatorOverloadBuilder(
8138 Sema &S, ArrayRef<Expr *> Args,
8139 Qualifiers VisibleTypeConversionsQuals,
8140 bool HasArithmeticOrEnumeralCandidateType,
8141 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8142 OverloadCandidateSet &CandidateSet)
8143 : S(S), Args(Args),
8144 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8145 HasArithmeticOrEnumeralCandidateType(
8146 HasArithmeticOrEnumeralCandidateType),
8147 CandidateTypes(CandidateTypes),
8148 CandidateSet(CandidateSet) {
8149
8150 InitArithmeticTypes();
8151 }
8152
8153 // Increment is deprecated for bool since C++17.
8154 //
8155 // C++ [over.built]p3:
8156 //
8157 // For every pair (T, VQ), where T is an arithmetic type other
8158 // than bool, and VQ is either volatile or empty, there exist
8159 // candidate operator functions of the form
8160 //
8161 // VQ T& operator++(VQ T&);
8162 // T operator++(VQ T&, int);
8163 //
8164 // C++ [over.built]p4:
8165 //
8166 // For every pair (T, VQ), where T is an arithmetic type other
8167 // than bool, and VQ is either volatile or empty, there exist
8168 // candidate operator functions of the form
8169 //
8170 // VQ T& operator--(VQ T&);
8171 // T operator--(VQ T&, int);
8172 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8173 if (!HasArithmeticOrEnumeralCandidateType)
8174 return;
8175
8176 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8177 const auto TypeOfT = ArithmeticTypes[Arith];
8178 if (TypeOfT == S.Context.BoolTy) {
8179 if (Op == OO_MinusMinus)
8180 continue;
8181 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8182 continue;
8183 }
8184 addPlusPlusMinusMinusStyleOverloads(
8185 TypeOfT,
8186 VisibleTypeConversionsQuals.hasVolatile(),
8187 VisibleTypeConversionsQuals.hasRestrict());
8188 }
8189 }
8190
8191 // C++ [over.built]p5:
8192 //
8193 // For every pair (T, VQ), where T is a cv-qualified or
8194 // cv-unqualified object type, and VQ is either volatile or
8195 // empty, there exist candidate operator functions of the form
8196 //
8197 // T*VQ& operator++(T*VQ&);
8198 // T*VQ& operator--(T*VQ&);
8199 // T* operator++(T*VQ&, int);
8200 // T* operator--(T*VQ&, int);
8201 void addPlusPlusMinusMinusPointerOverloads() {
8202 for (BuiltinCandidateTypeSet::iterator
8203 Ptr = CandidateTypes[0].pointer_begin(),
8204 PtrEnd = CandidateTypes[0].pointer_end();
8205 Ptr != PtrEnd; ++Ptr) {
8206 // Skip pointer types that aren't pointers to object types.
8207 if (!(*Ptr)->getPointeeType()->isObjectType())
8208 continue;
8209
8210 addPlusPlusMinusMinusStyleOverloads(*Ptr,
8211 (!(*Ptr).isVolatileQualified() &&
8212 VisibleTypeConversionsQuals.hasVolatile()),
8213 (!(*Ptr).isRestrictQualified() &&
8214 VisibleTypeConversionsQuals.hasRestrict()));
8215 }
8216 }
8217
8218 // C++ [over.built]p6:
8219 // For every cv-qualified or cv-unqualified object type T, there
8220 // exist candidate operator functions of the form
8221 //
8222 // T& operator*(T*);
8223 //
8224 // C++ [over.built]p7:
8225 // For every function type T that does not have cv-qualifiers or a
8226 // ref-qualifier, there exist candidate operator functions of the form
8227 // T& operator*(T*);
8228 void addUnaryStarPointerOverloads() {
8229 for (BuiltinCandidateTypeSet::iterator
8230 Ptr = CandidateTypes[0].pointer_begin(),
8231 PtrEnd = CandidateTypes[0].pointer_end();
8232 Ptr != PtrEnd; ++Ptr) {
8233 QualType ParamTy = *Ptr;
8234 QualType PointeeTy = ParamTy->getPointeeType();
8235 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8236 continue;
8237
8238 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8239 if (Proto->getMethodQuals() || Proto->getRefQualifier())
8240 continue;
8241
8242 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8243 }
8244 }
8245
8246 // C++ [over.built]p9:
8247 // For every promoted arithmetic type T, there exist candidate
8248 // operator functions of the form
8249 //
8250 // T operator+(T);
8251 // T operator-(T);
8252 void addUnaryPlusOrMinusArithmeticOverloads() {
8253 if (!HasArithmeticOrEnumeralCandidateType)
8254 return;
8255
8256 for (unsigned Arith = FirstPromotedArithmeticType;
8257 Arith < LastPromotedArithmeticType; ++Arith) {
8258 QualType ArithTy = ArithmeticTypes[Arith];
8259 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8260 }
8261
8262 // Extension: We also add these operators for vector types.
8263 for (BuiltinCandidateTypeSet::iterator
8264 Vec = CandidateTypes[0].vector_begin(),
8265 VecEnd = CandidateTypes[0].vector_end();
8266 Vec != VecEnd; ++Vec) {
8267 QualType VecTy = *Vec;
8268 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8269 }
8270 }
8271
8272 // C++ [over.built]p8:
8273 // For every type T, there exist candidate operator functions of
8274 // the form
8275 //
8276 // T* operator+(T*);
8277 void addUnaryPlusPointerOverloads() {
8278 for (BuiltinCandidateTypeSet::iterator
8279 Ptr = CandidateTypes[0].pointer_begin(),
8280 PtrEnd = CandidateTypes[0].pointer_end();
8281 Ptr != PtrEnd; ++Ptr) {
8282 QualType ParamTy = *Ptr;
8283 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8284 }
8285 }
8286
8287 // C++ [over.built]p10:
8288 // For every promoted integral type T, there exist candidate
8289 // operator functions of the form
8290 //
8291 // T operator~(T);
8292 void addUnaryTildePromotedIntegralOverloads() {
8293 if (!HasArithmeticOrEnumeralCandidateType)
8294 return;
8295
8296 for (unsigned Int = FirstPromotedIntegralType;
8297 Int < LastPromotedIntegralType; ++Int) {
8298 QualType IntTy = ArithmeticTypes[Int];
8299 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8300 }
8301
8302 // Extension: We also add this operator for vector types.
8303 for (BuiltinCandidateTypeSet::iterator
8304 Vec = CandidateTypes[0].vector_begin(),
8305 VecEnd = CandidateTypes[0].vector_end();
8306 Vec != VecEnd; ++Vec) {
8307 QualType VecTy = *Vec;
8308 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8309 }
8310 }
8311
8312 // C++ [over.match.oper]p16:
8313 // For every pointer to member type T or type std::nullptr_t, there
8314 // exist candidate operator functions of the form
8315 //
8316 // bool operator==(T,T);
8317 // bool operator!=(T,T);
8318 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8319 /// Set of (canonical) types that we've already handled.
8320 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8321
8322 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8323 for (BuiltinCandidateTypeSet::iterator
8324 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8325 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8326 MemPtr != MemPtrEnd;
8327 ++MemPtr) {
8328 // Don't add the same builtin candidate twice.
8329 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8330 continue;
8331
8332 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8333 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8334 }
8335
8336 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8337 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8338 if (AddedTypes.insert(NullPtrTy).second) {
8339 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8340 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8341 }
8342 }
8343 }
8344 }
8345
8346 // C++ [over.built]p15:
8347 //
8348 // For every T, where T is an enumeration type or a pointer type,
8349 // there exist candidate operator functions of the form
8350 //
8351 // bool operator<(T, T);
8352 // bool operator>(T, T);
8353 // bool operator<=(T, T);
8354 // bool operator>=(T, T);
8355 // bool operator==(T, T);
8356 // bool operator!=(T, T);
8357 // R operator<=>(T, T)
8358 void addGenericBinaryPointerOrEnumeralOverloads() {
8359 // C++ [over.match.oper]p3:
8360 // [...]the built-in candidates include all of the candidate operator
8361 // functions defined in 13.6 that, compared to the given operator, [...]
8362 // do not have the same parameter-type-list as any non-template non-member
8363 // candidate.
8364 //
8365 // Note that in practice, this only affects enumeration types because there
8366 // aren't any built-in candidates of record type, and a user-defined operator
8367 // must have an operand of record or enumeration type. Also, the only other
8368 // overloaded operator with enumeration arguments, operator=,
8369 // cannot be overloaded for enumeration types, so this is the only place
8370 // where we must suppress candidates like this.
8371 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8372 UserDefinedBinaryOperators;
8373
8374 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8375 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8376 CandidateTypes[ArgIdx].enumeration_end()) {
8377 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8378 CEnd = CandidateSet.end();
8379 C != CEnd; ++C) {
8380 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8381 continue;
8382
8383 if (C->Function->isFunctionTemplateSpecialization())
8384 continue;
8385
8386 // We interpret "same parameter-type-list" as applying to the
8387 // "synthesized candidate, with the order of the two parameters
8388 // reversed", not to the original function.
8389 bool Reversed = C->RewriteKind & CRK_Reversed;
8390 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8391 ->getType()
8392 .getUnqualifiedType();
8393 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8394 ->getType()
8395 .getUnqualifiedType();
8396
8397 // Skip if either parameter isn't of enumeral type.
8398 if (!FirstParamType->isEnumeralType() ||
8399 !SecondParamType->isEnumeralType())
8400 continue;
8401
8402 // Add this operator to the set of known user-defined operators.
8403 UserDefinedBinaryOperators.insert(
8404 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8405 S.Context.getCanonicalType(SecondParamType)));
8406 }
8407 }
8408 }
8409
8410 /// Set of (canonical) types that we've already handled.
8411 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8412
8413 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8414 for (BuiltinCandidateTypeSet::iterator
8415 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8416 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8417 Ptr != PtrEnd; ++Ptr) {
8418 // Don't add the same builtin candidate twice.
8419 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8420 continue;
8421
8422 QualType ParamTypes[2] = { *Ptr, *Ptr };
8423 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8424 }
8425 for (BuiltinCandidateTypeSet::iterator
8426 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8427 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8428 Enum != EnumEnd; ++Enum) {
8429 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8430
8431 // Don't add the same builtin candidate twice, or if a user defined
8432 // candidate exists.
8433 if (!AddedTypes.insert(CanonType).second ||
8434 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8435 CanonType)))
8436 continue;
8437 QualType ParamTypes[2] = { *Enum, *Enum };
8438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8439 }
8440 }
8441 }
8442
8443 // C++ [over.built]p13:
8444 //
8445 // For every cv-qualified or cv-unqualified object type T
8446 // there exist candidate operator functions of the form
8447 //
8448 // T* operator+(T*, ptrdiff_t);
8449 // T& operator[](T*, ptrdiff_t); [BELOW]
8450 // T* operator-(T*, ptrdiff_t);
8451 // T* operator+(ptrdiff_t, T*);
8452 // T& operator[](ptrdiff_t, T*); [BELOW]
8453 //
8454 // C++ [over.built]p14:
8455 //
8456 // For every T, where T is a pointer to object type, there
8457 // exist candidate operator functions of the form
8458 //
8459 // ptrdiff_t operator-(T, T);
8460 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8461 /// Set of (canonical) types that we've already handled.
8462 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8463
8464 for (int Arg = 0; Arg < 2; ++Arg) {
8465 QualType AsymmetricParamTypes[2] = {
8466 S.Context.getPointerDiffType(),
8467 S.Context.getPointerDiffType(),
8468 };
8469 for (BuiltinCandidateTypeSet::iterator
8470 Ptr = CandidateTypes[Arg].pointer_begin(),
8471 PtrEnd = CandidateTypes[Arg].pointer_end();
8472 Ptr != PtrEnd; ++Ptr) {
8473 QualType PointeeTy = (*Ptr)->getPointeeType();
8474 if (!PointeeTy->isObjectType())
8475 continue;
8476
8477 AsymmetricParamTypes[Arg] = *Ptr;
8478 if (Arg == 0 || Op == OO_Plus) {
8479 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8480 // T* operator+(ptrdiff_t, T*);
8481 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8482 }
8483 if (Op == OO_Minus) {
8484 // ptrdiff_t operator-(T, T);
8485 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8486 continue;
8487
8488 QualType ParamTypes[2] = { *Ptr, *Ptr };
8489 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8490 }
8491 }
8492 }
8493 }
8494
8495 // C++ [over.built]p12:
8496 //
8497 // For every pair of promoted arithmetic types L and R, there
8498 // exist candidate operator functions of the form
8499 //
8500 // LR operator*(L, R);
8501 // LR operator/(L, R);
8502 // LR operator+(L, R);
8503 // LR operator-(L, R);
8504 // bool operator<(L, R);
8505 // bool operator>(L, R);
8506 // bool operator<=(L, R);
8507 // bool operator>=(L, R);
8508 // bool operator==(L, R);
8509 // bool operator!=(L, R);
8510 //
8511 // where LR is the result of the usual arithmetic conversions
8512 // between types L and R.
8513 //
8514 // C++ [over.built]p24:
8515 //
8516 // For every pair of promoted arithmetic types L and R, there exist
8517 // candidate operator functions of the form
8518 //
8519 // LR operator?(bool, L, R);
8520 //
8521 // where LR is the result of the usual arithmetic conversions
8522 // between types L and R.
8523 // Our candidates ignore the first parameter.
8524 void addGenericBinaryArithmeticOverloads() {
8525 if (!HasArithmeticOrEnumeralCandidateType)
8526 return;
8527
8528 for (unsigned Left = FirstPromotedArithmeticType;
8529 Left < LastPromotedArithmeticType; ++Left) {
8530 for (unsigned Right = FirstPromotedArithmeticType;
8531 Right < LastPromotedArithmeticType; ++Right) {
8532 QualType LandR[2] = { ArithmeticTypes[Left],
8533 ArithmeticTypes[Right] };
8534 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8535 }
8536 }
8537
8538 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8539 // conditional operator for vector types.
8540 for (BuiltinCandidateTypeSet::iterator
8541 Vec1 = CandidateTypes[0].vector_begin(),
8542 Vec1End = CandidateTypes[0].vector_end();
8543 Vec1 != Vec1End; ++Vec1) {
8544 for (BuiltinCandidateTypeSet::iterator
8545 Vec2 = CandidateTypes[1].vector_begin(),
8546 Vec2End = CandidateTypes[1].vector_end();
8547 Vec2 != Vec2End; ++Vec2) {
8548 QualType LandR[2] = { *Vec1, *Vec2 };
8549 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8550 }
8551 }
8552 }
8553
8554 // C++2a [over.built]p14:
8555 //
8556 // For every integral type T there exists a candidate operator function
8557 // of the form
8558 //
8559 // std::strong_ordering operator<=>(T, T)
8560 //
8561 // C++2a [over.built]p15:
8562 //
8563 // For every pair of floating-point types L and R, there exists a candidate
8564 // operator function of the form
8565 //
8566 // std::partial_ordering operator<=>(L, R);
8567 //
8568 // FIXME: The current specification for integral types doesn't play nice with
8569 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8570 // comparisons. Under the current spec this can lead to ambiguity during
8571 // overload resolution. For example:
8572 //
8573 // enum A : int {a};
8574 // auto x = (a <=> (long)42);
8575 //
8576 // error: call is ambiguous for arguments 'A' and 'long'.
8577 // note: candidate operator<=>(int, int)
8578 // note: candidate operator<=>(long, long)
8579 //
8580 // To avoid this error, this function deviates from the specification and adds
8581 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8582 // arithmetic types (the same as the generic relational overloads).
8583 //
8584 // For now this function acts as a placeholder.
8585 void addThreeWayArithmeticOverloads() {
8586 addGenericBinaryArithmeticOverloads();
8587 }
8588
8589 // C++ [over.built]p17:
8590 //
8591 // For every pair of promoted integral types L and R, there
8592 // exist candidate operator functions of the form
8593 //
8594 // LR operator%(L, R);
8595 // LR operator&(L, R);
8596 // LR operator^(L, R);
8597 // LR operator|(L, R);
8598 // L operator<<(L, R);
8599 // L operator>>(L, R);
8600 //
8601 // where LR is the result of the usual arithmetic conversions
8602 // between types L and R.
8603 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8604 if (!HasArithmeticOrEnumeralCandidateType)
8605 return;
8606
8607 for (unsigned Left = FirstPromotedIntegralType;
8608 Left < LastPromotedIntegralType; ++Left) {
8609 for (unsigned Right = FirstPromotedIntegralType;
8610 Right < LastPromotedIntegralType; ++Right) {
8611 QualType LandR[2] = { ArithmeticTypes[Left],
8612 ArithmeticTypes[Right] };
8613 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8614 }
8615 }
8616 }
8617
8618 // C++ [over.built]p20:
8619 //
8620 // For every pair (T, VQ), where T is an enumeration or
8621 // pointer to member type and VQ is either volatile or
8622 // empty, there exist candidate operator functions of the form
8623 //
8624 // VQ T& operator=(VQ T&, T);
8625 void addAssignmentMemberPointerOrEnumeralOverloads() {
8626 /// Set of (canonical) types that we've already handled.
8627 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8628
8629 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8630 for (BuiltinCandidateTypeSet::iterator
8631 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8632 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8633 Enum != EnumEnd; ++Enum) {
8634 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8635 continue;
8636
8637 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8638 }
8639
8640 for (BuiltinCandidateTypeSet::iterator
8641 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8642 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8643 MemPtr != MemPtrEnd; ++MemPtr) {
8644 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8645 continue;
8646
8647 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8648 }
8649 }
8650 }
8651
8652 // C++ [over.built]p19:
8653 //
8654 // For every pair (T, VQ), where T is any type and VQ is either
8655 // volatile or empty, there exist candidate operator functions
8656 // of the form
8657 //
8658 // T*VQ& operator=(T*VQ&, T*);
8659 //
8660 // C++ [over.built]p21:
8661 //
8662 // For every pair (T, VQ), where T is a cv-qualified or
8663 // cv-unqualified object type and VQ is either volatile or
8664 // empty, there exist candidate operator functions of the form
8665 //
8666 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8667 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8668 void addAssignmentPointerOverloads(bool isEqualOp) {
8669 /// Set of (canonical) types that we've already handled.
8670 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8671
8672 for (BuiltinCandidateTypeSet::iterator
8673 Ptr = CandidateTypes[0].pointer_begin(),
8674 PtrEnd = CandidateTypes[0].pointer_end();
8675 Ptr != PtrEnd; ++Ptr) {
8676 // If this is operator=, keep track of the builtin candidates we added.
8677 if (isEqualOp)
8678 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8679 else if (!(*Ptr)->getPointeeType()->isObjectType())
8680 continue;
8681
8682 // non-volatile version
8683 QualType ParamTypes[2] = {
8684 S.Context.getLValueReferenceType(*Ptr),
8685 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8686 };
8687 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8688 /*IsAssignmentOperator=*/ isEqualOp);
8689
8690 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8691 VisibleTypeConversionsQuals.hasVolatile();
8692 if (NeedVolatile) {
8693 // volatile version
8694 ParamTypes[0] =
8695 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8696 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8697 /*IsAssignmentOperator=*/isEqualOp);
8698 }
8699
8700 if (!(*Ptr).isRestrictQualified() &&
8701 VisibleTypeConversionsQuals.hasRestrict()) {
8702 // restrict version
8703 ParamTypes[0]
8704 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8705 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8706 /*IsAssignmentOperator=*/isEqualOp);
8707
8708 if (NeedVolatile) {
8709 // volatile restrict version
8710 ParamTypes[0]
8711 = S.Context.getLValueReferenceType(
8712 S.Context.getCVRQualifiedType(*Ptr,
8713 (Qualifiers::Volatile |
8714 Qualifiers::Restrict)));
8715 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8716 /*IsAssignmentOperator=*/isEqualOp);
8717 }
8718 }
8719 }
8720
8721 if (isEqualOp) {
8722 for (BuiltinCandidateTypeSet::iterator
8723 Ptr = CandidateTypes[1].pointer_begin(),
8724 PtrEnd = CandidateTypes[1].pointer_end();
8725 Ptr != PtrEnd; ++Ptr) {
8726 // Make sure we don't add the same candidate twice.
8727 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8728 continue;
8729
8730 QualType ParamTypes[2] = {
8731 S.Context.getLValueReferenceType(*Ptr),
8732 *Ptr,
8733 };
8734
8735 // non-volatile version
8736 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8737 /*IsAssignmentOperator=*/true);
8738
8739 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8740 VisibleTypeConversionsQuals.hasVolatile();
8741 if (NeedVolatile) {
8742 // volatile version
8743 ParamTypes[0] =
8744 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8745 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8746 /*IsAssignmentOperator=*/true);
8747 }
8748
8749 if (!(*Ptr).isRestrictQualified() &&
8750 VisibleTypeConversionsQuals.hasRestrict()) {
8751 // restrict version
8752 ParamTypes[0]
8753 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8754 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8755 /*IsAssignmentOperator=*/true);
8756
8757 if (NeedVolatile) {
8758 // volatile restrict version
8759 ParamTypes[0]
8760 = S.Context.getLValueReferenceType(
8761 S.Context.getCVRQualifiedType(*Ptr,
8762 (Qualifiers::Volatile |
8763 Qualifiers::Restrict)));
8764 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8765 /*IsAssignmentOperator=*/true);
8766 }
8767 }
8768 }
8769 }
8770 }
8771
8772 // C++ [over.built]p18:
8773 //
8774 // For every triple (L, VQ, R), where L is an arithmetic type,
8775 // VQ is either volatile or empty, and R is a promoted
8776 // arithmetic type, there exist candidate operator functions of
8777 // the form
8778 //
8779 // VQ L& operator=(VQ L&, R);
8780 // VQ L& operator*=(VQ L&, R);
8781 // VQ L& operator/=(VQ L&, R);
8782 // VQ L& operator+=(VQ L&, R);
8783 // VQ L& operator-=(VQ L&, R);
8784 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8785 if (!HasArithmeticOrEnumeralCandidateType)
8786 return;
8787
8788 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8789 for (unsigned Right = FirstPromotedArithmeticType;
8790 Right < LastPromotedArithmeticType; ++Right) {
8791 QualType ParamTypes[2];
8792 ParamTypes[1] = ArithmeticTypes[Right];
8793 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8794 S, ArithmeticTypes[Left], Args[0]);
8795 // Add this built-in operator as a candidate (VQ is empty).
8796 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8797 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8798 /*IsAssignmentOperator=*/isEqualOp);
8799
8800 // Add this built-in operator as a candidate (VQ is 'volatile').
8801 if (VisibleTypeConversionsQuals.hasVolatile()) {
8802 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8803 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8804 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8805 /*IsAssignmentOperator=*/isEqualOp);
8806 }
8807 }
8808 }
8809
8810 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8811 for (BuiltinCandidateTypeSet::iterator
8812 Vec1 = CandidateTypes[0].vector_begin(),
8813 Vec1End = CandidateTypes[0].vector_end();
8814 Vec1 != Vec1End; ++Vec1) {
8815 for (BuiltinCandidateTypeSet::iterator
8816 Vec2 = CandidateTypes[1].vector_begin(),
8817 Vec2End = CandidateTypes[1].vector_end();
8818 Vec2 != Vec2End; ++Vec2) {
8819 QualType ParamTypes[2];
8820 ParamTypes[1] = *Vec2;
8821 // Add this built-in operator as a candidate (VQ is empty).
8822 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8823 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8824 /*IsAssignmentOperator=*/isEqualOp);
8825
8826 // Add this built-in operator as a candidate (VQ is 'volatile').
8827 if (VisibleTypeConversionsQuals.hasVolatile()) {
8828 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8829 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8830 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8831 /*IsAssignmentOperator=*/isEqualOp);
8832 }
8833 }
8834 }
8835 }
8836
8837 // C++ [over.built]p22:
8838 //
8839 // For every triple (L, VQ, R), where L is an integral type, VQ
8840 // is either volatile or empty, and R is a promoted integral
8841 // type, there exist candidate operator functions of the form
8842 //
8843 // VQ L& operator%=(VQ L&, R);
8844 // VQ L& operator<<=(VQ L&, R);
8845 // VQ L& operator>>=(VQ L&, R);
8846 // VQ L& operator&=(VQ L&, R);
8847 // VQ L& operator^=(VQ L&, R);
8848 // VQ L& operator|=(VQ L&, R);
8849 void addAssignmentIntegralOverloads() {
8850 if (!HasArithmeticOrEnumeralCandidateType)
8851 return;
8852
8853 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8854 for (unsigned Right = FirstPromotedIntegralType;
8855 Right < LastPromotedIntegralType; ++Right) {
8856 QualType ParamTypes[2];
8857 ParamTypes[1] = ArithmeticTypes[Right];
8858 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8859 S, ArithmeticTypes[Left], Args[0]);
8860 // Add this built-in operator as a candidate (VQ is empty).
8861 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8862 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8863 if (VisibleTypeConversionsQuals.hasVolatile()) {
8864 // Add this built-in operator as a candidate (VQ is 'volatile').
8865 ParamTypes[0] = LeftBaseTy;
8866 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8867 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8868 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8869 }
8870 }
8871 }
8872 }
8873
8874 // C++ [over.operator]p23:
8875 //
8876 // There also exist candidate operator functions of the form
8877 //
8878 // bool operator!(bool);
8879 // bool operator&&(bool, bool);
8880 // bool operator||(bool, bool);
8881 void addExclaimOverload() {
8882 QualType ParamTy = S.Context.BoolTy;
8883 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8884 /*IsAssignmentOperator=*/false,
8885 /*NumContextualBoolArguments=*/1);
8886 }
8887 void addAmpAmpOrPipePipeOverload() {
8888 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8889 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8890 /*IsAssignmentOperator=*/false,
8891 /*NumContextualBoolArguments=*/2);
8892 }
8893
8894 // C++ [over.built]p13:
8895 //
8896 // For every cv-qualified or cv-unqualified object type T there
8897 // exist candidate operator functions of the form
8898 //
8899 // T* operator+(T*, ptrdiff_t); [ABOVE]
8900 // T& operator[](T*, ptrdiff_t);
8901 // T* operator-(T*, ptrdiff_t); [ABOVE]
8902 // T* operator+(ptrdiff_t, T*); [ABOVE]
8903 // T& operator[](ptrdiff_t, T*);
8904 void addSubscriptOverloads() {
8905 for (BuiltinCandidateTypeSet::iterator
8906 Ptr = CandidateTypes[0].pointer_begin(),
8907 PtrEnd = CandidateTypes[0].pointer_end();
8908 Ptr != PtrEnd; ++Ptr) {
8909 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8910 QualType PointeeType = (*Ptr)->getPointeeType();
8911 if (!PointeeType->isObjectType())
8912 continue;
8913
8914 // T& operator[](T*, ptrdiff_t)
8915 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8916 }
8917
8918 for (BuiltinCandidateTypeSet::iterator
8919 Ptr = CandidateTypes[1].pointer_begin(),
8920 PtrEnd = CandidateTypes[1].pointer_end();
8921 Ptr != PtrEnd; ++Ptr) {
8922 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8923 QualType PointeeType = (*Ptr)->getPointeeType();
8924 if (!PointeeType->isObjectType())
8925 continue;
8926
8927 // T& operator[](ptrdiff_t, T*)
8928 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8929 }
8930 }
8931
8932 // C++ [over.built]p11:
8933 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8934 // C1 is the same type as C2 or is a derived class of C2, T is an object
8935 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8936 // there exist candidate operator functions of the form
8937 //
8938 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8939 //
8940 // where CV12 is the union of CV1 and CV2.
8941 void addArrowStarOverloads() {
8942 for (BuiltinCandidateTypeSet::iterator
8943 Ptr = CandidateTypes[0].pointer_begin(),
8944 PtrEnd = CandidateTypes[0].pointer_end();
8945 Ptr != PtrEnd; ++Ptr) {
8946 QualType C1Ty = (*Ptr);
8947 QualType C1;
8948 QualifierCollector Q1;
8949 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8950 if (!isa<RecordType>(C1))
8951 continue;
8952 // heuristic to reduce number of builtin candidates in the set.
8953 // Add volatile/restrict version only if there are conversions to a
8954 // volatile/restrict type.
8955 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8956 continue;
8957 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8958 continue;
8959 for (BuiltinCandidateTypeSet::iterator
8960 MemPtr = CandidateTypes[1].member_pointer_begin(),
8961 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8962 MemPtr != MemPtrEnd; ++MemPtr) {
8963 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8964 QualType C2 = QualType(mptr->getClass(), 0);
8965 C2 = C2.getUnqualifiedType();
8966 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8967 break;
8968 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8969 // build CV12 T&
8970 QualType T = mptr->getPointeeType();
8971 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8972 T.isVolatileQualified())
8973 continue;
8974 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8975 T.isRestrictQualified())
8976 continue;
8977 T = Q1.apply(S.Context, T);
8978 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8979 }
8980 }
8981 }
8982
8983 // Note that we don't consider the first argument, since it has been
8984 // contextually converted to bool long ago. The candidates below are
8985 // therefore added as binary.
8986 //
8987 // C++ [over.built]p25:
8988 // For every type T, where T is a pointer, pointer-to-member, or scoped
8989 // enumeration type, there exist candidate operator functions of the form
8990 //
8991 // T operator?(bool, T, T);
8992 //
8993 void addConditionalOperatorOverloads() {
8994 /// Set of (canonical) types that we've already handled.
8995 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8996
8997 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8998 for (BuiltinCandidateTypeSet::iterator
8999 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9000 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9001 Ptr != PtrEnd; ++Ptr) {
9002 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9003 continue;
9004
9005 QualType ParamTypes[2] = { *Ptr, *Ptr };
9006 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9007 }
9008
9009 for (BuiltinCandidateTypeSet::iterator
9010 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9011 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9012 MemPtr != MemPtrEnd; ++MemPtr) {
9013 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9014 continue;
9015
9016 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9017 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9018 }
9019
9020 if (S.getLangOpts().CPlusPlus11) {
9021 for (BuiltinCandidateTypeSet::iterator
9022 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9023 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9024 Enum != EnumEnd; ++Enum) {
9025 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9026 continue;
9027
9028 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9029 continue;
9030
9031 QualType ParamTypes[2] = { *Enum, *Enum };
9032 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9033 }
9034 }
9035 }
9036 }
9037};
9038
9039} // end anonymous namespace
9040
9041/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9042/// operator overloads to the candidate set (C++ [over.built]), based
9043/// on the operator @p Op and the arguments given. For example, if the
9044/// operator is a binary '+', this routine might add "int
9045/// operator+(int, int)" to cover integer addition.
9046void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9047 SourceLocation OpLoc,
9048 ArrayRef<Expr *> Args,
9049 OverloadCandidateSet &CandidateSet) {
9050 // Find all of the types that the arguments can convert to, but only
9051 // if the operator we're looking at has built-in operator candidates
9052 // that make use of these types. Also record whether we encounter non-record
9053 // candidate types or either arithmetic or enumeral candidate types.
9054 Qualifiers VisibleTypeConversionsQuals;
9055 VisibleTypeConversionsQuals.addConst();
9056 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9057 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9058
9059 bool HasNonRecordCandidateType = false;
9060 bool HasArithmeticOrEnumeralCandidateType = false;
9061 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9062 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9063 CandidateTypes.emplace_back(*this);
9064 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9065 OpLoc,
9066 true,
9067 (Op == OO_Exclaim ||
9068 Op == OO_AmpAmp ||
9069 Op == OO_PipePipe),
9070 VisibleTypeConversionsQuals);
9071 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9072 CandidateTypes[ArgIdx].hasNonRecordTypes();
9073 HasArithmeticOrEnumeralCandidateType =
9074 HasArithmeticOrEnumeralCandidateType ||
9075 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9076 }
9077
9078 // Exit early when no non-record types have been added to the candidate set
9079 // for any of the arguments to the operator.
9080 //
9081 // We can't exit early for !, ||, or &&, since there we have always have
9082 // 'bool' overloads.
9083 if (!HasNonRecordCandidateType &&
9084 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9085 return;
9086
9087 // Setup an object to manage the common state for building overloads.
9088 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9089 VisibleTypeConversionsQuals,
9090 HasArithmeticOrEnumeralCandidateType,
9091 CandidateTypes, CandidateSet);
9092
9093 // Dispatch over the operation to add in only those overloads which apply.
9094 switch (Op) {
9095 case OO_None:
9096 case NUM_OVERLOADED_OPERATORS:
9097 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9097)
;
9098
9099 case OO_New:
9100 case OO_Delete:
9101 case OO_Array_New:
9102 case OO_Array_Delete:
9103 case OO_Call:
9104 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9105)
9105 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9105)
;
9106
9107 case OO_Comma:
9108 case OO_Arrow:
9109 case OO_Coawait:
9110 // C++ [over.match.oper]p3:
9111 // -- For the operator ',', the unary operator '&', the
9112 // operator '->', or the operator 'co_await', the
9113 // built-in candidates set is empty.
9114 break;
9115
9116 case OO_Plus: // '+' is either unary or binary
9117 if (Args.size() == 1)
9118 OpBuilder.addUnaryPlusPointerOverloads();
9119 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9120
9121 case OO_Minus: // '-' is either unary or binary
9122 if (Args.size() == 1) {
9123 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9124 } else {
9125 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9126 OpBuilder.addGenericBinaryArithmeticOverloads();
9127 }
9128 break;
9129
9130 case OO_Star: // '*' is either unary or binary
9131 if (Args.size() == 1)
9132 OpBuilder.addUnaryStarPointerOverloads();
9133 else
9134 OpBuilder.addGenericBinaryArithmeticOverloads();
9135 break;
9136
9137 case OO_Slash:
9138 OpBuilder.addGenericBinaryArithmeticOverloads();
9139 break;
9140
9141 case OO_PlusPlus:
9142 case OO_MinusMinus:
9143 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9144 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9145 break;
9146
9147 case OO_EqualEqual:
9148 case OO_ExclaimEqual:
9149 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9150 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9151
9152 case OO_Less:
9153 case OO_Greater:
9154 case OO_LessEqual:
9155 case OO_GreaterEqual:
9156 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9157 OpBuilder.addGenericBinaryArithmeticOverloads();
9158 break;
9159
9160 case OO_Spaceship:
9161 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9162 OpBuilder.addThreeWayArithmeticOverloads();
9163 break;
9164
9165 case OO_Percent:
9166 case OO_Caret:
9167 case OO_Pipe:
9168 case OO_LessLess:
9169 case OO_GreaterGreater:
9170 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9171 break;
9172
9173 case OO_Amp: // '&' is either unary or binary
9174 if (Args.size() == 1)
9175 // C++ [over.match.oper]p3:
9176 // -- For the operator ',', the unary operator '&', or the
9177 // operator '->', the built-in candidates set is empty.
9178 break;
9179
9180 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9181 break;
9182
9183 case OO_Tilde:
9184 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9185 break;
9186
9187 case OO_Equal:
9188 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9189 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9190
9191 case OO_PlusEqual:
9192 case OO_MinusEqual:
9193 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9194 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9195
9196 case OO_StarEqual:
9197 case OO_SlashEqual:
9198 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9199 break;
9200
9201 case OO_PercentEqual:
9202 case OO_LessLessEqual:
9203 case OO_GreaterGreaterEqual:
9204 case OO_AmpEqual:
9205 case OO_CaretEqual:
9206 case OO_PipeEqual:
9207 OpBuilder.addAssignmentIntegralOverloads();
9208 break;
9209
9210 case OO_Exclaim:
9211 OpBuilder.addExclaimOverload();
9212 break;
9213
9214 case OO_AmpAmp:
9215 case OO_PipePipe:
9216 OpBuilder.addAmpAmpOrPipePipeOverload();
9217 break;
9218
9219 case OO_Subscript:
9220 OpBuilder.addSubscriptOverloads();
9221 break;
9222
9223 case OO_ArrowStar:
9224 OpBuilder.addArrowStarOverloads();
9225 break;
9226
9227 case OO_Conditional:
9228 OpBuilder.addConditionalOperatorOverloads();
9229 OpBuilder.addGenericBinaryArithmeticOverloads();
9230 break;
9231 }
9232}
9233
9234/// Add function candidates found via argument-dependent lookup
9235/// to the set of overloading candidates.
9236///
9237/// This routine performs argument-dependent name lookup based on the
9238/// given function name (which may also be an operator name) and adds
9239/// all of the overload candidates found by ADL to the overload
9240/// candidate set (C++ [basic.lookup.argdep]).
9241void
9242Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9243 SourceLocation Loc,
9244 ArrayRef<Expr *> Args,
9245 TemplateArgumentListInfo *ExplicitTemplateArgs,
9246 OverloadCandidateSet& CandidateSet,
9247 bool PartialOverloading) {
9248 ADLResult Fns;
9249
9250 // FIXME: This approach for uniquing ADL results (and removing
9251 // redundant candidates from the set) relies on pointer-equality,
9252 // which means we need to key off the canonical decl. However,
9253 // always going back to the canonical decl might not get us the
9254 // right set of default arguments. What default arguments are
9255 // we supposed to consider on ADL candidates, anyway?
9256
9257 // FIXME: Pass in the explicit template arguments?
9258 ArgumentDependentLookup(Name, Loc, Args, Fns);
9259
9260 // Erase all of the candidates we already knew about.
9261 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9262 CandEnd = CandidateSet.end();
9263 Cand != CandEnd; ++Cand)
9264 if (Cand->Function) {
9265 Fns.erase(Cand->Function);
9266 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9267 Fns.erase(FunTmpl);
9268 }
9269
9270 // For each of the ADL candidates we found, add it to the overload
9271 // set.
9272 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9273 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9274
9275 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9276 if (ExplicitTemplateArgs)
9277 continue;
9278
9279 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
9280 /*SuppressUserConversions=*/false, PartialOverloading,
9281 /*AllowExplicit*/ true,
9282 /*AllowExplicitConversions*/ false,
9283 ADLCallKind::UsesADL);
9284 } else {
9285 AddTemplateOverloadCandidate(
9286 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
9287 CandidateSet,
9288 /*SuppressUserConversions=*/false, PartialOverloading,
9289 /*AllowExplicit*/true, ADLCallKind::UsesADL);
9290 }
9291 }
9292}
9293
9294namespace {
9295enum class Comparison { Equal, Better, Worse };
9296}
9297
9298/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9299/// overload resolution.
9300///
9301/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9302/// Cand1's first N enable_if attributes have precisely the same conditions as
9303/// Cand2's first N enable_if attributes (where N = the number of enable_if
9304/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9305///
9306/// Note that you can have a pair of candidates such that Cand1's enable_if
9307/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9308/// worse than Cand1's.
9309static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9310 const FunctionDecl *Cand2) {
9311 // Common case: One (or both) decls don't have enable_if attrs.
9312 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9313 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9314 if (!Cand1Attr || !Cand2Attr) {
9315 if (Cand1Attr == Cand2Attr)
9316 return Comparison::Equal;
9317 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9318 }
9319
9320 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9321 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9322
9323 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9324 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9325 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9326 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9327
9328 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9329 // has fewer enable_if attributes than Cand2, and vice versa.
9330 if (!Cand1A)
9331 return Comparison::Worse;
9332 if (!Cand2A)
9333 return Comparison::Better;
9334
9335 Cand1ID.clear();
9336 Cand2ID.clear();
9337
9338 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9339 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9340 if (Cand1ID != Cand2ID)
9341 return Comparison::Worse;
9342 }
9343
9344 return Comparison::Equal;
9345}
9346
9347static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9348 const OverloadCandidate &Cand2) {
9349 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9350 !Cand2.Function->isMultiVersion())
9351 return false;
9352
9353 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9354 // is obviously better.
9355 if (Cand1.Function->isInvalidDecl()) return false;
9356 if (Cand2.Function->isInvalidDecl()) return true;
9357
9358 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9359 // cpu_dispatch, else arbitrarily based on the identifiers.
9360 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9361 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9362 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9363 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9364
9365 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9366 return false;
9367
9368 if (Cand1CPUDisp && !Cand2CPUDisp)
9369 return true;
9370 if (Cand2CPUDisp && !Cand1CPUDisp)
9371 return false;
9372
9373 if (Cand1CPUSpec && Cand2CPUSpec) {
9374 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9375 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9376
9377 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9378 FirstDiff = std::mismatch(
9379 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9380 Cand2CPUSpec->cpus_begin(),
9381 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9382 return LHS->getName() == RHS->getName();
9383 });
9384
9385 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9387, __PRETTY_FUNCTION__))
9386 "Two different cpu-specific versions should not have the same "((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9387, __PRETTY_FUNCTION__))
9387 "identifier list, otherwise they'd be the same decl!")((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9387, __PRETTY_FUNCTION__))
;
9388 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9389 }
9390 llvm_unreachable("No way to get here unless both had cpu_dispatch")::llvm::llvm_unreachable_internal("No way to get here unless both had cpu_dispatch"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9390)
;
9391}
9392
9393/// isBetterOverloadCandidate - Determines whether the first overload
9394/// candidate is a better candidate than the second (C++ 13.3.3p1).
9395bool clang::isBetterOverloadCandidate(
9396 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9397 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9398 // Define viable functions to be better candidates than non-viable
9399 // functions.
9400 if (!Cand2.Viable)
9401 return Cand1.Viable;
9402 else if (!Cand1.Viable)
9403 return false;
9404
9405 // C++ [over.match.best]p1:
9406 //
9407 // -- if F is a static member function, ICS1(F) is defined such
9408 // that ICS1(F) is neither better nor worse than ICS1(G) for
9409 // any function G, and, symmetrically, ICS1(G) is neither
9410 // better nor worse than ICS1(F).
9411 unsigned StartArg = 0;
9412 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9413 StartArg = 1;
9414
9415 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9416 // We don't allow incompatible pointer conversions in C++.
9417 if (!S.getLangOpts().CPlusPlus)
9418 return ICS.isStandard() &&
9419 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9420
9421 // The only ill-formed conversion we allow in C++ is the string literal to
9422 // char* conversion, which is only considered ill-formed after C++11.
9423 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9424 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9425 };
9426
9427 // Define functions that don't require ill-formed conversions for a given
9428 // argument to be better candidates than functions that do.
9429 unsigned NumArgs = Cand1.Conversions.size();
9430 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")((Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"
) ? static_cast<void> (0) : __assert_fail ("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9430, __PRETTY_FUNCTION__))
;
9431 bool HasBetterConversion = false;
9432 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9433 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9434 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9435 if (Cand1Bad != Cand2Bad) {
9436 if (Cand1Bad)
9437 return false;
9438 HasBetterConversion = true;
9439 }
9440 }
9441
9442 if (HasBetterConversion)
9443 return true;
9444
9445 // C++ [over.match.best]p1:
9446 // A viable function F1 is defined to be a better function than another
9447 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9448 // conversion sequence than ICSi(F2), and then...
9449 bool HasWorseConversion = false;
9450 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9451 switch (CompareImplicitConversionSequences(S, Loc,
9452 Cand1.Conversions[ArgIdx],
9453 Cand2.Conversions[ArgIdx])) {
9454 case ImplicitConversionSequence::Better:
9455 // Cand1 has a better conversion sequence.
9456 HasBetterConversion = true;
9457 break;
9458
9459 case ImplicitConversionSequence::Worse:
9460 if (Cand1.Function && Cand1.Function == Cand2.Function &&
9461 (Cand2.RewriteKind & CRK_Reversed) != 0) {
9462 // Work around large-scale breakage caused by considering reversed
9463 // forms of operator== in C++20:
9464 //
9465 // When comparing a function against its reversed form, if we have a
9466 // better conversion for one argument and a worse conversion for the
9467 // other, we prefer the non-reversed form.
9468 //
9469 // This prevents a conversion function from being considered ambiguous
9470 // with its own reversed form in various where it's only incidentally
9471 // heterogeneous.
9472 //
9473 // We diagnose this as an extension from CreateOverloadedBinOp.
9474 HasWorseConversion = true;
9475 break;
9476 }
9477
9478 // Cand1 can't be better than Cand2.
9479 return false;
9480
9481 case ImplicitConversionSequence::Indistinguishable:
9482 // Do nothing.
9483 break;
9484 }
9485 }
9486
9487 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9488 // ICSj(F2), or, if not that,
9489 if (HasBetterConversion)
9490 return true;
9491 if (HasWorseConversion)
9492 return false;
9493
9494 // -- the context is an initialization by user-defined conversion
9495 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9496 // from the return type of F1 to the destination type (i.e.,
9497 // the type of the entity being initialized) is a better
9498 // conversion sequence than the standard conversion sequence
9499 // from the return type of F2 to the destination type.
9500 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9501 Cand1.Function && Cand2.Function &&
9502 isa<CXXConversionDecl>(Cand1.Function) &&
9503 isa<CXXConversionDecl>(Cand2.Function)) {
9504 // First check whether we prefer one of the conversion functions over the
9505 // other. This only distinguishes the results in non-standard, extension
9506 // cases such as the conversion from a lambda closure type to a function
9507 // pointer or block.
9508 ImplicitConversionSequence::CompareKind Result =
9509 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9510 if (Result == ImplicitConversionSequence::Indistinguishable)
9511 Result = CompareStandardConversionSequences(S, Loc,
9512 Cand1.FinalConversion,
9513 Cand2.FinalConversion);
9514
9515 if (Result != ImplicitConversionSequence::Indistinguishable)
9516 return Result == ImplicitConversionSequence::Better;
9517
9518 // FIXME: Compare kind of reference binding if conversion functions
9519 // convert to a reference type used in direct reference binding, per
9520 // C++14 [over.match.best]p1 section 2 bullet 3.
9521 }
9522
9523 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9524 // as combined with the resolution to CWG issue 243.
9525 //
9526 // When the context is initialization by constructor ([over.match.ctor] or
9527 // either phase of [over.match.list]), a constructor is preferred over
9528 // a conversion function.
9529 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9530 Cand1.Function && Cand2.Function &&
9531 isa<CXXConstructorDecl>(Cand1.Function) !=
9532 isa<CXXConstructorDecl>(Cand2.Function))
9533 return isa<CXXConstructorDecl>(Cand1.Function);
9534
9535 // -- F1 is a non-template function and F2 is a function template
9536 // specialization, or, if not that,
9537 bool Cand1IsSpecialization = Cand1.Function &&
9538 Cand1.Function->getPrimaryTemplate();
9539 bool Cand2IsSpecialization = Cand2.Function &&
9540 Cand2.Function->getPrimaryTemplate();
9541 if (Cand1IsSpecialization != Cand2IsSpecialization)
9542 return Cand2IsSpecialization;
9543
9544 // -- F1 and F2 are function template specializations, and the function
9545 // template for F1 is more specialized than the template for F2
9546 // according to the partial ordering rules described in 14.5.5.2, or,
9547 // if not that,
9548 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9549 if (FunctionTemplateDecl *BetterTemplate
9550 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9551 Cand2.Function->getPrimaryTemplate(),
9552 Loc,
9553 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9554 : TPOC_Call,
9555 Cand1.ExplicitCallArguments,
9556 Cand2.ExplicitCallArguments))
9557 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9558 }
9559
9560 // -— F1 and F2 are non-template functions with the same
9561 // parameter-type-lists, and F1 is more constrained than F2 [...],
9562 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9563 !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9564 Cand2.Function->hasPrototype()) {
9565 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9566 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9567 if (PT1->getNumParams() == PT2->getNumParams() &&
9568 PT1->isVariadic() == PT2->isVariadic() &&
9569 S.FunctionParamTypesAreEqual(PT1, PT2)) {
9570 Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9571 Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9572 if (RC1 && RC2) {
9573 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9574 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9575 {RC2}, AtLeastAsConstrained1))
9576 return false;
9577 if (!AtLeastAsConstrained1)
9578 return false;
9579 if (S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9580 {RC1}, AtLeastAsConstrained2))
9581 return false;
9582 if (!AtLeastAsConstrained2)
9583 return true;
9584 } else if (RC1 || RC2)
9585 return RC1 != nullptr;
9586 }
9587 }
9588
9589 // -- F1 is a constructor for a class D, F2 is a constructor for a base
9590 // class B of D, and for all arguments the corresponding parameters of
9591 // F1 and F2 have the same type.
9592 // FIXME: Implement the "all parameters have the same type" check.
9593 bool Cand1IsInherited =
9594 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9595 bool Cand2IsInherited =
9596 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9597 if (Cand1IsInherited != Cand2IsInherited)
9598 return Cand2IsInherited;
9599 else if (Cand1IsInherited) {
9600 assert(Cand2IsInherited)((Cand2IsInherited) ? static_cast<void> (0) : __assert_fail
("Cand2IsInherited", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9600, __PRETTY_FUNCTION__))
;
9601 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9602 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9603 if (Cand1Class->isDerivedFrom(Cand2Class))
9604 return true;
9605 if (Cand2Class->isDerivedFrom(Cand1Class))
9606 return false;
9607 // Inherited from sibling base classes: still ambiguous.
9608 }
9609
9610 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9611 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9612 // with reversed order of parameters and F1 is not
9613 //
9614 // We rank reversed + different operator as worse than just reversed, but
9615 // that comparison can never happen, because we only consider reversing for
9616 // the maximally-rewritten operator (== or <=>).
9617 if (Cand1.RewriteKind != Cand2.RewriteKind)
9618 return Cand1.RewriteKind < Cand2.RewriteKind;
9619
9620 // Check C++17 tie-breakers for deduction guides.
9621 {
9622 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9623 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9624 if (Guide1 && Guide2) {
9625 // -- F1 is generated from a deduction-guide and F2 is not
9626 if (Guide1->isImplicit() != Guide2->isImplicit())
9627 return Guide2->isImplicit();
9628
9629 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9630 if (Guide1->isCopyDeductionCandidate())
9631 return true;
9632 }
9633 }
9634
9635 // Check for enable_if value-based overload resolution.
9636 if (Cand1.Function && Cand2.Function) {
9637 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9638 if (Cmp != Comparison::Equal)
9639 return Cmp == Comparison::Better;
9640 }
9641
9642 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9643 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9644 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9645 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9646 }
9647
9648 bool HasPS1 = Cand1.Function != nullptr &&
9649 functionHasPassObjectSizeParams(Cand1.Function);
9650 bool HasPS2 = Cand2.Function != nullptr &&
9651 functionHasPassObjectSizeParams(Cand2.Function);
9652 if (HasPS1 != HasPS2 && HasPS1)
9653 return true;
9654
9655 return isBetterMultiversionCandidate(Cand1, Cand2);
9656}
9657
9658/// Determine whether two declarations are "equivalent" for the purposes of
9659/// name lookup and overload resolution. This applies when the same internal/no
9660/// linkage entity is defined by two modules (probably by textually including
9661/// the same header). In such a case, we don't consider the declarations to
9662/// declare the same entity, but we also don't want lookups with both
9663/// declarations visible to be ambiguous in some cases (this happens when using
9664/// a modularized libstdc++).
9665bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9666 const NamedDecl *B) {
9667 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9668 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9669 if (!VA || !VB)
9670 return false;
9671
9672 // The declarations must be declaring the same name as an internal linkage
9673 // entity in different modules.
9674 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9675 VB->getDeclContext()->getRedeclContext()) ||
9676 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9677 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9678 VA->isExternallyVisible() || VB->isExternallyVisible())
9679 return false;
9680
9681 // Check that the declarations appear to be equivalent.
9682 //
9683 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9684 // For constants and functions, we should check the initializer or body is
9685 // the same. For non-constant variables, we shouldn't allow it at all.
9686 if (Context.hasSameType(VA->getType(), VB->getType()))
9687 return true;
9688
9689 // Enum constants within unnamed enumerations will have different types, but
9690 // may still be similar enough to be interchangeable for our purposes.
9691 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9692 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9693 // Only handle anonymous enums. If the enumerations were named and
9694 // equivalent, they would have been merged to the same type.
9695 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9696 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9697 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9698 !Context.hasSameType(EnumA->getIntegerType(),
9699 EnumB->getIntegerType()))
9700 return false;
9701 // Allow this only if the value is the same for both enumerators.
9702 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9703 }
9704 }
9705
9706 // Nothing else is sufficiently similar.
9707 return false;
9708}
9709
9710void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9711 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9712 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9713
9714 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9715 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9716 << !M << (M ? M->getFullModuleName() : "");
9717
9718 for (auto *E : Equiv) {
9719 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9720 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9721 << !M << (M ? M->getFullModuleName() : "");
9722 }
9723}
9724
9725/// Computes the best viable function (C++ 13.3.3)
9726/// within an overload candidate set.
9727///
9728/// \param Loc The location of the function name (or operator symbol) for
9729/// which overload resolution occurs.
9730///
9731/// \param Best If overload resolution was successful or found a deleted
9732/// function, \p Best points to the candidate function found.
9733///
9734/// \returns The result of overload resolution.
9735OverloadingResult
9736OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9737 iterator &Best) {
9738 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9739 std::transform(begin(), end(), std::back_inserter(Candidates),
9740 [](OverloadCandidate &Cand) { return &Cand; });
9741
9742 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9743 // are accepted by both clang and NVCC. However, during a particular
9744 // compilation mode only one call variant is viable. We need to
9745 // exclude non-viable overload candidates from consideration based
9746 // only on their host/device attributes. Specifically, if one
9747 // candidate call is WrongSide and the other is SameSide, we ignore
9748 // the WrongSide candidate.
9749 if (S.getLangOpts().CUDA) {
9750 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9751 bool ContainsSameSideCandidate =
9752 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9753 // Check viable function only.
9754 return Cand->Viable && Cand->Function &&
9755 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9756 Sema::CFP_SameSide;
9757 });
9758 if (ContainsSameSideCandidate) {
9759 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9760 // Check viable function only to avoid unnecessary data copying/moving.
9761 return Cand->Viable && Cand->Function &&
9762 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9763 Sema::CFP_WrongSide;
9764 };
9765 llvm::erase_if(Candidates, IsWrongSideCandidate);
9766 }
9767 }
9768
9769 // Find the best viable function.
9770 Best = end();
9771 for (auto *Cand : Candidates) {
9772 Cand->Best = false;
9773 if (Cand->Viable)
9774 if (Best == end() ||
9775 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9776 Best = Cand;
9777 }
9778
9779 // If we didn't find any viable functions, abort.
9780 if (Best == end())
9781 return OR_No_Viable_Function;
9782
9783 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9784
9785 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9786 PendingBest.push_back(&*Best);
9787 Best->Best = true;
9788
9789 // Make sure that this function is better than every other viable
9790 // function. If not, we have an ambiguity.
9791 while (!PendingBest.empty()) {
9792 auto *Curr = PendingBest.pop_back_val();
9793 for (auto *Cand : Candidates) {
9794 if (Cand->Viable && !Cand->Best &&
9795 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9796 PendingBest.push_back(Cand);
9797 Cand->Best = true;
9798
9799 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9800 Curr->Function))
9801 EquivalentCands.push_back(Cand->Function);
9802 else
9803 Best = end();
9804 }
9805 }
9806 }
9807
9808 // If we found more than one best candidate, this is ambiguous.
9809 if (Best == end())
9810 return OR_Ambiguous;
9811
9812 // Best is the best viable function.
9813 if (Best->Function && Best->Function->isDeleted())
9814 return OR_Deleted;
9815
9816 if (!EquivalentCands.empty())
9817 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9818 EquivalentCands);
9819
9820 return OR_Success;
9821}
9822
9823namespace {
9824
9825enum OverloadCandidateKind {
9826 oc_function,
9827 oc_method,
9828 oc_reversed_binary_operator,
9829 oc_constructor,
9830 oc_implicit_default_constructor,
9831 oc_implicit_copy_constructor,
9832 oc_implicit_move_constructor,
9833 oc_implicit_copy_assignment,
9834 oc_implicit_move_assignment,
9835 oc_implicit_equality_comparison,
9836 oc_inherited_constructor
9837};
9838
9839enum OverloadCandidateSelect {
9840 ocs_non_template,
9841 ocs_template,
9842 ocs_described_template,
9843};
9844
9845static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9846ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9847 OverloadCandidateRewriteKind CRK,
9848 std::string &Description) {
9849
9850 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9851 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9852 isTemplate = true;
9853 Description = S.getTemplateArgumentBindingsText(
9854 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9855 }
9856
9857 OverloadCandidateSelect Select = [&]() {
9858 if (!Description.empty())
9859 return ocs_described_template;
9860 return isTemplate ? ocs_template : ocs_non_template;
9861 }();
9862
9863 OverloadCandidateKind Kind = [&]() {
9864 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9865 return oc_implicit_equality_comparison;
9866
9867 if (CRK & CRK_Reversed)
9868 return oc_reversed_binary_operator;
9869
9870 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9871 if (!Ctor->isImplicit()) {
9872 if (isa<ConstructorUsingShadowDecl>(Found))
9873 return oc_inherited_constructor;
9874 else
9875 return oc_constructor;
9876 }
9877
9878 if (Ctor->isDefaultConstructor())
9879 return oc_implicit_default_constructor;
9880
9881 if (Ctor->isMoveConstructor())
9882 return oc_implicit_move_constructor;
9883
9884 assert(Ctor->isCopyConstructor() &&((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9885, __PRETTY_FUNCTION__))
9885 "unexpected sort of implicit constructor")((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9885, __PRETTY_FUNCTION__))
;
9886 return oc_implicit_copy_constructor;
9887 }
9888
9889 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9890 // This actually gets spelled 'candidate function' for now, but
9891 // it doesn't hurt to split it out.
9892 if (!Meth->isImplicit())
9893 return oc_method;
9894
9895 if (Meth->isMoveAssignmentOperator())
9896 return oc_implicit_move_assignment;
9897
9898 if (Meth->isCopyAssignmentOperator())
9899 return oc_implicit_copy_assignment;
9900
9901 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")((isa<CXXConversionDecl>(Meth) && "expected conversion"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9901, __PRETTY_FUNCTION__))
;
9902 return oc_method;
9903 }
9904
9905 return oc_function;
9906 }();
9907
9908 return std::make_pair(Kind, Select);
9909}
9910
9911void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9912 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9913 // set.
9914 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9915 S.Diag(FoundDecl->getLocation(),
9916 diag::note_ovl_candidate_inherited_constructor)
9917 << Shadow->getNominatedBaseClass();
9918}
9919
9920} // end anonymous namespace
9921
9922static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9923 const FunctionDecl *FD) {
9924 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9925 bool AlwaysTrue;
9926 if (EnableIf->getCond()->isValueDependent() ||
9927 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9928 return false;
9929 if (!AlwaysTrue)
9930 return false;
9931 }
9932 return true;
9933}
9934
9935/// Returns true if we can take the address of the function.
9936///
9937/// \param Complain - If true, we'll emit a diagnostic
9938/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9939/// we in overload resolution?
9940/// \param Loc - The location of the statement we're complaining about. Ignored
9941/// if we're not complaining, or if we're in overload resolution.
9942static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9943 bool Complain,
9944 bool InOverloadResolution,
9945 SourceLocation Loc) {
9946 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9947 if (Complain) {
9948 if (InOverloadResolution)
9949 S.Diag(FD->getBeginLoc(),
9950 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9951 else
9952 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9953 }
9954 return false;
9955 }
9956
9957 if (const Expr *RC = FD->getTrailingRequiresClause()) {
9958 ConstraintSatisfaction Satisfaction;
9959 if (S.CheckConstraintSatisfaction(RC, Satisfaction))
9960 return false;
9961 if (!Satisfaction.IsSatisfied) {
9962 if (Complain) {
9963 if (InOverloadResolution)
9964 S.Diag(FD->getBeginLoc(),
9965 diag::note_ovl_candidate_unsatisfied_constraints);
9966 else
9967 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
9968 << FD;
9969 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
9970 }
9971 return false;
9972 }
9973 }
9974
9975 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9976 return P->hasAttr<PassObjectSizeAttr>();
9977 });
9978 if (I == FD->param_end())
9979 return true;
9980
9981 if (Complain) {
9982 // Add one to ParamNo because it's user-facing
9983 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9984 if (InOverloadResolution)
9985 S.Diag(FD->getLocation(),
9986 diag::note_ovl_candidate_has_pass_object_size_params)
9987 << ParamNo;
9988 else
9989 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9990 << FD << ParamNo;
9991 }
9992 return false;
9993}
9994
9995static bool checkAddressOfCandidateIsAvailable(Sema &S,
9996 const FunctionDecl *FD) {
9997 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9998 /*InOverloadResolution=*/true,
9999 /*Loc=*/SourceLocation());
10000}
10001
10002bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10003 bool Complain,
10004 SourceLocation Loc) {
10005 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10006 /*InOverloadResolution=*/false,
10007 Loc);
10008}
10009
10010// Notes the location of an overload candidate.
10011void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10012 OverloadCandidateRewriteKind RewriteKind,
10013 QualType DestType, bool TakingAddress) {
10014 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10015 return;
10016 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10017 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10018 return;
10019
10020 std::string FnDesc;
10021 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10022 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10023 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10024 << (unsigned)KSPair.first << (unsigned)KSPair.second
10025 << Fn << FnDesc;
10026
10027 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10028 Diag(Fn->getLocation(), PD);
10029 MaybeEmitInheritedConstructorNote(*this, Found);
10030}
10031
10032static void
10033MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10034 // Perhaps the ambiguity was caused by two atomic constraints that are
10035 // 'identical' but not equivalent:
10036 //
10037 // void foo() requires (sizeof(T) > 4) { } // #1
10038 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10039 //
10040 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10041 // #2 to subsume #1, but these constraint are not considered equivalent
10042 // according to the subsumption rules because they are not the same
10043 // source-level construct. This behavior is quite confusing and we should try
10044 // to help the user figure out what happened.
10045
10046 SmallVector<const Expr *, 3> FirstAC, SecondAC;
10047 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10048 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10049 if (!I->Function)
10050 continue;
10051 SmallVector<const Expr *, 3> AC;
10052 if (auto *Template = I->Function->getPrimaryTemplate())
10053 Template->getAssociatedConstraints(AC);
10054 else
10055 I->Function->getAssociatedConstraints(AC);
10056 if (AC.empty())
10057 continue;
10058 if (FirstCand == nullptr) {
10059 FirstCand = I->Function;
10060 FirstAC = AC;
10061 } else if (SecondCand == nullptr) {
10062 SecondCand = I->Function;
10063 SecondAC = AC;
10064 } else {
10065 // We have more than one pair of constrained functions - this check is
10066 // expensive and we'd rather not try to diagnose it.
10067 return;
10068 }
10069 }
10070 if (!SecondCand)
10071 return;
10072 // The diagnostic can only happen if there are associated constraints on
10073 // both sides (there needs to be some identical atomic constraint).
10074 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10075 SecondCand, SecondAC))
10076 // Just show the user one diagnostic, they'll probably figure it out
10077 // from here.
10078 return;
10079}
10080
10081// Notes the location of all overload candidates designated through
10082// OverloadedExpr
10083void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10084 bool TakingAddress) {
10085 assert(OverloadedExpr->getType() == Context.OverloadTy)((OverloadedExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10085, __PRETTY_FUNCTION__))
;
10086
10087 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10088 OverloadExpr *OvlExpr = Ovl.Expression;
10089
10090 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10091 IEnd = OvlExpr->decls_end();
10092 I != IEnd; ++I) {
10093 if (FunctionTemplateDecl *FunTmpl =
10094 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10095 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10096 TakingAddress);
10097 } else if (FunctionDecl *Fun
10098 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10099 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10100 }
10101 }
10102}
10103
10104/// Diagnoses an ambiguous conversion. The partial diagnostic is the
10105/// "lead" diagnostic; it will be given two arguments, the source and
10106/// target types of the conversion.
10107void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10108 Sema &S,
10109 SourceLocation CaretLoc,
10110 const PartialDiagnostic &PDiag) const {
10111 S.Diag(CaretLoc, PDiag)
10112 << Ambiguous.getFromType() << Ambiguous.getToType();
10113 // FIXME: The note limiting machinery is borrowed from
10114 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10115 // refactoring here.
10116 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10117 unsigned CandsShown = 0;
10118 AmbiguousConversionSequence::const_iterator I, E;
10119 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10120 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10121 break;
10122 ++CandsShown;
10123 S.NoteOverloadCandidate(I->first, I->second);
10124 }
10125 if (I != E)
10126 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10127}
10128
10129static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10130 unsigned I, bool TakingCandidateAddress) {
10131 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10132 assert(Conv.isBad())((Conv.isBad()) ? static_cast<void> (0) : __assert_fail
("Conv.isBad()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10132, __PRETTY_FUNCTION__))
;
10133 assert(Cand->Function && "for now, candidate must be a function")((Cand->Function && "for now, candidate must be a function"
) ? static_cast<void> (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10133, __PRETTY_FUNCTION__))
;
10134 FunctionDecl *Fn = Cand->Function;
10135
10136 // There's a conversion slot for the object argument if this is a
10137 // non-constructor method. Note that 'I' corresponds the
10138 // conversion-slot index.
10139 bool isObjectArgument = false;
10140 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10141 if (I == 0)
10142 isObjectArgument = true;
10143 else
10144 I--;
10145 }
10146
10147 std::string FnDesc;
10148 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10149 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10150 FnDesc);
10151
10152 Expr *FromExpr = Conv.Bad.FromExpr;
10153 QualType FromTy = Conv.Bad.getFromType();
10154 QualType ToTy = Conv.Bad.getToType();
10155
10156 if (FromTy == S.Context.OverloadTy) {
10157 assert(FromExpr && "overload set argument came from implicit argument?")((FromExpr && "overload set argument came from implicit argument?"
) ? static_cast<void> (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10157, __PRETTY_FUNCTION__))
;
10158 Expr *E = FromExpr->IgnoreParens();
10159 if (isa<UnaryOperator>(E))
10160 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10161 DeclarationName Name = cast<OverloadExpr>(E)->getName();
10162
10163 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10164 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10166 << Name << I + 1;
10167 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10168 return;
10169 }
10170
10171 // Do some hand-waving analysis to see if the non-viability is due
10172 // to a qualifier mismatch.
10173 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10174 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10175 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10176 CToTy = RT->getPointeeType();
10177 else {
10178 // TODO: detect and diagnose the full richness of const mismatches.
10179 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10180 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10181 CFromTy = FromPT->getPointeeType();
10182 CToTy = ToPT->getPointeeType();
10183 }
10184 }
10185
10186 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10187 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10188 Qualifiers FromQs = CFromTy.getQualifiers();
10189 Qualifiers ToQs = CToTy.getQualifiers();
10190
10191 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10192 if (isObjectArgument)
10193 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10194 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10195 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10196 << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10197 else
10198 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10199 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10200 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10201 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10202 << ToTy->isReferenceType() << I + 1;
10203 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10204 return;
10205 }
10206
10207 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10208 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10209 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10210 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10211 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10212 << (unsigned)isObjectArgument << I + 1;
10213 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10214 return;
10215 }
10216
10217 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10218 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10219 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10220 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10221 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10222 << (unsigned)isObjectArgument << I + 1;
10223 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10224 return;
10225 }
10226
10227 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10229 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10230 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10231 << FromQs.hasUnaligned() << I + 1;
10232 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10233 return;
10234 }
10235
10236 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10237 assert(CVR && "unexpected qualifiers mismatch")((CVR && "unexpected qualifiers mismatch") ? static_cast
<void> (0) : __assert_fail ("CVR && \"unexpected qualifiers mismatch\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10237, __PRETTY_FUNCTION__))
;
10238
10239 if (isObjectArgument) {
10240 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10241 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10242 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10243 << (CVR - 1);
10244 } else {
10245 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10246 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10247 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10248 << (CVR - 1) << I + 1;
10249 }
10250 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10251 return;
10252 }
10253
10254 // Special diagnostic for failure to convert an initializer list, since
10255 // telling the user that it has type void is not useful.
10256 if (FromExpr && isa<InitListExpr>(FromExpr)) {
10257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10258 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10259 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10260 << ToTy << (unsigned)isObjectArgument << I + 1;
10261 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10262 return;
10263 }
10264
10265 // Diagnose references or pointers to incomplete types differently,
10266 // since it's far from impossible that the incompleteness triggered
10267 // the failure.
10268 QualType TempFromTy = FromTy.getNonReferenceType();
10269 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10270 TempFromTy = PTy->getPointeeType();
10271 if (TempFromTy->isIncompleteType()) {
10272 // Emit the generic diagnostic and, optionally, add the hints to it.
10273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10274 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10275 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10276 << ToTy << (unsigned)isObjectArgument << I + 1
10277 << (unsigned)(Cand->Fix.Kind);
10278
10279 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10280 return;
10281 }
10282
10283 // Diagnose base -> derived pointer conversions.
10284 unsigned BaseToDerivedConversion = 0;
10285 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10286 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10287 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10288 FromPtrTy->getPointeeType()) &&
10289 !FromPtrTy->getPointeeType()->isIncompleteType() &&
10290 !ToPtrTy->getPointeeType()->isIncompleteType() &&
10291 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10292 FromPtrTy->getPointeeType()))
10293 BaseToDerivedConversion = 1;
10294 }
10295 } else if (const ObjCObjectPointerType *FromPtrTy
10296 = FromTy->getAs<ObjCObjectPointerType>()) {
10297 if (const ObjCObjectPointerType *ToPtrTy
10298 = ToTy->getAs<ObjCObjectPointerType>())
10299 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10300 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10301 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10302 FromPtrTy->getPointeeType()) &&
10303 FromIface->isSuperClassOf(ToIface))
10304 BaseToDerivedConversion = 2;
10305 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10306 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10307 !FromTy->isIncompleteType() &&
10308 !ToRefTy->getPointeeType()->isIncompleteType() &&
10309 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10310 BaseToDerivedConversion = 3;
10311 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10312 ToTy.getNonReferenceType().getCanonicalType() ==
10313 FromTy.getNonReferenceType().getCanonicalType()) {
10314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10315 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10316 << (unsigned)isObjectArgument << I + 1
10317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10318 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10319 return;
10320 }
10321 }
10322
10323 if (BaseToDerivedConversion) {
10324 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10325 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10326 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10327 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10328 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10329 return;
10330 }
10331
10332 if (isa<ObjCObjectPointerType>(CFromTy) &&
10333 isa<PointerType>(CToTy)) {
10334 Qualifiers FromQs = CFromTy.getQualifiers();
10335 Qualifiers ToQs = CToTy.getQualifiers();
10336 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10338 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10339 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10340 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10341 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10342 return;
10343 }
10344 }
10345
10346 if (TakingCandidateAddress &&
10347 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10348 return;
10349
10350 // Emit the generic diagnostic and, optionally, add the hints to it.
10351 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10352 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10353 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10354 << ToTy << (unsigned)isObjectArgument << I + 1
10355 << (unsigned)(Cand->Fix.Kind);
10356
10357 // If we can fix the conversion, suggest the FixIts.
10358 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10359 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10360 FDiag << *HI;
10361 S.Diag(Fn->getLocation(), FDiag);
10362
10363 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10364}
10365
10366/// Additional arity mismatch diagnosis specific to a function overload
10367/// candidates. This is not covered by the more general DiagnoseArityMismatch()
10368/// over a candidate in any candidate set.
10369static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10370 unsigned NumArgs) {
10371 FunctionDecl *Fn = Cand->Function;
10372 unsigned MinParams = Fn->getMinRequiredArguments();
10373
10374 // With invalid overloaded operators, it's possible that we think we
10375 // have an arity mismatch when in fact it looks like we have the
10376 // right number of arguments, because only overloaded operators have
10377 // the weird behavior of overloading member and non-member functions.
10378 // Just don't report anything.
10379 if (Fn->isInvalidDecl() &&
10380 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10381 return true;
10382
10383 if (NumArgs < MinParams) {
10384 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10386, __PRETTY_FUNCTION__))
10385 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10386, __PRETTY_FUNCTION__))
10386 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10386, __PRETTY_FUNCTION__))
;
10387 } else {
10388 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10390, __PRETTY_FUNCTION__))
10389 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10390, __PRETTY_FUNCTION__))
10390 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10390, __PRETTY_FUNCTION__))
;
10391 }
10392
10393 return false;
10394}
10395
10396/// General arity mismatch diagnosis over a candidate in a candidate set.
10397static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10398 unsigned NumFormalArgs) {
10399 assert(isa<FunctionDecl>(D) &&((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
10400 "The templated declaration should at least be a function"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
10401 " when diagnosing bad template argument deduction due to too many"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
10402 " or too few arguments")((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
;
10403
10404 FunctionDecl *Fn = cast<FunctionDecl>(D);
10405
10406 // TODO: treat calls to a missing default constructor as a special case
10407 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
10408 unsigned MinParams = Fn->getMinRequiredArguments();
10409
10410 // at least / at most / exactly
10411 unsigned mode, modeCount;
10412 if (NumFormalArgs < MinParams) {
10413 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10414 FnTy->isTemplateVariadic())
10415 mode = 0; // "at least"
10416 else
10417 mode = 2; // "exactly"
10418 modeCount = MinParams;
10419 } else {
10420 if (MinParams != FnTy->getNumParams())
10421 mode = 1; // "at most"
10422 else
10423 mode = 2; // "exactly"
10424 modeCount = FnTy->getNumParams();
10425 }
10426
10427 std::string Description;
10428 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10429 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10430
10431 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10432 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10433 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10434 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10435 else
10436 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10437 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10438 << Description << mode << modeCount << NumFormalArgs;
10439
10440 MaybeEmitInheritedConstructorNote(S, Found);
10441}
10442
10443/// Arity mismatch diagnosis specific to a function overload candidate.
10444static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10445 unsigned NumFormalArgs) {
10446 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10447 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10448}
10449
10450static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10451 if (TemplateDecl *TD = Templated->getDescribedTemplate())
10452 return TD;
10453 llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10454)
10454 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10454)
;
10455}
10456
10457/// Diagnose a failed template-argument deduction.
10458static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10459 DeductionFailureInfo &DeductionFailure,
10460 unsigned NumArgs,
10461 bool TakingCandidateAddress) {
10462 TemplateParameter Param = DeductionFailure.getTemplateParameter();
10463 NamedDecl *ParamD;
10464 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10465 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10466 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10467 switch (DeductionFailure.Result) {
10468 case Sema::TDK_Success:
10469 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10469)
;
10470
10471 case Sema::TDK_Incomplete: {
10472 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10472, __PRETTY_FUNCTION__))
;
10473 S.Diag(Templated->getLocation(),
10474 diag::note_ovl_candidate_incomplete_deduction)
10475 << ParamD->getDeclName();
10476 MaybeEmitInheritedConstructorNote(S, Found);
10477 return;
10478 }
10479
10480 case Sema::TDK_IncompletePack: {
10481 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10481, __PRETTY_FUNCTION__))
;
10482 S.Diag(Templated->getLocation(),
10483 diag::note_ovl_candidate_incomplete_deduction_pack)
10484 << ParamD->getDeclName()
10485 << (DeductionFailure.getFirstArg()->pack_size() + 1)
10486 << *DeductionFailure.getFirstArg();
10487 MaybeEmitInheritedConstructorNote(S, Found);
10488 return;
10489 }
10490
10491 case Sema::TDK_Underqualified: {
10492 assert(ParamD && "no parameter found for bad qualifiers deduction result")((ParamD && "no parameter found for bad qualifiers deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10492, __PRETTY_FUNCTION__))
;
10493 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10494
10495 QualType Param = DeductionFailure.getFirstArg()->getAsType();
10496
10497 // Param will have been canonicalized, but it should just be a
10498 // qualified version of ParamD, so move the qualifiers to that.
10499 QualifierCollector Qs;
10500 Qs.strip(Param);
10501 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10502 assert(S.Context.hasSameType(Param, NonCanonParam))((S.Context.hasSameType(Param, NonCanonParam)) ? static_cast<
void> (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10502, __PRETTY_FUNCTION__))
;
10503
10504 // Arg has also been canonicalized, but there's nothing we can do
10505 // about that. It also doesn't matter as much, because it won't
10506 // have any template parameters in it (because deduction isn't
10507 // done on dependent types).
10508 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10509
10510 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10511 << ParamD->getDeclName() << Arg << NonCanonParam;
10512 MaybeEmitInheritedConstructorNote(S, Found);
10513 return;
10514 }
10515
10516 case Sema::TDK_Inconsistent: {
10517 assert(ParamD && "no parameter found for inconsistent deduction result")((ParamD && "no parameter found for inconsistent deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10517, __PRETTY_FUNCTION__))
;
10518 int which = 0;
10519 if (isa<TemplateTypeParmDecl>(ParamD))
10520 which = 0;
10521 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10522 // Deduction might have failed because we deduced arguments of two
10523 // different types for a non-type template parameter.
10524 // FIXME: Use a different TDK value for this.
10525 QualType T1 =
10526 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10527 QualType T2 =
10528 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10529 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10530 S.Diag(Templated->getLocation(),
10531 diag::note_ovl_candidate_inconsistent_deduction_types)
10532 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10533 << *DeductionFailure.getSecondArg() << T2;
10534 MaybeEmitInheritedConstructorNote(S, Found);
10535 return;
10536 }
10537
10538 which = 1;
10539 } else {
10540 which = 2;
10541 }
10542
10543 // Tweak the diagnostic if the problem is that we deduced packs of
10544 // different arities. We'll print the actual packs anyway in case that
10545 // includes additional useful information.
10546 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10547 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10548 DeductionFailure.getFirstArg()->pack_size() !=
10549 DeductionFailure.getSecondArg()->pack_size()) {
10550 which = 3;
10551 }
10552
10553 S.Diag(Templated->getLocation(),
10554 diag::note_ovl_candidate_inconsistent_deduction)
10555 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10556 << *DeductionFailure.getSecondArg();
10557 MaybeEmitInheritedConstructorNote(S, Found);
10558 return;
10559 }
10560
10561 case Sema::TDK_InvalidExplicitArguments:
10562 assert(ParamD && "no parameter found for invalid explicit arguments")((ParamD && "no parameter found for invalid explicit arguments"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10562, __PRETTY_FUNCTION__))
;
10563 if (ParamD->getDeclName())
10564 S.Diag(Templated->getLocation(),
10565 diag::note_ovl_candidate_explicit_arg_mismatch_named)
10566 << ParamD->getDeclName();
10567 else {
10568 int index = 0;
10569 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10570 index = TTP->getIndex();
10571 else if (NonTypeTemplateParmDecl *NTTP
10572 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10573 index = NTTP->getIndex();
10574 else
10575 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10576 S.Diag(Templated->getLocation(),
10577 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10578 << (index + 1);
10579 }
10580 MaybeEmitInheritedConstructorNote(S, Found);
10581 return;
10582
10583 case Sema::TDK_ConstraintsNotSatisfied: {
10584 // Format the template argument list into the argument string.
10585 SmallString<128> TemplateArgString;
10586 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10587 TemplateArgString = " ";
10588 TemplateArgString += S.getTemplateArgumentBindingsText(
10589 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10590 if (TemplateArgString.size() == 1)
10591 TemplateArgString.clear();
10592 S.Diag(Templated->getLocation(),
10593 diag::note_ovl_candidate_unsatisfied_constraints)
10594 << TemplateArgString;
10595
10596 S.DiagnoseUnsatisfiedConstraint(
10597 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10598 return;
10599 }
10600 case Sema::TDK_TooManyArguments:
10601 case Sema::TDK_TooFewArguments:
10602 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10603 return;
10604
10605 case Sema::TDK_InstantiationDepth:
10606 S.Diag(Templated->getLocation(),
10607 diag::note_ovl_candidate_instantiation_depth);
10608 MaybeEmitInheritedConstructorNote(S, Found);
10609 return;
10610
10611 case Sema::TDK_SubstitutionFailure: {
10612 // Format the template argument list into the argument string.
10613 SmallString<128> TemplateArgString;
10614 if (TemplateArgumentList *Args =
10615 DeductionFailure.getTemplateArgumentList()) {
10616 TemplateArgString = " ";
10617 TemplateArgString += S.getTemplateArgumentBindingsText(
10618 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10619 if (TemplateArgString.size() == 1)
10620 TemplateArgString.clear();
10621 }
10622
10623 // If this candidate was disabled by enable_if, say so.
10624 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10625 if (PDiag && PDiag->second.getDiagID() ==
10626 diag::err_typename_nested_not_found_enable_if) {
10627 // FIXME: Use the source range of the condition, and the fully-qualified
10628 // name of the enable_if template. These are both present in PDiag.
10629 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10630 << "'enable_if'" << TemplateArgString;
10631 return;
10632 }
10633
10634 // We found a specific requirement that disabled the enable_if.
10635 if (PDiag && PDiag->second.getDiagID() ==
10636 diag::err_typename_nested_not_found_requirement) {
10637 S.Diag(Templated->getLocation(),
10638 diag::note_ovl_candidate_disabled_by_requirement)
10639 << PDiag->second.getStringArg(0) << TemplateArgString;
10640 return;
10641 }
10642
10643 // Format the SFINAE diagnostic into the argument string.
10644 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10645 // formatted message in another diagnostic.
10646 SmallString<128> SFINAEArgString;
10647 SourceRange R;
10648 if (PDiag) {
10649 SFINAEArgString = ": ";
10650 R = SourceRange(PDiag->first, PDiag->first);
10651 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10652 }
10653
10654 S.Diag(Templated->getLocation(),
10655 diag::note_ovl_candidate_substitution_failure)
10656 << TemplateArgString << SFINAEArgString << R;
10657 MaybeEmitInheritedConstructorNote(S, Found);
10658 return;
10659 }
10660
10661 case Sema::TDK_DeducedMismatch:
10662 case Sema::TDK_DeducedMismatchNested: {
10663 // Format the template argument list into the argument string.
10664 SmallString<128> TemplateArgString;
10665 if (TemplateArgumentList *Args =
10666 DeductionFailure.getTemplateArgumentList()) {
10667 TemplateArgString = " ";
10668 TemplateArgString += S.getTemplateArgumentBindingsText(
10669 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10670 if (TemplateArgString.size() == 1)
10671 TemplateArgString.clear();
10672 }
10673
10674 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10675 << (*DeductionFailure.getCallArgIndex() + 1)
10676 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10677 << TemplateArgString
10678 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10679 break;
10680 }
10681
10682 case Sema::TDK_NonDeducedMismatch: {
10683 // FIXME: Provide a source location to indicate what we couldn't match.
10684 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10685 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10686 if (FirstTA.getKind() == TemplateArgument::Template &&
10687 SecondTA.getKind() == TemplateArgument::Template) {
10688 TemplateName FirstTN = FirstTA.getAsTemplate();
10689 TemplateName SecondTN = SecondTA.getAsTemplate();
10690 if (FirstTN.getKind() == TemplateName::Template &&
10691 SecondTN.getKind() == TemplateName::Template) {
10692 if (FirstTN.getAsTemplateDecl()->getName() ==
10693 SecondTN.getAsTemplateDecl()->getName()) {
10694 // FIXME: This fixes a bad diagnostic where both templates are named
10695 // the same. This particular case is a bit difficult since:
10696 // 1) It is passed as a string to the diagnostic printer.
10697 // 2) The diagnostic printer only attempts to find a better
10698 // name for types, not decls.
10699 // Ideally, this should folded into the diagnostic printer.
10700 S.Diag(Templated->getLocation(),
10701 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10702 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10703 return;
10704 }
10705 }
10706 }
10707
10708 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10709 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10710 return;
10711
10712 // FIXME: For generic lambda parameters, check if the function is a lambda
10713 // call operator, and if so, emit a prettier and more informative
10714 // diagnostic that mentions 'auto' and lambda in addition to
10715 // (or instead of?) the canonical template type parameters.
10716 S.Diag(Templated->getLocation(),
10717 diag::note_ovl_candidate_non_deduced_mismatch)
10718 << FirstTA << SecondTA;
10719 return;
10720 }
10721 // TODO: diagnose these individually, then kill off
10722 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10723 case Sema::TDK_MiscellaneousDeductionFailure:
10724 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10725 MaybeEmitInheritedConstructorNote(S, Found);
10726 return;
10727 case Sema::TDK_CUDATargetMismatch:
10728 S.Diag(Templated->getLocation(),
10729 diag::note_cuda_ovl_candidate_target_mismatch);
10730 return;
10731 }
10732}
10733
10734/// Diagnose a failed template-argument deduction, for function calls.
10735static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10736 unsigned NumArgs,
10737 bool TakingCandidateAddress) {
10738 unsigned TDK = Cand->DeductionFailure.Result;
10739 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10740 if (CheckArityMismatch(S, Cand, NumArgs))
10741 return;
10742 }
10743 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10744 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10745}
10746
10747/// CUDA: diagnose an invalid call across targets.
10748static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10749 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10750 FunctionDecl *Callee = Cand->Function;
10751
10752 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10753 CalleeTarget = S.IdentifyCUDATarget(Callee);
10754
10755 std::string FnDesc;
10756 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10757 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10758 Cand->getRewriteKind(), FnDesc);
10759
10760 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10761 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10762 << FnDesc /* Ignored */
10763 << CalleeTarget << CallerTarget;
10764
10765 // This could be an implicit constructor for which we could not infer the
10766 // target due to a collsion. Diagnose that case.
10767 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10768 if (Meth != nullptr && Meth->isImplicit()) {
10769 CXXRecordDecl *ParentClass = Meth->getParent();
10770 Sema::CXXSpecialMember CSM;
10771
10772 switch (FnKindPair.first) {
10773 default:
10774 return;
10775 case oc_implicit_default_constructor:
10776 CSM = Sema::CXXDefaultConstructor;
10777 break;
10778 case oc_implicit_copy_constructor:
10779 CSM = Sema::CXXCopyConstructor;
10780 break;
10781 case oc_implicit_move_constructor:
10782 CSM = Sema::CXXMoveConstructor;
10783 break;
10784 case oc_implicit_copy_assignment:
10785 CSM = Sema::CXXCopyAssignment;
10786 break;
10787 case oc_implicit_move_assignment:
10788 CSM = Sema::CXXMoveAssignment;
10789 break;
10790 };
10791
10792 bool ConstRHS = false;
10793 if (Meth->getNumParams()) {
10794 if (const ReferenceType *RT =
10795 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10796 ConstRHS = RT->getPointeeType().isConstQualified();
10797 }
10798 }
10799
10800 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10801 /* ConstRHS */ ConstRHS,
10802 /* Diagnose */ true);
10803 }
10804}
10805
10806static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10807 FunctionDecl *Callee = Cand->Function;
10808 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10809
10810 S.Diag(Callee->getLocation(),
10811 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10812 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10813}
10814
10815static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10816 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10817 assert(ES.isExplicit() && "not an explicit candidate")((ES.isExplicit() && "not an explicit candidate") ? static_cast
<void> (0) : __assert_fail ("ES.isExplicit() && \"not an explicit candidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10817, __PRETTY_FUNCTION__))
;
10818
10819 unsigned Kind;
10820 switch (Cand->Function->getDeclKind()) {
10821 case Decl::Kind::CXXConstructor:
10822 Kind = 0;
10823 break;
10824 case Decl::Kind::CXXConversion:
10825 Kind = 1;
10826 break;
10827 case Decl::Kind::CXXDeductionGuide:
10828 Kind = Cand->Function->isImplicit() ? 0 : 2;
10829 break;
10830 default:
10831 llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10831)
;
10832 }
10833
10834 // Note the location of the first (in-class) declaration; a redeclaration
10835 // (particularly an out-of-class definition) will typically lack the
10836 // 'explicit' specifier.
10837 // FIXME: This is probably a good thing to do for all 'candidate' notes.
10838 FunctionDecl *First = Cand->Function->getFirstDecl();
10839 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10840 First = Pattern->getFirstDecl();
10841
10842 S.Diag(First->getLocation(),
10843 diag::note_ovl_candidate_explicit)
10844 << Kind << (ES.getExpr() ? 1 : 0)
10845 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10846}
10847
10848static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10849 FunctionDecl *Callee = Cand->Function;
10850
10851 S.Diag(Callee->getLocation(),
10852 diag::note_ovl_candidate_disabled_by_extension)
10853 << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10854}
10855
10856/// Generates a 'note' diagnostic for an overload candidate. We've
10857/// already generated a primary error at the call site.
10858///
10859/// It really does need to be a single diagnostic with its caret
10860/// pointed at the candidate declaration. Yes, this creates some
10861/// major challenges of technical writing. Yes, this makes pointing
10862/// out problems with specific arguments quite awkward. It's still
10863/// better than generating twenty screens of text for every failed
10864/// overload.
10865///
10866/// It would be great to be able to express per-candidate problems
10867/// more richly for those diagnostic clients that cared, but we'd
10868/// still have to be just as careful with the default diagnostics.
10869/// \param CtorDestAS Addr space of object being constructed (for ctor
10870/// candidates only).
10871static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10872 unsigned NumArgs,
10873 bool TakingCandidateAddress,
10874 LangAS CtorDestAS = LangAS::Default) {
10875 FunctionDecl *Fn = Cand->Function;
10876
10877 // Note deleted candidates, but only if they're viable.
10878 if (Cand->Viable) {
10879 if (Fn->isDeleted()) {
10880 std::string FnDesc;
10881 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10882 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10883 Cand->getRewriteKind(), FnDesc);
10884
10885 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10886 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10887 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10888 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10889 return;
10890 }
10891
10892 // We don't really have anything else to say about viable candidates.
10893 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10894 return;
10895 }
10896
10897 switch (Cand->FailureKind) {
10898 case ovl_fail_too_many_arguments:
10899 case ovl_fail_too_few_arguments:
10900 return DiagnoseArityMismatch(S, Cand, NumArgs);
10901
10902 case ovl_fail_bad_deduction:
10903 return DiagnoseBadDeduction(S, Cand, NumArgs,
10904 TakingCandidateAddress);
10905
10906 case ovl_fail_illegal_constructor: {
10907 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10908 << (Fn->getPrimaryTemplate() ? 1 : 0);
10909 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10910 return;
10911 }
10912
10913 case ovl_fail_object_addrspace_mismatch: {
10914 Qualifiers QualsForPrinting;
10915 QualsForPrinting.setAddressSpace(CtorDestAS);
10916 S.Diag(Fn->getLocation(),
10917 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10918 << QualsForPrinting;
10919 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10920 return;
10921 }
10922
10923 case ovl_fail_trivial_conversion:
10924 case ovl_fail_bad_final_conversion:
10925 case ovl_fail_final_conversion_not_exact:
10926 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10927
10928 case ovl_fail_bad_conversion: {
10929 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10930 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10931 if (Cand->Conversions[I].isBad())
10932 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10933
10934 // FIXME: this currently happens when we're called from SemaInit
10935 // when user-conversion overload fails. Figure out how to handle
10936 // those conditions and diagnose them well.
10937 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10938 }
10939
10940 case ovl_fail_bad_target:
10941 return DiagnoseBadTarget(S, Cand);
10942
10943 case ovl_fail_enable_if:
10944 return DiagnoseFailedEnableIfAttr(S, Cand);
10945
10946 case ovl_fail_explicit:
10947 return DiagnoseFailedExplicitSpec(S, Cand);
10948
10949 case ovl_fail_ext_disabled:
10950 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10951
10952 case ovl_fail_inhctor_slice:
10953 // It's generally not interesting to note copy/move constructors here.
10954 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10955 return;
10956 S.Diag(Fn->getLocation(),
10957 diag::note_ovl_candidate_inherited_constructor_slice)
10958 << (Fn->getPrimaryTemplate() ? 1 : 0)
10959 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10960 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10961 return;
10962
10963 case ovl_fail_addr_not_available: {
10964 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10965 (void)Available;
10966 assert(!Available)((!Available) ? static_cast<void> (0) : __assert_fail (
"!Available", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10966, __PRETTY_FUNCTION__))
;
10967 break;
10968 }
10969 case ovl_non_default_multiversion_function:
10970 // Do nothing, these should simply be ignored.
10971 break;
10972
10973 case ovl_fail_constraints_not_satisfied: {
10974 std::string FnDesc;
10975 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10976 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10977 Cand->getRewriteKind(), FnDesc);
10978
10979 S.Diag(Fn->getLocation(),
10980 diag::note_ovl_candidate_constraints_not_satisfied)
10981 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10982 << FnDesc /* Ignored */;
10983 ConstraintSatisfaction Satisfaction;
10984 if (S.CheckConstraintSatisfaction(Fn->getTrailingRequiresClause(),
10985 Satisfaction))
10986 break;
10987 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10988 }
10989 }
10990}
10991
10992static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10993 // Desugar the type of the surrogate down to a function type,
10994 // retaining as many typedefs as possible while still showing
10995 // the function type (and, therefore, its parameter types).
10996 QualType FnType = Cand->Surrogate->getConversionType();
10997 bool isLValueReference = false;
10998 bool isRValueReference = false;
10999 bool isPointer = false;
11000 if (const LValueReferenceType *FnTypeRef =
11001 FnType->getAs<LValueReferenceType>()) {
11002 FnType = FnTypeRef->getPointeeType();
11003 isLValueReference = true;
11004 } else if (const RValueReferenceType *FnTypeRef =
11005 FnType->getAs<RValueReferenceType>()) {
11006 FnType = FnTypeRef->getPointeeType();
11007 isRValueReference = true;
11008 }
11009 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11010 FnType = FnTypePtr->getPointeeType();
11011 isPointer = true;
11012 }
11013 // Desugar down to a function type.
11014 FnType = QualType(FnType->getAs<FunctionType>(), 0);
11015 // Reconstruct the pointer/reference as appropriate.
11016 if (isPointer) FnType = S.Context.getPointerType(FnType);
11017 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11018 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11019
11020 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11021 << FnType;
11022}
11023
11024static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11025 SourceLocation OpLoc,
11026 OverloadCandidate *Cand) {
11027 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")((Cand->Conversions.size() <= 2 && "builtin operator is not binary"
) ? static_cast<void> (0) : __assert_fail ("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11027, __PRETTY_FUNCTION__))
;
11028 std::string TypeStr("operator");
11029 TypeStr += Opc;
11030 TypeStr += "(";
11031 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11032 if (Cand->Conversions.size() == 1) {
11033 TypeStr += ")";
11034 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11035 } else {
11036 TypeStr += ", ";
11037 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11038 TypeStr += ")";
11039 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11040 }
11041}
11042
11043static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11044 OverloadCandidate *Cand) {
11045 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11046 if (ICS.isBad()) break; // all meaningless after first invalid
11047 if (!ICS.isAmbiguous()) continue;
11048
11049 ICS.DiagnoseAmbiguousConversion(
11050 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11051 }
11052}
11053
11054static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11055 if (Cand->Function)
11056 return Cand->Function->getLocation();
11057 if (Cand->IsSurrogate)
11058 return Cand->Surrogate->getLocation();
11059 return SourceLocation();
11060}
11061
11062static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11063 switch ((Sema::TemplateDeductionResult)DFI.Result) {
11064 case Sema::TDK_Success:
11065 case Sema::TDK_NonDependentConversionFailure:
11066 llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11066)
;
11067
11068 case Sema::TDK_Invalid:
11069 case Sema::TDK_Incomplete:
11070 case Sema::TDK_IncompletePack:
11071 return 1;
11072
11073 case Sema::TDK_Underqualified:
11074 case Sema::TDK_Inconsistent:
11075 return 2;
11076
11077 case Sema::TDK_SubstitutionFailure:
11078 case Sema::TDK_DeducedMismatch:
11079 case Sema::TDK_ConstraintsNotSatisfied:
11080 case Sema::TDK_DeducedMismatchNested:
11081 case Sema::TDK_NonDeducedMismatch:
11082 case Sema::TDK_MiscellaneousDeductionFailure:
11083 case Sema::TDK_CUDATargetMismatch:
11084 return 3;
11085
11086 case Sema::TDK_InstantiationDepth:
11087 return 4;
11088
11089 case Sema::TDK_InvalidExplicitArguments:
11090 return 5;
11091
11092 case Sema::TDK_TooManyArguments:
11093 case Sema::TDK_TooFewArguments:
11094 return 6;
11095 }
11096 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11096)
;
11097}
11098
11099namespace {
11100struct CompareOverloadCandidatesForDisplay {
11101 Sema &S;
11102 SourceLocation Loc;
11103 size_t NumArgs;
11104 OverloadCandidateSet::CandidateSetKind CSK;
11105
11106 CompareOverloadCandidatesForDisplay(
11107 Sema &S, SourceLocation Loc, size_t NArgs,
11108 OverloadCandidateSet::CandidateSetKind CSK)
11109 : S(S), NumArgs(NArgs), CSK(CSK) {}
11110
11111 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11112 // If there are too many or too few arguments, that's the high-order bit we
11113 // want to sort by, even if the immediate failure kind was something else.
11114 if (C->FailureKind == ovl_fail_too_many_arguments ||
11115 C->FailureKind == ovl_fail_too_few_arguments)
11116 return static_cast<OverloadFailureKind>(C->FailureKind);
11117
11118 if (C->Function) {
11119 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11120 return ovl_fail_too_many_arguments;
11121 if (NumArgs < C->Function->getMinRequiredArguments())
11122 return ovl_fail_too_few_arguments;
11123 }
11124
11125 return static_cast<OverloadFailureKind>(C->FailureKind);
11126 }
11127
11128 bool operator()(const OverloadCandidate *L,
11129 const OverloadCandidate *R) {
11130 // Fast-path this check.
11131 if (L == R) return false;
11132
11133 // Order first by viability.
11134 if (L->Viable) {
11135 if (!R->Viable) return true;
11136
11137 // TODO: introduce a tri-valued comparison for overload
11138 // candidates. Would be more worthwhile if we had a sort
11139 // that could exploit it.
11140 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11141 return true;
11142 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11143 return false;
11144 } else if (R->Viable)
11145 return false;
11146
11147 assert(L->Viable == R->Viable)((L->Viable == R->Viable) ? static_cast<void> (0)
: __assert_fail ("L->Viable == R->Viable", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11147, __PRETTY_FUNCTION__))
;
11148
11149 // Criteria by which we can sort non-viable candidates:
11150 if (!L->Viable) {
11151 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11152 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11153
11154 // 1. Arity mismatches come after other candidates.
11155 if (LFailureKind == ovl_fail_too_many_arguments ||
11156 LFailureKind == ovl_fail_too_few_arguments) {
11157 if (RFailureKind == ovl_fail_too_many_arguments ||
11158 RFailureKind == ovl_fail_too_few_arguments) {
11159 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11160 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11161 if (LDist == RDist) {
11162 if (LFailureKind == RFailureKind)
11163 // Sort non-surrogates before surrogates.
11164 return !L->IsSurrogate && R->IsSurrogate;
11165 // Sort candidates requiring fewer parameters than there were
11166 // arguments given after candidates requiring more parameters
11167 // than there were arguments given.
11168 return LFailureKind == ovl_fail_too_many_arguments;
11169 }
11170 return LDist < RDist;
11171 }
11172 return false;
11173 }
11174 if (RFailureKind == ovl_fail_too_many_arguments ||
11175 RFailureKind == ovl_fail_too_few_arguments)
11176 return true;
11177
11178 // 2. Bad conversions come first and are ordered by the number
11179 // of bad conversions and quality of good conversions.
11180 if (LFailureKind == ovl_fail_bad_conversion) {
11181 if (RFailureKind != ovl_fail_bad_conversion)
11182 return true;
11183
11184 // The conversion that can be fixed with a smaller number of changes,
11185 // comes first.
11186 unsigned numLFixes = L->Fix.NumConversionsFixed;
11187 unsigned numRFixes = R->Fix.NumConversionsFixed;
11188 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes;
11189 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes;
11190 if (numLFixes != numRFixes) {
11191 return numLFixes < numRFixes;
11192 }
11193
11194 // If there's any ordering between the defined conversions...
11195 // FIXME: this might not be transitive.
11196 assert(L->Conversions.size() == R->Conversions.size())((L->Conversions.size() == R->Conversions.size()) ? static_cast
<void> (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11196, __PRETTY_FUNCTION__))
;
11197
11198 int leftBetter = 0;
11199 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11200 for (unsigned E = L->Conversions.size(); I != E; ++I) {
11201 switch (CompareImplicitConversionSequences(S, Loc,
11202 L->Conversions[I],
11203 R->Conversions[I])) {
11204 case ImplicitConversionSequence::Better:
11205 leftBetter++;
11206 break;
11207
11208 case ImplicitConversionSequence::Worse:
11209 leftBetter--;
11210 break;
11211
11212 case ImplicitConversionSequence::Indistinguishable:
11213 break;
11214 }
11215 }
11216 if (leftBetter > 0) return true;
11217 if (leftBetter < 0) return false;
11218
11219 } else if (RFailureKind == ovl_fail_bad_conversion)
11220 return false;
11221
11222 if (LFailureKind == ovl_fail_bad_deduction) {
11223 if (RFailureKind != ovl_fail_bad_deduction)
11224 return true;
11225
11226 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11227 return RankDeductionFailure(L->DeductionFailure)
11228 < RankDeductionFailure(R->DeductionFailure);
11229 } else if (RFailureKind == ovl_fail_bad_deduction)
11230 return false;
11231
11232 // TODO: others?
11233 }
11234
11235 // Sort everything else by location.
11236 SourceLocation LLoc = GetLocationForCandidate(L);
11237 SourceLocation RLoc = GetLocationForCandidate(R);
11238
11239 // Put candidates without locations (e.g. builtins) at the end.
11240 if (LLoc.isInvalid()) return false;
11241 if (RLoc.isInvalid()) return true;
11242
11243 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11244 }
11245};
11246}
11247
11248/// CompleteNonViableCandidate - Normally, overload resolution only
11249/// computes up to the first bad conversion. Produces the FixIt set if
11250/// possible.
11251static void
11252CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11253 ArrayRef<Expr *> Args,
11254 OverloadCandidateSet::CandidateSetKind CSK) {
11255 assert(!Cand->Viable)((!Cand->Viable) ? static_cast<void> (0) : __assert_fail
("!Cand->Viable", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11255, __PRETTY_FUNCTION__))
;
11256
11257 // Don't do anything on failures other than bad conversion.
11258 if (Cand->FailureKind != ovl_fail_bad_conversion)
11259 return;
11260
11261 // We only want the FixIts if all the arguments can be corrected.
11262 bool Unfixable = false;
11263 // Use a implicit copy initialization to check conversion fixes.
11264 Cand->Fix.setConversionChecker(TryCopyInitialization);
11265
11266 // Attempt to fix the bad conversion.
11267 unsigned ConvCount = Cand->Conversions.size();
11268 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11269 ++ConvIdx) {
11270 assert(ConvIdx != ConvCount && "no bad conversion in candidate")((ConvIdx != ConvCount && "no bad conversion in candidate"
) ? static_cast<void> (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11270, __PRETTY_FUNCTION__))
;
11271 if (Cand->Conversions[ConvIdx].isInitialized() &&
11272 Cand->Conversions[ConvIdx].isBad()) {
11273 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11274 break;
11275 }
11276 }
11277
11278 // FIXME: this should probably be preserved from the overload
11279 // operation somehow.
11280 bool SuppressUserConversions = false;
11281
11282 unsigned ConvIdx = 0;
11283 unsigned ArgIdx = 0;
11284 ArrayRef<QualType> ParamTypes;
11285 bool Reversed = Cand->RewriteKind & CRK_Reversed;
11286
11287 if (Cand->IsSurrogate) {
11288 QualType ConvType
11289 = Cand->Surrogate->getConversionType().getNonReferenceType();
11290 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11291 ConvType = ConvPtrType->getPointeeType();
11292 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11293 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11294 ConvIdx = 1;
11295 } else if (Cand->Function) {
11296 ParamTypes =
11297 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11298 if (isa<CXXMethodDecl>(Cand->Function) &&
11299 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11300 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11301 ConvIdx = 1;
11302 if (CSK == OverloadCandidateSet::CSK_Operator &&
11303 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11304 // Argument 0 is 'this', which doesn't have a corresponding parameter.
11305 ArgIdx = 1;
11306 }
11307 } else {
11308 // Builtin operator.
11309 assert(ConvCount <= 3)((ConvCount <= 3) ? static_cast<void> (0) : __assert_fail
("ConvCount <= 3", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11309, __PRETTY_FUNCTION__))
;
11310 ParamTypes = Cand->BuiltinParamTypes;
11311 }
11312
11313 // Fill in the rest of the conversions.
11314 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11315 ConvIdx != ConvCount;
11316 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11317 assert(ArgIdx < Args.size() && "no argument for this arg conversion")((ArgIdx < Args.size() && "no argument for this arg conversion"
) ? static_cast<void> (0) : __assert_fail ("ArgIdx < Args.size() && \"no argument for this arg conversion\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11317, __PRETTY_FUNCTION__))
;
11318 if (Cand->Conversions[ConvIdx].isInitialized()) {
11319 // We've already checked this conversion.
11320 } else if (ParamIdx < ParamTypes.size()) {
11321 if (ParamTypes[ParamIdx]->isDependentType())
11322 Cand->Conversions[ConvIdx].setAsIdentityConversion(
11323 Args[ArgIdx]->getType());
11324 else {
11325 Cand->Conversions[ConvIdx] =
11326 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11327 SuppressUserConversions,
11328 /*InOverloadResolution=*/true,
11329 /*AllowObjCWritebackConversion=*/
11330 S.getLangOpts().ObjCAutoRefCount);
11331 // Store the FixIt in the candidate if it exists.
11332 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11333 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11334 }
11335 } else
11336 Cand->Conversions[ConvIdx].setEllipsis();
11337 }
11338}
11339
11340SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11341 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11342 SourceLocation OpLoc,
11343 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11344 // Sort the candidates by viability and position. Sorting directly would
11345 // be prohibitive, so we make a set of pointers and sort those.
11346 SmallVector<OverloadCandidate*, 32> Cands;
11347 if (OCD == OCD_AllCandidates) Cands.reserve(size());
11348 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11349 if (!Filter(*Cand))
11350 continue;
11351 switch (OCD) {
11352 case OCD_AllCandidates:
11353 if (!Cand->Viable) {
11354 if (!Cand->Function && !Cand->IsSurrogate) {
11355 // This a non-viable builtin candidate. We do not, in general,
11356 // want to list every possible builtin candidate.
11357 continue;
11358 }
11359 CompleteNonViableCandidate(S, Cand, Args, Kind);
11360 }
11361 break;
11362
11363 case OCD_ViableCandidates:
11364 if (!Cand->Viable)
11365 continue;
11366 break;
11367
11368 case OCD_AmbiguousCandidates:
11369 if (!Cand->Best)
11370 continue;
11371 break;
11372 }
11373
11374 Cands.push_back(Cand);
11375 }
11376
11377 llvm::stable_sort(
11378 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11379
11380 return Cands;
11381}
11382
11383/// When overload resolution fails, prints diagnostic messages containing the
11384/// candidates in the candidate set.
11385void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11386 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11387 StringRef Opc, SourceLocation OpLoc,
11388 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11389
11390 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11391
11392 S.Diag(PD.first, PD.second);
11393
11394 NoteCandidates(S, Args, Cands, Opc, OpLoc);
11395
11396 if (OCD == OCD_AmbiguousCandidates)
11397 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11398}
11399
11400void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11401 ArrayRef<OverloadCandidate *> Cands,
11402 StringRef Opc, SourceLocation OpLoc) {
11403 bool ReportedAmbiguousConversions = false;
11404
11405 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11406 unsigned CandsShown = 0;
11407 auto I = Cands.begin(), E = Cands.end();
11408 for (; I != E; ++I) {
11409 OverloadCandidate *Cand = *I;
11410
11411 // Set an arbitrary limit on the number of candidate functions we'll spam
11412 // the user with. FIXME: This limit should depend on details of the
11413 // candidate list.
11414 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11415 break;
11416 }
11417 ++CandsShown;
11418
11419 if (Cand->Function)
11420 NoteFunctionCandidate(S, Cand, Args.size(),
11421 /*TakingCandidateAddress=*/false, DestAS);
11422 else if (Cand->IsSurrogate)
11423 NoteSurrogateCandidate(S, Cand);
11424 else {
11425 assert(Cand->Viable &&((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11426, __PRETTY_FUNCTION__))
11426 "Non-viable built-in candidates are not added to Cands.")((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11426, __PRETTY_FUNCTION__))
;
11427 // Generally we only see ambiguities including viable builtin
11428 // operators if overload resolution got screwed up by an
11429 // ambiguous user-defined conversion.
11430 //
11431 // FIXME: It's quite possible for different conversions to see
11432 // different ambiguities, though.
11433 if (!ReportedAmbiguousConversions) {
11434 NoteAmbiguousUserConversions(S, OpLoc, Cand);
11435 ReportedAmbiguousConversions = true;
11436 }
11437
11438 // If this is a viable builtin, print it.
11439 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11440 }
11441 }
11442
11443 if (I != E)
11444 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11445}
11446
11447static SourceLocation
11448GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11449 return Cand->Specialization ? Cand->Specialization->getLocation()
11450 : SourceLocation();
11451}
11452
11453namespace {
11454struct CompareTemplateSpecCandidatesForDisplay {
11455 Sema &S;
11456 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11457
11458 bool operator()(const TemplateSpecCandidate *L,
11459 const TemplateSpecCandidate *R) {
11460 // Fast-path this check.
11461 if (L == R)
11462 return false;
11463
11464 // Assuming that both candidates are not matches...
11465
11466 // Sort by the ranking of deduction failures.
11467 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11468 return RankDeductionFailure(L->DeductionFailure) <
11469 RankDeductionFailure(R->DeductionFailure);
11470
11471 // Sort everything else by location.
11472 SourceLocation LLoc = GetLocationForCandidate(L);
11473 SourceLocation RLoc = GetLocationForCandidate(R);
11474
11475 // Put candidates without locations (e.g. builtins) at the end.
11476 if (LLoc.isInvalid())
11477 return false;
11478 if (RLoc.isInvalid())
11479 return true;
11480
11481 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11482 }
11483};
11484}
11485
11486/// Diagnose a template argument deduction failure.
11487/// We are treating these failures as overload failures due to bad
11488/// deductions.
11489void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11490 bool ForTakingAddress) {
11491 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11492 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11493}
11494
11495void TemplateSpecCandidateSet::destroyCandidates() {
11496 for (iterator i = begin(), e = end(); i != e; ++i) {
11497 i->DeductionFailure.Destroy();
11498 }
11499}
11500
11501void TemplateSpecCandidateSet::clear() {
11502 destroyCandidates();
11503 Candidates.clear();
11504}
11505
11506/// NoteCandidates - When no template specialization match is found, prints
11507/// diagnostic messages containing the non-matching specializations that form
11508/// the candidate set.
11509/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11510/// OCD == OCD_AllCandidates and Cand->Viable == false.
11511void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11512 // Sort the candidates by position (assuming no candidate is a match).
11513 // Sorting directly would be prohibitive, so we make a set of pointers
11514 // and sort those.
11515 SmallVector<TemplateSpecCandidate *, 32> Cands;
11516 Cands.reserve(size());
11517 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11518 if (Cand->Specialization)
11519 Cands.push_back(Cand);
11520 // Otherwise, this is a non-matching builtin candidate. We do not,
11521 // in general, want to list every possible builtin candidate.
11522 }
11523
11524 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11525
11526 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11527 // for generalization purposes (?).
11528 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11529
11530 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11531 unsigned CandsShown = 0;
11532 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11533 TemplateSpecCandidate *Cand = *I;
11534
11535 // Set an arbitrary limit on the number of candidates we'll spam
11536 // the user with. FIXME: This limit should depend on details of the
11537 // candidate list.
11538 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11539 break;
11540 ++CandsShown;
11541
11542 assert(Cand->Specialization &&((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11543, __PRETTY_FUNCTION__))
11543 "Non-matching built-in candidates are not added to Cands.")((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11543, __PRETTY_FUNCTION__))
;
11544 Cand->NoteDeductionFailure(S, ForTakingAddress);
11545 }
11546
11547 if (I != E)
11548 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11549}
11550
11551// [PossiblyAFunctionType] --> [Return]
11552// NonFunctionType --> NonFunctionType
11553// R (A) --> R(A)
11554// R (*)(A) --> R (A)
11555// R (&)(A) --> R (A)
11556// R (S::*)(A) --> R (A)
11557QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11558 QualType Ret = PossiblyAFunctionType;
11559 if (const PointerType *ToTypePtr =
11560 PossiblyAFunctionType->getAs<PointerType>())
11561 Ret = ToTypePtr->getPointeeType();
11562 else if (const ReferenceType *ToTypeRef =
11563 PossiblyAFunctionType->getAs<ReferenceType>())
11564 Ret = ToTypeRef->getPointeeType();
11565 else if (const MemberPointerType *MemTypePtr =
11566 PossiblyAFunctionType->getAs<MemberPointerType>())
11567 Ret = MemTypePtr->getPointeeType();
11568 Ret =
11569 Context.getCanonicalType(Ret).getUnqualifiedType();
11570 return Ret;
11571}
11572
11573static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11574 bool Complain = true) {
11575 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11576 S.DeduceReturnType(FD, Loc, Complain))
11577 return true;
11578
11579 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11580 if (S.getLangOpts().CPlusPlus17 &&
11581 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11582 !S.ResolveExceptionSpec(Loc, FPT))
11583 return true;
11584
11585 return false;
11586}
11587
11588namespace {
11589// A helper class to help with address of function resolution
11590// - allows us to avoid passing around all those ugly parameters
11591class AddressOfFunctionResolver {
11592 Sema& S;
11593 Expr* SourceExpr;
11594 const QualType& TargetType;
11595 QualType TargetFunctionType; // Extracted function type from target type
11596
11597 bool Complain;
11598 //DeclAccessPair& ResultFunctionAccessPair;
11599 ASTContext& Context;
11600
11601 bool TargetTypeIsNonStaticMemberFunction;
11602 bool FoundNonTemplateFunction;
11603 bool StaticMemberFunctionFromBoundPointer;
11604 bool HasComplained;
11605
11606 OverloadExpr::FindResult OvlExprInfo;
11607 OverloadExpr *OvlExpr;
11608 TemplateArgumentListInfo OvlExplicitTemplateArgs;
11609 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11610 TemplateSpecCandidateSet FailedCandidates;
11611
11612public:
11613 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11614 const QualType &TargetType, bool Complain)
11615 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11616 Complain(Complain), Context(S.getASTContext()),
11617 TargetTypeIsNonStaticMemberFunction(
11618 !!TargetType->getAs<MemberPointerType>()),
11619 FoundNonTemplateFunction(false),
11620 StaticMemberFunctionFromBoundPointer(false),
11621 HasComplained(false),
11622 OvlExprInfo(OverloadExpr::find(SourceExpr)),
11623 OvlExpr(OvlExprInfo.Expression),
11624 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11625 ExtractUnqualifiedFunctionTypeFromTargetType();
11626
11627 if (TargetFunctionType->isFunctionType()) {
11628 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11629 if (!UME->isImplicitAccess() &&
11630 !S.ResolveSingleFunctionTemplateSpecialization(UME))
11631 StaticMemberFunctionFromBoundPointer = true;
11632 } else if (OvlExpr->hasExplicitTemplateArgs()) {
11633 DeclAccessPair dap;
11634 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11635 OvlExpr, false, &dap)) {
11636 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11637 if (!Method->isStatic()) {
11638 // If the target type is a non-function type and the function found
11639 // is a non-static member function, pretend as if that was the
11640 // target, it's the only possible type to end up with.
11641 TargetTypeIsNonStaticMemberFunction = true;
11642
11643 // And skip adding the function if its not in the proper form.
11644 // We'll diagnose this due to an empty set of functions.
11645 if (!OvlExprInfo.HasFormOfMemberPointer)
11646 return;
11647 }
11648
11649 Matches.push_back(std::make_pair(dap, Fn));
11650 }
11651 return;
11652 }
11653
11654 if (OvlExpr->hasExplicitTemplateArgs())
11655 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11656
11657 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11658 // C++ [over.over]p4:
11659 // If more than one function is selected, [...]
11660 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11661 if (FoundNonTemplateFunction)
11662 EliminateAllTemplateMatches();
11663 else
11664 EliminateAllExceptMostSpecializedTemplate();
11665 }
11666 }
11667
11668 if (S.getLangOpts().CUDA && Matches.size() > 1)
11669 EliminateSuboptimalCudaMatches();
11670 }
11671
11672 bool hasComplained() const { return HasComplained; }
11673
11674private:
11675 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11676 QualType Discard;
11677 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11678 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11679 }
11680
11681 /// \return true if A is considered a better overload candidate for the
11682 /// desired type than B.
11683 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11684 // If A doesn't have exactly the correct type, we don't want to classify it
11685 // as "better" than anything else. This way, the user is required to
11686 // disambiguate for us if there are multiple candidates and no exact match.
11687 return candidateHasExactlyCorrectType(A) &&
11688 (!candidateHasExactlyCorrectType(B) ||
11689 compareEnableIfAttrs(S, A, B) == Comparison::Better);
11690 }
11691
11692 /// \return true if we were able to eliminate all but one overload candidate,
11693 /// false otherwise.
11694 bool eliminiateSuboptimalOverloadCandidates() {
11695 // Same algorithm as overload resolution -- one pass to pick the "best",
11696 // another pass to be sure that nothing is better than the best.
11697 auto Best = Matches.begin();
11698 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11699 if (isBetterCandidate(I->second, Best->second))
11700 Best = I;
11701
11702 const FunctionDecl *BestFn = Best->second;
11703 auto IsBestOrInferiorToBest = [this, BestFn](
11704 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11705 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11706 };
11707
11708 // Note: We explicitly leave Matches unmodified if there isn't a clear best
11709 // option, so we can potentially give the user a better error
11710 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11711 return false;
11712 Matches[0] = *Best;
11713 Matches.resize(1);
11714 return true;
11715 }
11716
11717 bool isTargetTypeAFunction() const {
11718 return TargetFunctionType->isFunctionType();
11719 }
11720
11721 // [ToType] [Return]
11722
11723 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11724 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11725 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11726 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11727 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11728 }
11729
11730 // return true if any matching specializations were found
11731 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11732 const DeclAccessPair& CurAccessFunPair) {
11733 if (CXXMethodDecl *Method
11734 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11735 // Skip non-static function templates when converting to pointer, and
11736 // static when converting to member pointer.
11737 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11738 return false;
11739 }
11740 else if (TargetTypeIsNonStaticMemberFunction)
11741 return false;
11742
11743 // C++ [over.over]p2:
11744 // If the name is a function template, template argument deduction is
11745 // done (14.8.2.2), and if the argument deduction succeeds, the
11746 // resulting template argument list is used to generate a single
11747 // function template specialization, which is added to the set of
11748 // overloaded functions considered.
11749 FunctionDecl *Specialization = nullptr;
11750 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11751 if (Sema::TemplateDeductionResult Result
11752 = S.DeduceTemplateArguments(FunctionTemplate,
11753 &OvlExplicitTemplateArgs,
11754 TargetFunctionType, Specialization,
11755 Info, /*IsAddressOfFunction*/true)) {
11756 // Make a note of the failed deduction for diagnostics.
11757 FailedCandidates.addCandidate()
11758 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11759 MakeDeductionFailureInfo(Context, Result, Info));
11760 return false;
11761 }
11762
11763 // Template argument deduction ensures that we have an exact match or
11764 // compatible pointer-to-function arguments that would be adjusted by ICS.
11765 // This function template specicalization works.
11766 assert(S.isSameOrCompatibleFunctionType(((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11768, __PRETTY_FUNCTION__))
11767 Context.getCanonicalType(Specialization->getType()),((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11768, __PRETTY_FUNCTION__))
11768 Context.getCanonicalType(TargetFunctionType)))((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11768, __PRETTY_FUNCTION__))
;
11769
11770 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11771 return false;
11772
11773 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11774 return true;
11775 }
11776
11777 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11778 const DeclAccessPair& CurAccessFunPair) {
11779 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11780 // Skip non-static functions when converting to pointer, and static
11781 // when converting to member pointer.
11782 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11783 return false;
11784 }
11785 else if (TargetTypeIsNonStaticMemberFunction)
11786 return false;
11787
11788 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11789 if (S.getLangOpts().CUDA)
11790 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11791 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11792 return false;
11793 if (FunDecl->isMultiVersion()) {
11794 const auto *TA = FunDecl->getAttr<TargetAttr>();
11795 if (TA && !TA->isDefaultVersion())
11796 return false;
11797 }
11798
11799 // If any candidate has a placeholder return type, trigger its deduction
11800 // now.
11801 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11802 Complain)) {
11803 HasComplained |= Complain;
11804 return false;
11805 }
11806
11807 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11808 return false;
11809
11810 // If we're in C, we need to support types that aren't exactly identical.
11811 if (!S.getLangOpts().CPlusPlus ||
11812 candidateHasExactlyCorrectType(FunDecl)) {
11813 Matches.push_back(std::make_pair(
11814 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11815 FoundNonTemplateFunction = true;
11816 return true;
11817 }
11818 }
11819
11820 return false;
11821 }
11822
11823 bool FindAllFunctionsThatMatchTargetTypeExactly() {
11824 bool Ret = false;
11825
11826 // If the overload expression doesn't have the form of a pointer to
11827 // member, don't try to convert it to a pointer-to-member type.
11828 if (IsInvalidFormOfPointerToMemberFunction())
11829 return false;
11830
11831 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11832 E = OvlExpr->decls_end();
11833 I != E; ++I) {
11834 // Look through any using declarations to find the underlying function.
11835 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11836
11837 // C++ [over.over]p3:
11838 // Non-member functions and static member functions match
11839 // targets of type "pointer-to-function" or "reference-to-function."
11840 // Nonstatic member functions match targets of
11841 // type "pointer-to-member-function."
11842 // Note that according to DR 247, the containing class does not matter.
11843 if (FunctionTemplateDecl *FunctionTemplate
11844 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11845 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11846 Ret = true;
11847 }
11848 // If we have explicit template arguments supplied, skip non-templates.
11849 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11850 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11851 Ret = true;
11852 }
11853 assert(Ret || Matches.empty())((Ret || Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Ret || Matches.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11853, __PRETTY_FUNCTION__))
;
11854 return Ret;
11855 }
11856
11857 void EliminateAllExceptMostSpecializedTemplate() {
11858 // [...] and any given function template specialization F1 is
11859 // eliminated if the set contains a second function template
11860 // specialization whose function template is more specialized
11861 // than the function template of F1 according to the partial
11862 // ordering rules of 14.5.5.2.
11863
11864 // The algorithm specified above is quadratic. We instead use a
11865 // two-pass algorithm (similar to the one used to identify the
11866 // best viable function in an overload set) that identifies the
11867 // best function template (if it exists).
11868
11869 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11870 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11871 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11872
11873 // TODO: It looks like FailedCandidates does not serve much purpose
11874 // here, since the no_viable diagnostic has index 0.
11875 UnresolvedSetIterator Result = S.getMostSpecialized(
11876 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11877 SourceExpr->getBeginLoc(), S.PDiag(),
11878 S.PDiag(diag::err_addr_ovl_ambiguous)
11879 << Matches[0].second->getDeclName(),
11880 S.PDiag(diag::note_ovl_candidate)
11881 << (unsigned)oc_function << (unsigned)ocs_described_template,
11882 Complain, TargetFunctionType);
11883
11884 if (Result != MatchesCopy.end()) {
11885 // Make it the first and only element
11886 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11887 Matches[0].second = cast<FunctionDecl>(*Result);
11888 Matches.resize(1);
11889 } else
11890 HasComplained |= Complain;
11891 }
11892
11893 void EliminateAllTemplateMatches() {
11894 // [...] any function template specializations in the set are
11895 // eliminated if the set also contains a non-template function, [...]
11896 for (unsigned I = 0, N = Matches.size(); I != N; ) {
11897 if (Matches[I].second->getPrimaryTemplate() == nullptr)
11898 ++I;
11899 else {
11900 Matches[I] = Matches[--N];
11901 Matches.resize(N);
11902 }
11903 }
11904 }
11905
11906 void EliminateSuboptimalCudaMatches() {
11907 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11908 }
11909
11910public:
11911 void ComplainNoMatchesFound() const {
11912 assert(Matches.empty())((Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Matches.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11912, __PRETTY_FUNCTION__))
;
11913 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11914 << OvlExpr->getName() << TargetFunctionType
11915 << OvlExpr->getSourceRange();
11916 if (FailedCandidates.empty())
11917 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11918 /*TakingAddress=*/true);
11919 else {
11920 // We have some deduction failure messages. Use them to diagnose
11921 // the function templates, and diagnose the non-template candidates
11922 // normally.
11923 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11924 IEnd = OvlExpr->decls_end();
11925 I != IEnd; ++I)
11926 if (FunctionDecl *Fun =
11927 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11928 if (!functionHasPassObjectSizeParams(Fun))
11929 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11930 /*TakingAddress=*/true);
11931 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11932 }
11933 }
11934
11935 bool IsInvalidFormOfPointerToMemberFunction() const {
11936 return TargetTypeIsNonStaticMemberFunction &&
11937 !OvlExprInfo.HasFormOfMemberPointer;
11938 }
11939
11940 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11941 // TODO: Should we condition this on whether any functions might
11942 // have matched, or is it more appropriate to do that in callers?
11943 // TODO: a fixit wouldn't hurt.
11944 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11945 << TargetType << OvlExpr->getSourceRange();
11946 }
11947
11948 bool IsStaticMemberFunctionFromBoundPointer() const {
11949 return StaticMemberFunctionFromBoundPointer;
11950 }
11951
11952 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11953 S.Diag(OvlExpr->getBeginLoc(),
11954 diag::err_invalid_form_pointer_member_function)
11955 << OvlExpr->getSourceRange();
11956 }
11957
11958 void ComplainOfInvalidConversion() const {
11959 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11960 << OvlExpr->getName() << TargetType;
11961 }
11962
11963 void ComplainMultipleMatchesFound() const {
11964 assert(Matches.size() > 1)((Matches.size() > 1) ? static_cast<void> (0) : __assert_fail
("Matches.size() > 1", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11964, __PRETTY_FUNCTION__))
;
11965 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11966 << OvlExpr->getName() << OvlExpr->getSourceRange();
11967 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11968 /*TakingAddress=*/true);
11969 }
11970
11971 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11972
11973 int getNumMatches() const { return Matches.size(); }
11974
11975 FunctionDecl* getMatchingFunctionDecl() const {
11976 if (Matches.size() != 1) return nullptr;
11977 return Matches[0].second;
11978 }
11979
11980 const DeclAccessPair* getMatchingFunctionAccessPair() const {
11981 if (Matches.size() != 1) return nullptr;
11982 return &Matches[0].first;
11983 }
11984};
11985}
11986
11987/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11988/// an overloaded function (C++ [over.over]), where @p From is an
11989/// expression with overloaded function type and @p ToType is the type
11990/// we're trying to resolve to. For example:
11991///
11992/// @code
11993/// int f(double);
11994/// int f(int);
11995///
11996/// int (*pfd)(double) = f; // selects f(double)
11997/// @endcode
11998///
11999/// This routine returns the resulting FunctionDecl if it could be
12000/// resolved, and NULL otherwise. When @p Complain is true, this
12001/// routine will emit diagnostics if there is an error.
12002FunctionDecl *
12003Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12004 QualType TargetType,
12005 bool Complain,
12006 DeclAccessPair &FoundResult,
12007 bool *pHadMultipleCandidates) {
12008 assert(AddressOfExpr->getType() == Context.OverloadTy)((AddressOfExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12008, __PRETTY_FUNCTION__))
;
12009
12010 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12011 Complain);
12012 int NumMatches = Resolver.getNumMatches();
12013 FunctionDecl *Fn = nullptr;
12014 bool ShouldComplain = Complain && !Resolver.hasComplained();
12015 if (NumMatches == 0 && ShouldComplain) {
12016 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12017 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12018 else
12019 Resolver.ComplainNoMatchesFound();
12020 }
12021 else if (NumMatches > 1 && ShouldComplain)
12022 Resolver.ComplainMultipleMatchesFound();
12023 else if (NumMatches == 1) {
12024 Fn = Resolver.getMatchingFunctionDecl();
12025 assert(Fn)((Fn) ? static_cast<void> (0) : __assert_fail ("Fn", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12025, __PRETTY_FUNCTION__))
;
12026 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12027 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12028 FoundResult = *Resolver.getMatchingFunctionAccessPair();
12029 if (Complain) {
12030 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12031 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12032 else
12033 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12034 }
12035 }
12036
12037 if (pHadMultipleCandidates)
12038 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12039 return Fn;
12040}
12041
12042/// Given an expression that refers to an overloaded function, try to
12043/// resolve that function to a single function that can have its address taken.
12044/// This will modify `Pair` iff it returns non-null.
12045///
12046/// This routine can only succeed if from all of the candidates in the overload
12047/// set for SrcExpr that can have their addresses taken, there is one candidate
12048/// that is more constrained than the rest.
12049FunctionDecl *
12050Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12051 OverloadExpr::FindResult R = OverloadExpr::find(E);
12052 OverloadExpr *Ovl = R.Expression;
12053 bool IsResultAmbiguous = false;
12054 FunctionDecl *Result = nullptr;
12055 DeclAccessPair DAP;
12056 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12057
12058 auto CheckMoreConstrained =
12059 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12060 SmallVector<const Expr *, 1> AC1, AC2;
12061 FD1->getAssociatedConstraints(AC1);
12062 FD2->getAssociatedConstraints(AC2);
12063 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12064 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12065 return None;
12066 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12067 return None;
12068 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12069 return None;
12070 return AtLeastAsConstrained1;
12071 };
12072
12073 // Don't use the AddressOfResolver because we're specifically looking for
12074 // cases where we have one overload candidate that lacks
12075 // enable_if/pass_object_size/...
12076 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12077 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12078 if (!FD)
12079 return nullptr;
12080
12081 if (!checkAddressOfFunctionIsAvailable(FD))
12082 continue;
12083
12084 // We have more than one result - see if it is more constrained than the
12085 // previous one.
12086 if (Result) {
12087 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12088 Result);
12089 if (!MoreConstrainedThanPrevious) {
12090 IsResultAmbiguous = true;
12091 AmbiguousDecls.push_back(FD);
12092 continue;
12093 }
12094 if (!*MoreConstrainedThanPrevious)
12095 continue;
12096 // FD is more constrained - replace Result with it.
12097 }
12098 IsResultAmbiguous = false;
12099 DAP = I.getPair();
12100 Result = FD;
12101 }
12102
12103 if (IsResultAmbiguous)
12104 return nullptr;
12105
12106 if (Result) {
12107 SmallVector<const Expr *, 1> ResultAC;
12108 // We skipped over some ambiguous declarations which might be ambiguous with
12109 // the selected result.
12110 for (FunctionDecl *Skipped : AmbiguousDecls)
12111 if (!CheckMoreConstrained(Skipped, Result).hasValue())
12112 return nullptr;
12113 Pair = DAP;
12114 }
12115 return Result;
12116}
12117
12118/// Given an overloaded function, tries to turn it into a non-overloaded
12119/// function reference using resolveAddressOfSingleOverloadCandidate. This
12120/// will perform access checks, diagnose the use of the resultant decl, and, if
12121/// requested, potentially perform a function-to-pointer decay.
12122///
12123/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12124/// Otherwise, returns true. This may emit diagnostics and return true.
12125bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12126 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12127 Expr *E = SrcExpr.get();
12128 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")((E->getType() == Context.OverloadTy && "SrcExpr must be an overload"
) ? static_cast<void> (0) : __assert_fail ("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12128, __PRETTY_FUNCTION__))
;
12129
12130 DeclAccessPair DAP;
12131 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12132 if (!Found || Found->isCPUDispatchMultiVersion() ||
12133 Found->isCPUSpecificMultiVersion())
12134 return false;
12135
12136 // Emitting multiple diagnostics for a function that is both inaccessible and
12137 // unavailable is consistent with our behavior elsewhere. So, always check
12138 // for both.
12139 DiagnoseUseOfDecl(Found, E->getExprLoc());
12140 CheckAddressOfMemberAccess(E, DAP);
12141 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12142 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12143 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12144 else
12145 SrcExpr = Fixed;
12146 return true;
12147}
12148
12149/// Given an expression that refers to an overloaded function, try to
12150/// resolve that overloaded function expression down to a single function.
12151///
12152/// This routine can only resolve template-ids that refer to a single function
12153/// template, where that template-id refers to a single template whose template
12154/// arguments are either provided by the template-id or have defaults,
12155/// as described in C++0x [temp.arg.explicit]p3.
12156///
12157/// If no template-ids are found, no diagnostics are emitted and NULL is
12158/// returned.
12159FunctionDecl *
12160Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12161 bool Complain,
12162 DeclAccessPair *FoundResult) {
12163 // C++ [over.over]p1:
12164 // [...] [Note: any redundant set of parentheses surrounding the
12165 // overloaded function name is ignored (5.1). ]
12166 // C++ [over.over]p1:
12167 // [...] The overloaded function name can be preceded by the &
12168 // operator.
12169
12170 // If we didn't actually find any template-ids, we're done.
12171 if (!ovl->hasExplicitTemplateArgs())
12172 return nullptr;
12173
12174 TemplateArgumentListInfo ExplicitTemplateArgs;
12175 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12176 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12177
12178 // Look through all of the overloaded functions, searching for one
12179 // whose type matches exactly.
12180 FunctionDecl *Matched = nullptr;
12181 for (UnresolvedSetIterator I = ovl->decls_begin(),
12182 E = ovl->decls_end(); I != E; ++I) {
12183 // C++0x [temp.arg.explicit]p3:
12184 // [...] In contexts where deduction is done and fails, or in contexts
12185 // where deduction is not done, if a template argument list is
12186 // specified and it, along with any default template arguments,
12187 // identifies a single function template specialization, then the
12188 // template-id is an lvalue for the function template specialization.
12189 FunctionTemplateDecl *FunctionTemplate
12190 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12191
12192 // C++ [over.over]p2:
12193 // If the name is a function template, template argument deduction is
12194 // done (14.8.2.2), and if the argument deduction succeeds, the
12195 // resulting template argument list is used to generate a single
12196 // function template specialization, which is added to the set of
12197 // overloaded functions considered.
12198 FunctionDecl *Specialization = nullptr;
12199 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12200 if (TemplateDeductionResult Result
12201 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12202 Specialization, Info,
12203 /*IsAddressOfFunction*/true)) {
12204 // Make a note of the failed deduction for diagnostics.
12205 // TODO: Actually use the failed-deduction info?
12206 FailedCandidates.addCandidate()
12207 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12208 MakeDeductionFailureInfo(Context, Result, Info));
12209 continue;
12210 }
12211
12212 assert(Specialization && "no specialization and no error?")((Specialization && "no specialization and no error?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"no specialization and no error?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12212, __PRETTY_FUNCTION__))
;
12213
12214 // Multiple matches; we can't resolve to a single declaration.
12215 if (Matched) {
12216 if (Complain) {
12217 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12218 << ovl->getName();
12219 NoteAllOverloadCandidates(ovl);
12220 }
12221 return nullptr;
12222 }
12223
12224 Matched = Specialization;
12225 if (FoundResult) *FoundResult = I.getPair();
12226 }
12227
12228 if (Matched &&
12229 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12230 return nullptr;
12231
12232 return Matched;
12233}
12234
12235// Resolve and fix an overloaded expression that can be resolved
12236// because it identifies a single function template specialization.
12237//
12238// Last three arguments should only be supplied if Complain = true
12239//
12240// Return true if it was logically possible to so resolve the
12241// expression, regardless of whether or not it succeeded. Always
12242// returns true if 'complain' is set.
12243bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12244 ExprResult &SrcExpr, bool doFunctionPointerConverion,
12245 bool complain, SourceRange OpRangeForComplaining,
12246 QualType DestTypeForComplaining,
12247 unsigned DiagIDForComplaining) {
12248 assert(SrcExpr.get()->getType() == Context.OverloadTy)((SrcExpr.get()->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12248, __PRETTY_FUNCTION__))
;
12249
12250 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12251
12252 DeclAccessPair found;
12253 ExprResult SingleFunctionExpression;
12254 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12255 ovl.Expression, /*complain*/ false, &found)) {
12256 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12257 SrcExpr = ExprError();
12258 return true;
12259 }
12260
12261 // It is only correct to resolve to an instance method if we're
12262 // resolving a form that's permitted to be a pointer to member.
12263 // Otherwise we'll end up making a bound member expression, which
12264 // is illegal in all the contexts we resolve like this.
12265 if (!ovl.HasFormOfMemberPointer &&
12266 isa<CXXMethodDecl>(fn) &&
12267 cast<CXXMethodDecl>(fn)->isInstance()) {
12268 if (!complain) return false;
12269
12270 Diag(ovl.Expression->getExprLoc(),
12271 diag::err_bound_member_function)
12272 << 0 << ovl.Expression->getSourceRange();
12273
12274 // TODO: I believe we only end up here if there's a mix of
12275 // static and non-static candidates (otherwise the expression
12276 // would have 'bound member' type, not 'overload' type).
12277 // Ideally we would note which candidate was chosen and why
12278 // the static candidates were rejected.
12279 SrcExpr = ExprError();
12280 return true;
12281 }
12282
12283 // Fix the expression to refer to 'fn'.
12284 SingleFunctionExpression =
12285 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12286
12287 // If desired, do function-to-pointer decay.
12288 if (doFunctionPointerConverion) {
12289 SingleFunctionExpression =
12290 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12291 if (SingleFunctionExpression.isInvalid()) {
12292 SrcExpr = ExprError();
12293 return true;
12294 }
12295 }
12296 }
12297
12298 if (!SingleFunctionExpression.isUsable()) {
12299 if (complain) {
12300 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12301 << ovl.Expression->getName()
12302 << DestTypeForComplaining
12303 << OpRangeForComplaining
12304 << ovl.Expression->getQualifierLoc().getSourceRange();
12305 NoteAllOverloadCandidates(SrcExpr.get());
12306
12307 SrcExpr = ExprError();
12308 return true;
12309 }
12310
12311 return false;
12312 }
12313
12314 SrcExpr = SingleFunctionExpression;
12315 return true;
12316}
12317
12318/// Add a single candidate to the overload set.
12319static void AddOverloadedCallCandidate(Sema &S,
12320 DeclAccessPair FoundDecl,
12321 TemplateArgumentListInfo *ExplicitTemplateArgs,
12322 ArrayRef<Expr *> Args,
12323 OverloadCandidateSet &CandidateSet,
12324 bool PartialOverloading,
12325 bool KnownValid) {
12326 NamedDecl *Callee = FoundDecl.getDecl();
12327 if (isa<UsingShadowDecl>(Callee))
12328 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12329
12330 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12331 if (ExplicitTemplateArgs) {
12332 assert(!KnownValid && "Explicit template arguments?")((!KnownValid && "Explicit template arguments?") ? static_cast
<void> (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12332, __PRETTY_FUNCTION__))
;
12333 return;
12334 }
12335 // Prevent ill-formed function decls to be added as overload candidates.
12336 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12337 return;
12338
12339 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12340 /*SuppressUserConversions=*/false,
12341 PartialOverloading);
12342 return;
12343 }
12344
12345 if (FunctionTemplateDecl *FuncTemplate
12346 = dyn_cast<FunctionTemplateDecl>(Callee)) {
12347 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12348 ExplicitTemplateArgs, Args, CandidateSet,
12349 /*SuppressUserConversions=*/false,
12350 PartialOverloading);
12351 return;
12352 }
12353
12354 assert(!KnownValid && "unhandled case in overloaded call candidate")((!KnownValid && "unhandled case in overloaded call candidate"
) ? static_cast<void> (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12354, __PRETTY_FUNCTION__))
;
12355}
12356
12357/// Add the overload candidates named by callee and/or found by argument
12358/// dependent lookup to the given overload set.
12359void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12360 ArrayRef<Expr *> Args,
12361 OverloadCandidateSet &CandidateSet,
12362 bool PartialOverloading) {
12363
12364#ifndef NDEBUG
12365 // Verify that ArgumentDependentLookup is consistent with the rules
12366 // in C++0x [basic.lookup.argdep]p3:
12367 //
12368 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12369 // and let Y be the lookup set produced by argument dependent
12370 // lookup (defined as follows). If X contains
12371 //
12372 // -- a declaration of a class member, or
12373 //
12374 // -- a block-scope function declaration that is not a
12375 // using-declaration, or
12376 //
12377 // -- a declaration that is neither a function or a function
12378 // template
12379 //
12380 // then Y is empty.
12381
12382 if (ULE->requiresADL()) {
12383 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12384 E = ULE->decls_end(); I != E; ++I) {
12385 assert(!(*I)->getDeclContext()->isRecord())((!(*I)->getDeclContext()->isRecord()) ? static_cast<
void> (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12385, __PRETTY_FUNCTION__))
;
12386 assert(isa<UsingShadowDecl>(*I) ||((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12387, __PRETTY_FUNCTION__))
12387 !(*I)->getDeclContext()->isFunctionOrMethod())((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12387, __PRETTY_FUNCTION__))
;
12388 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? static_cast<void> (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12388, __PRETTY_FUNCTION__))
;
12389 }
12390 }
12391#endif
12392
12393 // It would be nice to avoid this copy.
12394 TemplateArgumentListInfo TABuffer;
12395 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12396 if (ULE->hasExplicitTemplateArgs()) {
12397 ULE->copyTemplateArgumentsInto(TABuffer);
12398 ExplicitTemplateArgs = &TABuffer;
12399 }
12400
12401 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12402 E = ULE->decls_end(); I != E; ++I)
12403 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12404 CandidateSet, PartialOverloading,
12405 /*KnownValid*/ true);
12406
12407 if (ULE->requiresADL())
12408 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12409 Args, ExplicitTemplateArgs,
12410 CandidateSet, PartialOverloading);
12411}
12412
12413/// Determine whether a declaration with the specified name could be moved into
12414/// a different namespace.
12415static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12416 switch (Name.getCXXOverloadedOperator()) {
12417 case OO_New: case OO_Array_New:
12418 case OO_Delete: case OO_Array_Delete:
12419 return false;
12420
12421 default:
12422 return true;
12423 }
12424}
12425
12426/// Attempt to recover from an ill-formed use of a non-dependent name in a
12427/// template, where the non-dependent name was declared after the template
12428/// was defined. This is common in code written for a compilers which do not
12429/// correctly implement two-stage name lookup.
12430///
12431/// Returns true if a viable candidate was found and a diagnostic was issued.
12432static bool
12433DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12434 const CXXScopeSpec &SS, LookupResult &R,
12435 OverloadCandidateSet::CandidateSetKind CSK,
12436 TemplateArgumentListInfo *ExplicitTemplateArgs,
12437 ArrayRef<Expr *> Args,
12438 bool *DoDiagnoseEmptyLookup = nullptr) {
12439 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12440 return false;
12441
12442 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12443 if (DC->isTransparentContext())
12444 continue;
12445
12446 SemaRef.LookupQualifiedName(R, DC);
12447
12448 if (!R.empty()) {
12449 R.suppressDiagnostics();
12450
12451 if (isa<CXXRecordDecl>(DC)) {
12452 // Don't diagnose names we find in classes; we get much better
12453 // diagnostics for these from DiagnoseEmptyLookup.
12454 R.clear();
12455 if (DoDiagnoseEmptyLookup)
12456 *DoDiagnoseEmptyLookup = true;
12457 return false;
12458 }
12459
12460 OverloadCandidateSet Candidates(FnLoc, CSK);
12461 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12462 AddOverloadedCallCandidate(SemaRef, I.getPair(),
12463 ExplicitTemplateArgs, Args,
12464 Candidates, false, /*KnownValid*/ false);
12465
12466 OverloadCandidateSet::iterator Best;
12467 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12468 // No viable functions. Don't bother the user with notes for functions
12469 // which don't work and shouldn't be found anyway.
12470 R.clear();
12471 return false;
12472 }
12473
12474 // Find the namespaces where ADL would have looked, and suggest
12475 // declaring the function there instead.
12476 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12477 Sema::AssociatedClassSet AssociatedClasses;
12478 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12479 AssociatedNamespaces,
12480 AssociatedClasses);
12481 Sema::AssociatedNamespaceSet SuggestedNamespaces;
12482 if (canBeDeclaredInNamespace(R.getLookupName())) {
12483 DeclContext *Std = SemaRef.getStdNamespace();
12484 for (Sema::AssociatedNamespaceSet::iterator
12485 it = AssociatedNamespaces.begin(),
12486 end = AssociatedNamespaces.end(); it != end; ++it) {
12487 // Never suggest declaring a function within namespace 'std'.
12488 if (Std && Std->Encloses(*it))
12489 continue;
12490
12491 // Never suggest declaring a function within a namespace with a
12492 // reserved name, like __gnu_cxx.
12493 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12494 if (NS &&
12495 NS->getQualifiedNameAsString().find("__") != std::string::npos)
12496 continue;
12497
12498 SuggestedNamespaces.insert(*it);
12499 }
12500 }
12501
12502 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12503 << R.getLookupName();
12504 if (SuggestedNamespaces.empty()) {
12505 SemaRef.Diag(Best->Function->getLocation(),
12506 diag::note_not_found_by_two_phase_lookup)
12507 << R.getLookupName() << 0;
12508 } else if (SuggestedNamespaces.size() == 1) {
12509 SemaRef.Diag(Best->Function->getLocation(),
12510 diag::note_not_found_by_two_phase_lookup)
12511 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12512 } else {
12513 // FIXME: It would be useful to list the associated namespaces here,
12514 // but the diagnostics infrastructure doesn't provide a way to produce
12515 // a localized representation of a list of items.
12516 SemaRef.Diag(Best->Function->getLocation(),
12517 diag::note_not_found_by_two_phase_lookup)
12518 << R.getLookupName() << 2;
12519 }
12520
12521 // Try to recover by calling this function.
12522 return true;
12523 }
12524
12525 R.clear();
12526 }
12527
12528 return false;
12529}
12530
12531/// Attempt to recover from ill-formed use of a non-dependent operator in a
12532/// template, where the non-dependent operator was declared after the template
12533/// was defined.
12534///
12535/// Returns true if a viable candidate was found and a diagnostic was issued.
12536static bool
12537DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12538 SourceLocation OpLoc,
12539 ArrayRef<Expr *> Args) {
12540 DeclarationName OpName =
12541 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12542 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12543 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12544 OverloadCandidateSet::CSK_Operator,
12545 /*ExplicitTemplateArgs=*/nullptr, Args);
12546}
12547
12548namespace {
12549class BuildRecoveryCallExprRAII {
12550 Sema &SemaRef;
12551public:
12552 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12553 assert(SemaRef.IsBuildingRecoveryCallExpr == false)((SemaRef.IsBuildingRecoveryCallExpr == false) ? static_cast<
void> (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12553, __PRETTY_FUNCTION__))
;
12554 SemaRef.IsBuildingRecoveryCallExpr = true;
12555 }
12556
12557 ~BuildRecoveryCallExprRAII() {
12558 SemaRef.IsBuildingRecoveryCallExpr = false;
12559 }
12560};
12561
12562}
12563
12564/// Attempts to recover from a call where no functions were found.
12565///
12566/// Returns true if new candidates were found.
12567static ExprResult
12568BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12569 UnresolvedLookupExpr *ULE,
12570 SourceLocation LParenLoc,
12571 MutableArrayRef<Expr *> Args,
12572 SourceLocation RParenLoc,
12573 bool EmptyLookup, bool AllowTypoCorrection) {
12574 // Do not try to recover if it is already building a recovery call.
12575 // This stops infinite loops for template instantiations like
12576 //
12577 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12578 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12579 //
12580 if (SemaRef.IsBuildingRecoveryCallExpr)
12581 return ExprError();
12582 BuildRecoveryCallExprRAII RCE(SemaRef);
12583
12584 CXXScopeSpec SS;
12585 SS.Adopt(ULE->getQualifierLoc());
12586 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12587
12588 TemplateArgumentListInfo TABuffer;
12589 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12590 if (ULE->hasExplicitTemplateArgs()) {
12591 ULE->copyTemplateArgumentsInto(TABuffer);
12592 ExplicitTemplateArgs = &TABuffer;
12593 }
12594
12595 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12596 Sema::LookupOrdinaryName);
12597 bool DoDiagnoseEmptyLookup = EmptyLookup;
12598 if (!DiagnoseTwoPhaseLookup(
12599 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12600 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12601 NoTypoCorrectionCCC NoTypoValidator{};
12602 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12603 ExplicitTemplateArgs != nullptr,
12604 dyn_cast<MemberExpr>(Fn));
12605 CorrectionCandidateCallback &Validator =
12606 AllowTypoCorrection
12607 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12608 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12609 if (!DoDiagnoseEmptyLookup ||
12610 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12611 Args))
12612 return ExprError();
12613 }
12614
12615 assert(!R.empty() && "lookup results empty despite recovery")((!R.empty() && "lookup results empty despite recovery"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12615, __PRETTY_FUNCTION__))
;
12616
12617 // If recovery created an ambiguity, just bail out.
12618 if (R.isAmbiguous()) {
12619 R.suppressDiagnostics();
12620 return ExprError();
12621 }
12622
12623 // Build an implicit member call if appropriate. Just drop the
12624 // casts and such from the call, we don't really care.
12625 ExprResult NewFn = ExprError();
12626 if ((*R.begin())->isCXXClassMember())
12627 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12628 ExplicitTemplateArgs, S);
12629 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12630 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12631 ExplicitTemplateArgs);
12632 else
12633 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12634
12635 if (NewFn.isInvalid())
12636 return ExprError();
12637
12638 // This shouldn't cause an infinite loop because we're giving it
12639 // an expression with viable lookup results, which should never
12640 // end up here.
12641 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12642 MultiExprArg(Args.data(), Args.size()),
12643 RParenLoc);
12644}
12645
12646/// Constructs and populates an OverloadedCandidateSet from
12647/// the given function.
12648/// \returns true when an the ExprResult output parameter has been set.
12649bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12650 UnresolvedLookupExpr *ULE,
12651 MultiExprArg Args,
12652 SourceLocation RParenLoc,
12653 OverloadCandidateSet *CandidateSet,
12654 ExprResult *Result) {
12655#ifndef NDEBUG
12656 if (ULE->requiresADL()) {
12657 // To do ADL, we must have found an unqualified name.
12658 assert(!ULE->getQualifier() && "qualified name with ADL")((!ULE->getQualifier() && "qualified name with ADL"
) ? static_cast<void> (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12658, __PRETTY_FUNCTION__))
;
12659
12660 // We don't perform ADL for implicit declarations of builtins.
12661 // Verify that this was correctly set up.
12662 FunctionDecl *F;
12663 if (ULE->decls_begin() != ULE->decls_end() &&
12664 ULE->decls_begin() + 1 == ULE->decls_end() &&
12665 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12666 F->getBuiltinID() && F->isImplicit())
12667 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12667)
;
12668
12669 // We don't perform ADL in C.
12670 assert(getLangOpts().CPlusPlus && "ADL enabled in C")((getLangOpts().CPlusPlus && "ADL enabled in C") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12670, __PRETTY_FUNCTION__))
;
12671 }
12672#endif
12673
12674 UnbridgedCastsSet UnbridgedCasts;
12675 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12676 *Result = ExprError();
12677 return true;
12678 }
12679
12680 // Add the functions denoted by the callee to the set of candidate
12681 // functions, including those from argument-dependent lookup.
12682 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12683
12684 if (getLangOpts().MSVCCompat &&
12685 CurContext->isDependentContext() && !isSFINAEContext() &&
12686 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12687
12688 OverloadCandidateSet::iterator Best;
12689 if (CandidateSet->empty() ||
12690 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12691 OR_No_Viable_Function) {
12692 // In Microsoft mode, if we are inside a template class member function
12693 // then create a type dependent CallExpr. The goal is to postpone name
12694 // lookup to instantiation time to be able to search into type dependent
12695 // base classes.
12696 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12697 VK_RValue, RParenLoc);
12698 CE->setTypeDependent(true);
12699 CE->setValueDependent(true);
12700 CE->setInstantiationDependent(true);
12701 *Result = CE;
12702 return true;
12703 }
12704 }
12705
12706 if (CandidateSet->empty())
12707 return false;
12708
12709 UnbridgedCasts.restore();
12710 return false;
12711}
12712
12713/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12714/// the completed call expression. If overload resolution fails, emits
12715/// diagnostics and returns ExprError()
12716static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12717 UnresolvedLookupExpr *ULE,
12718 SourceLocation LParenLoc,
12719 MultiExprArg Args,
12720 SourceLocation RParenLoc,
12721 Expr *ExecConfig,
12722 OverloadCandidateSet *CandidateSet,
12723 OverloadCandidateSet::iterator *Best,
12724 OverloadingResult OverloadResult,
12725 bool AllowTypoCorrection) {
12726 if (CandidateSet->empty())
12727 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12728 RParenLoc, /*EmptyLookup=*/true,
12729 AllowTypoCorrection);
12730
12731 switch (OverloadResult) {
12732 case OR_Success: {
12733 FunctionDecl *FDecl = (*Best)->Function;
12734 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12735 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12736 return ExprError();
12737 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12738 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12739 ExecConfig, /*IsExecConfig=*/false,
12740 (*Best)->IsADLCandidate);
12741 }
12742
12743 case OR_No_Viable_Function: {
12744 // Try to recover by looking for viable functions which the user might
12745 // have meant to call.
12746 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12747 Args, RParenLoc,
12748 /*EmptyLookup=*/false,
12749 AllowTypoCorrection);
12750 if (!Recovery.isInvalid())
12751 return Recovery;
12752
12753 // If the user passes in a function that we can't take the address of, we
12754 // generally end up emitting really bad error messages. Here, we attempt to
12755 // emit better ones.
12756 for (const Expr *Arg : Args) {
12757 if (!Arg->getType()->isFunctionType())
12758 continue;
12759 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12760 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12761 if (FD &&
12762 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12763 Arg->getExprLoc()))
12764 return ExprError();
12765 }
12766 }
12767
12768 CandidateSet->NoteCandidates(
12769 PartialDiagnosticAt(
12770 Fn->getBeginLoc(),
12771 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12772 << ULE->getName() << Fn->getSourceRange()),
12773 SemaRef, OCD_AllCandidates, Args);
12774 break;
12775 }
12776
12777 case OR_Ambiguous:
12778 CandidateSet->NoteCandidates(
12779 PartialDiagnosticAt(Fn->getBeginLoc(),
12780 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12781 << ULE->getName() << Fn->getSourceRange()),
12782 SemaRef, OCD_AmbiguousCandidates, Args);
12783 break;
12784
12785 case OR_Deleted: {
12786 CandidateSet->NoteCandidates(
12787 PartialDiagnosticAt(Fn->getBeginLoc(),
12788 SemaRef.PDiag(diag::err_ovl_deleted_call)
12789 << ULE->getName() << Fn->getSourceRange()),
12790 SemaRef, OCD_AllCandidates, Args);
12791
12792 // We emitted an error for the unavailable/deleted function call but keep
12793 // the call in the AST.
12794 FunctionDecl *FDecl = (*Best)->Function;
12795 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12796 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12797 ExecConfig, /*IsExecConfig=*/false,
12798 (*Best)->IsADLCandidate);
12799 }
12800 }
12801
12802 // Overload resolution failed.
12803 return ExprError();
12804}
12805
12806static void markUnaddressableCandidatesUnviable(Sema &S,
12807 OverloadCandidateSet &CS) {
12808 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12809 if (I->Viable &&
12810 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12811 I->Viable = false;
12812 I->FailureKind = ovl_fail_addr_not_available;
12813 }
12814 }
12815}
12816
12817/// BuildOverloadedCallExpr - Given the call expression that calls Fn
12818/// (which eventually refers to the declaration Func) and the call
12819/// arguments Args/NumArgs, attempt to resolve the function call down
12820/// to a specific function. If overload resolution succeeds, returns
12821/// the call expression produced by overload resolution.
12822/// Otherwise, emits diagnostics and returns ExprError.
12823ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12824 UnresolvedLookupExpr *ULE,
12825 SourceLocation LParenLoc,
12826 MultiExprArg Args,
12827 SourceLocation RParenLoc,
12828 Expr *ExecConfig,
12829 bool AllowTypoCorrection,
12830 bool CalleesAddressIsTaken) {
12831 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12832 OverloadCandidateSet::CSK_Normal);
12833 ExprResult result;
12834
12835 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12836 &result))
12837 return result;
12838
12839 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12840 // functions that aren't addressible are considered unviable.
12841 if (CalleesAddressIsTaken)
12842 markUnaddressableCandidatesUnviable(*this, CandidateSet);
12843
12844 OverloadCandidateSet::iterator Best;
12845 OverloadingResult OverloadResult =
12846 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12847
12848 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12849 ExecConfig, &CandidateSet, &Best,
12850 OverloadResult, AllowTypoCorrection);
12851}
12852
12853static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12854 return Functions.size() > 1 ||
12855 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12856}
12857
12858/// Create a unary operation that may resolve to an overloaded
12859/// operator.
12860///
12861/// \param OpLoc The location of the operator itself (e.g., '*').
12862///
12863/// \param Opc The UnaryOperatorKind that describes this operator.
12864///
12865/// \param Fns The set of non-member functions that will be
12866/// considered by overload resolution. The caller needs to build this
12867/// set based on the context using, e.g.,
12868/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12869/// set should not contain any member functions; those will be added
12870/// by CreateOverloadedUnaryOp().
12871///
12872/// \param Input The input argument.
12873ExprResult
12874Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12875 const UnresolvedSetImpl &Fns,
12876 Expr *Input, bool PerformADL) {
12877 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12878 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")((Op != OO_None && "Invalid opcode for overloaded unary operator"
) ? static_cast<void> (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12878, __PRETTY_FUNCTION__))
;
12879 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12880 // TODO: provide better source location info.
12881 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12882
12883 if (checkPlaceholderForOverload(*this, Input))
12884 return ExprError();
12885
12886 Expr *Args[2] = { Input, nullptr };
12887 unsigned NumArgs = 1;
12888
12889 // For post-increment and post-decrement, add the implicit '0' as
12890 // the second argument, so that we know this is a post-increment or
12891 // post-decrement.
12892 if (Opc == UO_PostInc || Opc == UO_PostDec) {
12893 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12894 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12895 SourceLocation());
12896 NumArgs = 2;
12897 }
12898
12899 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12900
12901 if (Input->isTypeDependent()) {
12902 if (Fns.empty())
12903 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12904 VK_RValue, OK_Ordinary, OpLoc, false);
12905
12906 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12907 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12908 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12909 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12910 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12911 Context.DependentTy, VK_RValue, OpLoc,
12912 FPOptions());
12913 }
12914
12915 // Build an empty overload set.
12916 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12917
12918 // Add the candidates from the given function set.
12919 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12920
12921 // Add operator candidates that are member functions.
12922 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12923
12924 // Add candidates from ADL.
12925 if (PerformADL) {
12926 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12927 /*ExplicitTemplateArgs*/nullptr,
12928 CandidateSet);
12929 }
12930
12931 // Add builtin operator candidates.
12932 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12933
12934 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12935
12936 // Perform overload resolution.
12937 OverloadCandidateSet::iterator Best;
12938 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12939 case OR_Success: {
12940 // We found a built-in operator or an overloaded operator.
12941 FunctionDecl *FnDecl = Best->Function;
12942
12943 if (FnDecl) {
12944 Expr *Base = nullptr;
12945 // We matched an overloaded operator. Build a call to that
12946 // operator.
12947
12948 // Convert the arguments.
12949 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12950 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12951
12952 ExprResult InputRes =
12953 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12954 Best->FoundDecl, Method);
12955 if (InputRes.isInvalid())
12956 return ExprError();
12957 Base = Input = InputRes.get();
12958 } else {
12959 // Convert the arguments.
12960 ExprResult InputInit
12961 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12962 Context,
12963 FnDecl->getParamDecl(0)),
12964 SourceLocation(),
12965 Input);
12966 if (InputInit.isInvalid())
12967 return ExprError();
12968 Input = InputInit.get();
12969 }
12970
12971 // Build the actual expression node.
12972 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12973 Base, HadMultipleCandidates,
12974 OpLoc);
12975 if (FnExpr.isInvalid())
12976 return ExprError();
12977
12978 // Determine the result type.
12979 QualType ResultTy = FnDecl->getReturnType();
12980 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12981 ResultTy = ResultTy.getNonLValueExprType(Context);
12982
12983 Args[0] = Input;
12984 CallExpr *TheCall = CXXOperatorCallExpr::Create(
12985 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12986 FPOptions(), Best->IsADLCandidate);
12987
12988 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12989 return ExprError();
12990
12991 if (CheckFunctionCall(FnDecl, TheCall,
12992 FnDecl->getType()->castAs<FunctionProtoType>()))
12993 return ExprError();
12994
12995 return MaybeBindToTemporary(TheCall);
12996 } else {
12997 // We matched a built-in operator. Convert the arguments, then
12998 // break out so that we will build the appropriate built-in
12999 // operator node.
13000 ExprResult InputRes = PerformImplicitConversion(
13001 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13002 CCK_ForBuiltinOverloadedOp);
13003 if (InputRes.isInvalid())
13004 return ExprError();
13005 Input = InputRes.get();
13006 break;
13007 }
13008 }
13009
13010 case OR_No_Viable_Function:
13011 // This is an erroneous use of an operator which can be overloaded by
13012 // a non-member function. Check for non-member operators which were
13013 // defined too late to be candidates.
13014 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13015 // FIXME: Recover by calling the found function.
13016 return ExprError();
13017
13018 // No viable function; fall through to handling this as a
13019 // built-in operator, which will produce an error message for us.
13020 break;
13021
13022 case OR_Ambiguous:
13023 CandidateSet.NoteCandidates(
13024 PartialDiagnosticAt(OpLoc,
13025 PDiag(diag::err_ovl_ambiguous_oper_unary)
13026 << UnaryOperator::getOpcodeStr(Opc)
13027 << Input->getType() << Input->getSourceRange()),
13028 *this, OCD_AmbiguousCandidates, ArgsArray,
13029 UnaryOperator::getOpcodeStr(Opc), OpLoc);
13030 return ExprError();
13031
13032 case OR_Deleted:
13033 CandidateSet.NoteCandidates(
13034 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13035 << UnaryOperator::getOpcodeStr(Opc)
13036 << Input->getSourceRange()),
13037 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13038 OpLoc);
13039 return ExprError();
13040 }
13041
13042 // Either we found no viable overloaded operator or we matched a
13043 // built-in operator. In either case, fall through to trying to
13044 // build a built-in operation.
13045 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13046}
13047
13048/// Perform lookup for an overloaded binary operator.
13049void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13050 OverloadedOperatorKind Op,
13051 const UnresolvedSetImpl &Fns,
13052 ArrayRef<Expr *> Args, bool PerformADL) {
13053 SourceLocation OpLoc = CandidateSet.getLocation();
13054
13055 OverloadedOperatorKind ExtraOp =
13056 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13057 ? getRewrittenOverloadedOperator(Op)
13058 : OO_None;
13059
13060 // Add the candidates from the given function set. This also adds the
13061 // rewritten candidates using these functions if necessary.
13062 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13063
13064 // Add operator candidates that are member functions.
13065 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13066 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13067 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13068 OverloadCandidateParamOrder::Reversed);
13069
13070 // In C++20, also add any rewritten member candidates.
13071 if (ExtraOp) {
13072 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13073 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13074 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13075 CandidateSet,
13076 OverloadCandidateParamOrder::Reversed);
13077 }
13078
13079 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13080 // performed for an assignment operator (nor for operator[] nor operator->,
13081 // which don't get here).
13082 if (Op != OO_Equal && PerformADL) {
13083 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13084 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13085 /*ExplicitTemplateArgs*/ nullptr,
13086 CandidateSet);
13087 if (ExtraOp) {
13088 DeclarationName ExtraOpName =
13089 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13090 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13091 /*ExplicitTemplateArgs*/ nullptr,
13092 CandidateSet);
13093 }
13094 }
13095
13096 // Add builtin operator candidates.
13097 //
13098 // FIXME: We don't add any rewritten candidates here. This is strictly
13099 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13100 // resulting in our selecting a rewritten builtin candidate. For example:
13101 //
13102 // enum class E { e };
13103 // bool operator!=(E, E) requires false;
13104 // bool k = E::e != E::e;
13105 //
13106 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13107 // it seems unreasonable to consider rewritten builtin candidates. A core
13108 // issue has been filed proposing to removed this requirement.
13109 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13110}
13111
13112/// Create a binary operation that may resolve to an overloaded
13113/// operator.
13114///
13115/// \param OpLoc The location of the operator itself (e.g., '+').
13116///
13117/// \param Opc The BinaryOperatorKind that describes this operator.
13118///
13119/// \param Fns The set of non-member functions that will be
13120/// considered by overload resolution. The caller needs to build this
13121/// set based on the context using, e.g.,
13122/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13123/// set should not contain any member functions; those will be added
13124/// by CreateOverloadedBinOp().
13125///
13126/// \param LHS Left-hand argument.
13127/// \param RHS Right-hand argument.
13128/// \param PerformADL Whether to consider operator candidates found by ADL.
13129/// \param AllowRewrittenCandidates Whether to consider candidates found by
13130/// C++20 operator rewrites.
13131/// \param DefaultedFn If we are synthesizing a defaulted operator function,
13132/// the function in question. Such a function is never a candidate in
13133/// our overload resolution. This also enables synthesizing a three-way
13134/// comparison from < and == as described in C++20 [class.spaceship]p1.
13135ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13136 BinaryOperatorKind Opc,
13137 const UnresolvedSetImpl &Fns, Expr *LHS,
13138 Expr *RHS, bool PerformADL,
13139 bool AllowRewrittenCandidates,
13140 FunctionDecl *DefaultedFn) {
13141 Expr *Args[2] = { LHS, RHS };
13142 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13143
13144 if (!getLangOpts().CPlusPlus2a)
13145 AllowRewrittenCandidates = false;
13146
13147 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13148
13149 // If either side is type-dependent, create an appropriate dependent
13150 // expression.
13151 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13152 if (Fns.empty()) {
13153 // If there are no functions to store, just build a dependent
13154 // BinaryOperator or CompoundAssignment.
13155 if (Opc <= BO_Assign || Opc > BO_OrAssign)
13156 return new (Context) BinaryOperator(
13157 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
13158 OpLoc, FPFeatures);
13159
13160 return new (Context) CompoundAssignOperator(
13161 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
13162 Context.DependentTy, Context.DependentTy, OpLoc,
13163 FPFeatures);
13164 }
13165
13166 // FIXME: save results of ADL from here?
13167 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13168 // TODO: provide better source location info in DNLoc component.
13169 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13170 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13171 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13172 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13173 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13174 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13175 Context.DependentTy, VK_RValue, OpLoc,
13176 FPFeatures);
13177 }
13178
13179 // Always do placeholder-like conversions on the RHS.
13180 if (checkPlaceholderForOverload(*this, Args[1]))
13181 return ExprError();
13182
13183 // Do placeholder-like conversion on the LHS; note that we should
13184 // not get here with a PseudoObject LHS.
13185 assert(Args[0]->getObjectKind() != OK_ObjCProperty)((Args[0]->getObjectKind() != OK_ObjCProperty) ? static_cast
<void> (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13185, __PRETTY_FUNCTION__))
;
13186 if (checkPlaceholderForOverload(*this, Args[0]))
13187 return ExprError();
13188
13189 // If this is the assignment operator, we only perform overload resolution
13190 // if the left-hand side is a class or enumeration type. This is actually
13191 // a hack. The standard requires that we do overload resolution between the
13192 // various built-in candidates, but as DR507 points out, this can lead to
13193 // problems. So we do it this way, which pretty much follows what GCC does.
13194 // Note that we go the traditional code path for compound assignment forms.
13195 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13196 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13197
13198 // If this is the .* operator, which is not overloadable, just
13199 // create a built-in binary operator.
13200 if (Opc == BO_PtrMemD)
13201 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13202
13203 // Build the overload set.
13204 OverloadCandidateSet CandidateSet(
13205 OpLoc, OverloadCandidateSet::CSK_Operator,
13206 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13207 if (DefaultedFn)
13208 CandidateSet.exclude(DefaultedFn);
13209 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13210
13211 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13212
13213 // Perform overload resolution.
13214 OverloadCandidateSet::iterator Best;
13215 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13216 case OR_Success: {
13217 // We found a built-in operator or an overloaded operator.
13218 FunctionDecl *FnDecl = Best->Function;
13219
13220 bool IsReversed = (Best->RewriteKind & CRK_Reversed);
13221 if (IsReversed)
13222 std::swap(Args[0], Args[1]);
13223
13224 if (FnDecl) {
13225 Expr *Base = nullptr;
13226 // We matched an overloaded operator. Build a call to that
13227 // operator.
13228
13229 OverloadedOperatorKind ChosenOp =
13230 FnDecl->getDeclName().getCXXOverloadedOperator();
13231
13232 // C++2a [over.match.oper]p9:
13233 // If a rewritten operator== candidate is selected by overload
13234 // resolution for an operator@, its return type shall be cv bool
13235 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13236 !FnDecl->getReturnType()->isBooleanType()) {
13237 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
13238 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13239 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13240 Diag(FnDecl->getLocation(), diag::note_declared_at);
13241 return ExprError();
13242 }
13243
13244 if (AllowRewrittenCandidates && !IsReversed &&
13245 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
13246 // We could have reversed this operator, but didn't. Check if the
13247 // reversed form was a viable candidate, and if so, if it had a
13248 // better conversion for either parameter. If so, this call is
13249 // formally ambiguous, and allowing it is an extension.
13250 for (OverloadCandidate &Cand : CandidateSet) {
13251 if (Cand.Viable && Cand.Function == FnDecl &&
13252 Cand.RewriteKind & CRK_Reversed) {
13253 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13254 if (CompareImplicitConversionSequences(
13255 *this, OpLoc, Cand.Conversions[ArgIdx],
13256 Best->Conversions[ArgIdx]) ==
13257 ImplicitConversionSequence::Better) {
13258 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13259 << BinaryOperator::getOpcodeStr(Opc)
13260 << Args[0]->getType() << Args[1]->getType()
13261 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13262 Diag(FnDecl->getLocation(),
13263 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13264 }
13265 }
13266 break;
13267 }
13268 }
13269 }
13270
13271 // Convert the arguments.
13272 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13273 // Best->Access is only meaningful for class members.
13274 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13275
13276 ExprResult Arg1 =
13277 PerformCopyInitialization(
13278 InitializedEntity::InitializeParameter(Context,
13279 FnDecl->getParamDecl(0)),
13280 SourceLocation(), Args[1]);
13281 if (Arg1.isInvalid())
13282 return ExprError();
13283
13284 ExprResult Arg0 =
13285 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13286 Best->FoundDecl, Method);
13287 if (Arg0.isInvalid())
13288 return ExprError();
13289 Base = Args[0] = Arg0.getAs<Expr>();
13290 Args[1] = RHS = Arg1.getAs<Expr>();
13291 } else {
13292 // Convert the arguments.
13293 ExprResult Arg0 = PerformCopyInitialization(
13294 InitializedEntity::InitializeParameter(Context,
13295 FnDecl->getParamDecl(0)),
13296 SourceLocation(), Args[0]);
13297 if (Arg0.isInvalid())
13298 return ExprError();
13299
13300 ExprResult Arg1 =
13301 PerformCopyInitialization(
13302 InitializedEntity::InitializeParameter(Context,
13303 FnDecl->getParamDecl(1)),
13304 SourceLocation(), Args[1]);
13305 if (Arg1.isInvalid())
13306 return ExprError();
13307 Args[0] = LHS = Arg0.getAs<Expr>();
13308 Args[1] = RHS = Arg1.getAs<Expr>();
13309 }
13310
13311 // Build the actual expression node.
13312 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13313 Best->FoundDecl, Base,
13314 HadMultipleCandidates, OpLoc);
13315 if (FnExpr.isInvalid())
13316 return ExprError();
13317
13318 // Determine the result type.
13319 QualType ResultTy = FnDecl->getReturnType();
13320 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13321 ResultTy = ResultTy.getNonLValueExprType(Context);
13322
13323 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13324 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13325 FPFeatures, Best->IsADLCandidate);
13326
13327 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13328 FnDecl))
13329 return ExprError();
13330
13331 ArrayRef<const Expr *> ArgsArray(Args, 2);
13332 const Expr *ImplicitThis = nullptr;
13333 // Cut off the implicit 'this'.
13334 if (isa<CXXMethodDecl>(FnDecl)) {
13335 ImplicitThis = ArgsArray[0];
13336 ArgsArray = ArgsArray.slice(1);
13337 }
13338
13339 // Check for a self move.
13340 if (Op == OO_Equal)
13341 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13342
13343 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13344 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13345 VariadicDoesNotApply);
13346
13347 ExprResult R = MaybeBindToTemporary(TheCall);
13348 if (R.isInvalid())
13349 return ExprError();
13350
13351 // For a rewritten candidate, we've already reversed the arguments
13352 // if needed. Perform the rest of the rewrite now.
13353 if ((Best->RewriteKind & CRK_DifferentOperator) ||
13354 (Op == OO_Spaceship && IsReversed)) {
13355 if (Op == OO_ExclaimEqual) {
13356 assert(ChosenOp == OO_EqualEqual && "unexpected operator name")((ChosenOp == OO_EqualEqual && "unexpected operator name"
) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_EqualEqual && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13356, __PRETTY_FUNCTION__))
;
13357 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13358 } else {
13359 assert(ChosenOp == OO_Spaceship && "unexpected operator name")((ChosenOp == OO_Spaceship && "unexpected operator name"
) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_Spaceship && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13359, __PRETTY_FUNCTION__))
;
13360 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13361 Expr *ZeroLiteral =
13362 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13363
13364 Sema::CodeSynthesisContext Ctx;
13365 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13366 Ctx.Entity = FnDecl;
13367 pushCodeSynthesisContext(Ctx);
13368
13369 R = CreateOverloadedBinOp(
13370 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13371 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13372 /*AllowRewrittenCandidates=*/false);
13373
13374 popCodeSynthesisContext();
13375 }
13376 if (R.isInvalid())
13377 return ExprError();
13378 } else {
13379 assert(ChosenOp == Op && "unexpected operator name")((ChosenOp == Op && "unexpected operator name") ? static_cast
<void> (0) : __assert_fail ("ChosenOp == Op && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13379, __PRETTY_FUNCTION__))
;
13380 }
13381
13382 // Make a note in the AST if we did any rewriting.
13383 if (Best->RewriteKind != CRK_None)
13384 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13385
13386 return R;
13387 } else {
13388 // We matched a built-in operator. Convert the arguments, then
13389 // break out so that we will build the appropriate built-in
13390 // operator node.
13391 ExprResult ArgsRes0 = PerformImplicitConversion(
13392 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13393 AA_Passing, CCK_ForBuiltinOverloadedOp);
13394 if (ArgsRes0.isInvalid())
13395 return ExprError();
13396 Args[0] = ArgsRes0.get();
13397
13398 ExprResult ArgsRes1 = PerformImplicitConversion(
13399 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13400 AA_Passing, CCK_ForBuiltinOverloadedOp);
13401 if (ArgsRes1.isInvalid())
13402 return ExprError();
13403 Args[1] = ArgsRes1.get();
13404 break;
13405 }
13406 }
13407
13408 case OR_No_Viable_Function: {
13409 // C++ [over.match.oper]p9:
13410 // If the operator is the operator , [...] and there are no
13411 // viable functions, then the operator is assumed to be the
13412 // built-in operator and interpreted according to clause 5.
13413 if (Opc == BO_Comma)
13414 break;
13415
13416 // When defaulting an 'operator<=>', we can try to synthesize a three-way
13417 // compare result using '==' and '<'.
13418 if (DefaultedFn && Opc == BO_Cmp) {
13419 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13420 Args[1], DefaultedFn);
13421 if (E.isInvalid() || E.isUsable())
13422 return E;
13423 }
13424
13425 // For class as left operand for assignment or compound assignment
13426 // operator do not fall through to handling in built-in, but report that
13427 // no overloaded assignment operator found
13428 ExprResult Result = ExprError();
13429 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13430 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13431 Args, OpLoc);
13432 if (Args[0]->getType()->isRecordType() &&
13433 Opc >= BO_Assign && Opc <= BO_OrAssign) {
13434 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13435 << BinaryOperator::getOpcodeStr(Opc)
13436 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13437 if (Args[0]->getType()->isIncompleteType()) {
13438 Diag(OpLoc, diag::note_assign_lhs_incomplete)
13439 << Args[0]->getType()
13440 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13441 }
13442 } else {
13443 // This is an erroneous use of an operator which can be overloaded by
13444 // a non-member function. Check for non-member operators which were
13445 // defined too late to be candidates.
13446 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13447 // FIXME: Recover by calling the found function.
13448 return ExprError();
13449
13450 // No viable function; try to create a built-in operation, which will
13451 // produce an error. Then, show the non-viable candidates.
13452 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13453 }
13454 assert(Result.isInvalid() &&((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13455, __PRETTY_FUNCTION__))
13455 "C++ binary operator overloading is missing candidates!")((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13455, __PRETTY_FUNCTION__))
;
13456 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13457 return Result;
13458 }
13459
13460 case OR_Ambiguous:
13461 CandidateSet.NoteCandidates(
13462 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13463 << BinaryOperator::getOpcodeStr(Opc)
13464 << Args[0]->getType()
13465 << Args[1]->getType()
13466 << Args[0]->getSourceRange()
13467 << Args[1]->getSourceRange()),
13468 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13469 OpLoc);
13470 return ExprError();
13471
13472 case OR_Deleted:
13473 if (isImplicitlyDeleted(Best->Function)) {
13474 FunctionDecl *DeletedFD = Best->Function;
13475 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13476 if (DFK.isSpecialMember()) {
13477 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13478 << Args[0]->getType() << DFK.asSpecialMember();
13479 } else {
13480 assert(DFK.isComparison())((DFK.isComparison()) ? static_cast<void> (0) : __assert_fail
("DFK.isComparison()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13480, __PRETTY_FUNCTION__))
;
13481 Diag(OpLoc, diag::err_ovl_deleted_comparison)
13482 << Args[0]->getType() << DeletedFD;
13483 }
13484
13485 // The user probably meant to call this special member. Just
13486 // explain why it's deleted.
13487 NoteDeletedFunction(DeletedFD);
13488 return ExprError();
13489 }
13490 CandidateSet.NoteCandidates(
13491 PartialDiagnosticAt(
13492 OpLoc, PDiag(diag::err_ovl_deleted_oper)
13493 << getOperatorSpelling(Best->Function->getDeclName()
13494 .getCXXOverloadedOperator())
13495 << Args[0]->getSourceRange()
13496 << Args[1]->getSourceRange()),
13497 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13498 OpLoc);
13499 return ExprError();
13500 }
13501
13502 // We matched a built-in operator; build it.
13503 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13504}
13505
13506ExprResult Sema::BuildSynthesizedThreeWayComparison(
13507 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13508 FunctionDecl *DefaultedFn) {
13509 const ComparisonCategoryInfo *Info =
13510 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13511 // If we're not producing a known comparison category type, we can't
13512 // synthesize a three-way comparison. Let the caller diagnose this.
13513 if (!Info)
13514 return ExprResult((Expr*)nullptr);
13515
13516 // If we ever want to perform this synthesis more generally, we will need to
13517 // apply the temporary materialization conversion to the operands.
13518 assert(LHS->isGLValue() && RHS->isGLValue() &&((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13519, __PRETTY_FUNCTION__))
13519 "cannot use prvalue expressions more than once")((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13519, __PRETTY_FUNCTION__))
;
13520 Expr *OrigLHS = LHS;
13521 Expr *OrigRHS = RHS;
13522
13523 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13524 // each of them multiple times below.
13525 LHS = new (Context)
13526 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13527 LHS->getObjectKind(), LHS);
13528 RHS = new (Context)
13529 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13530 RHS->getObjectKind(), RHS);
13531
13532 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13533 DefaultedFn);
13534 if (Eq.isInvalid())
13535 return ExprError();
13536
13537 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13538 true, DefaultedFn);
13539 if (Less.isInvalid())
13540 return ExprError();
13541
13542 ExprResult Greater;
13543 if (Info->isPartial()) {
13544 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13545 DefaultedFn);
13546 if (Greater.isInvalid())
13547 return ExprError();
13548 }
13549
13550 // Form the list of comparisons we're going to perform.
13551 struct Comparison {
13552 ExprResult Cmp;
13553 ComparisonCategoryResult Result;
13554 } Comparisons[4] =
13555 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13556 : ComparisonCategoryResult::Equivalent},
13557 {Less, ComparisonCategoryResult::Less},
13558 {Greater, ComparisonCategoryResult::Greater},
13559 {ExprResult(), ComparisonCategoryResult::Unordered},
13560 };
13561
13562 int I = Info->isPartial() ? 3 : 2;
13563
13564 // Combine the comparisons with suitable conditional expressions.
13565 ExprResult Result;
13566 for (; I >= 0; --I) {
13567 // Build a reference to the comparison category constant.
13568 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13569 // FIXME: Missing a constant for a comparison category. Diagnose this?
13570 if (!VI)
13571 return ExprResult((Expr*)nullptr);
13572 ExprResult ThisResult =
13573 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13574 if (ThisResult.isInvalid())
13575 return ExprError();
13576
13577 // Build a conditional unless this is the final case.
13578 if (Result.get()) {
13579 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13580 ThisResult.get(), Result.get());
13581 if (Result.isInvalid())
13582 return ExprError();
13583 } else {
13584 Result = ThisResult;
13585 }
13586 }
13587
13588 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13589 // bind the OpaqueValueExprs before they're (repeatedly) used.
13590 Expr *SyntacticForm = new (Context)
13591 BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13592 Result.get()->getValueKind(),
13593 Result.get()->getObjectKind(), OpLoc, FPFeatures);
13594 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13595 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13596}
13597
13598ExprResult
13599Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13600 SourceLocation RLoc,
13601 Expr *Base, Expr *Idx) {
13602 Expr *Args[2] = { Base, Idx };
13603 DeclarationName OpName =
13604 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13605
13606 // If either side is type-dependent, create an appropriate dependent
13607 // expression.
13608 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13609
13610 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13611 // CHECKME: no 'operator' keyword?
13612 DeclarationNameInfo OpNameInfo(OpName, LLoc);
13613 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13614 UnresolvedLookupExpr *Fn
13615 = UnresolvedLookupExpr::Create(Context, NamingClass,
13616 NestedNameSpecifierLoc(), OpNameInfo,
13617 /*ADL*/ true, /*Overloaded*/ false,
13618 UnresolvedSetIterator(),
13619 UnresolvedSetIterator());
13620 // Can't add any actual overloads yet
13621
13622 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13623 Context.DependentTy, VK_RValue, RLoc,
13624 FPOptions());
13625 }
13626
13627 // Handle placeholders on both operands.
13628 if (checkPlaceholderForOverload(*this, Args[0]))
13629 return ExprError();
13630 if (checkPlaceholderForOverload(*this, Args[1]))
13631 return ExprError();
13632
13633 // Build an empty overload set.
13634 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13635
13636 // Subscript can only be overloaded as a member function.
13637
13638 // Add operator candidates that are member functions.
13639 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13640
13641 // Add builtin operator candidates.
13642 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13643
13644 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13645
13646 // Perform overload resolution.
13647 OverloadCandidateSet::iterator Best;
13648 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13649 case OR_Success: {
13650 // We found a built-in operator or an overloaded operator.
13651 FunctionDecl *FnDecl = Best->Function;
13652
13653 if (FnDecl) {
13654 // We matched an overloaded operator. Build a call to that
13655 // operator.
13656
13657 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13658
13659 // Convert the arguments.
13660 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13661 ExprResult Arg0 =
13662 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13663 Best->FoundDecl, Method);
13664 if (Arg0.isInvalid())
13665 return ExprError();
13666 Args[0] = Arg0.get();
13667
13668 // Convert the arguments.
13669 ExprResult InputInit
13670 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13671 Context,
13672 FnDecl->getParamDecl(0)),
13673 SourceLocation(),
13674 Args[1]);
13675 if (InputInit.isInvalid())
13676 return ExprError();
13677
13678 Args[1] = InputInit.getAs<Expr>();
13679
13680 // Build the actual expression node.
13681 DeclarationNameInfo OpLocInfo(OpName, LLoc);
13682 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13683 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13684 Best->FoundDecl,
13685 Base,
13686 HadMultipleCandidates,
13687 OpLocInfo.getLoc(),
13688 OpLocInfo.getInfo());
13689 if (FnExpr.isInvalid())
13690 return ExprError();
13691
13692 // Determine the result type
13693 QualType ResultTy = FnDecl->getReturnType();
13694 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13695 ResultTy = ResultTy.getNonLValueExprType(Context);
13696
13697 CXXOperatorCallExpr *TheCall =
13698 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13699 Args, ResultTy, VK, RLoc, FPOptions());
13700
13701 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13702 return ExprError();
13703
13704 if (CheckFunctionCall(Method, TheCall,
13705 Method->getType()->castAs<FunctionProtoType>()))
13706 return ExprError();
13707
13708 return MaybeBindToTemporary(TheCall);
13709 } else {
13710 // We matched a built-in operator. Convert the arguments, then
13711 // break out so that we will build the appropriate built-in
13712 // operator node.
13713 ExprResult ArgsRes0 = PerformImplicitConversion(
13714 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13715 AA_Passing, CCK_ForBuiltinOverloadedOp);
13716 if (ArgsRes0.isInvalid())
13717 return ExprError();
13718 Args[0] = ArgsRes0.get();
13719
13720 ExprResult ArgsRes1 = PerformImplicitConversion(
13721 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13722 AA_Passing, CCK_ForBuiltinOverloadedOp);
13723 if (ArgsRes1.isInvalid())
13724 return ExprError();
13725 Args[1] = ArgsRes1.get();
13726
13727 break;
13728 }
13729 }
13730
13731 case OR_No_Viable_Function: {
13732 PartialDiagnostic PD = CandidateSet.empty()
13733 ? (PDiag(diag::err_ovl_no_oper)
13734 << Args[0]->getType() << /*subscript*/ 0
13735 << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13736 : (PDiag(diag::err_ovl_no_viable_subscript)
13737 << Args[0]->getType() << Args[0]->getSourceRange()
13738 << Args[1]->getSourceRange());
13739 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13740 OCD_AllCandidates, Args, "[]", LLoc);
13741 return ExprError();
13742 }
13743
13744 case OR_Ambiguous:
13745 CandidateSet.NoteCandidates(
13746 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13747 << "[]" << Args[0]->getType()
13748 << Args[1]->getType()
13749 << Args[0]->getSourceRange()
13750 << Args[1]->getSourceRange()),
13751 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13752 return ExprError();
13753
13754 case OR_Deleted:
13755 CandidateSet.NoteCandidates(
13756 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13757 << "[]" << Args[0]->getSourceRange()
13758 << Args[1]->getSourceRange()),
13759 *this, OCD_AllCandidates, Args, "[]", LLoc);
13760 return ExprError();
13761 }
13762
13763 // We matched a built-in operator; build it.
13764 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13765}
13766
13767/// BuildCallToMemberFunction - Build a call to a member
13768/// function. MemExpr is the expression that refers to the member
13769/// function (and includes the object parameter), Args/NumArgs are the
13770/// arguments to the function call (not including the object
13771/// parameter). The caller needs to validate that the member
13772/// expression refers to a non-static member function or an overloaded
13773/// member function.
13774ExprResult
13775Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13776 SourceLocation LParenLoc,
13777 MultiExprArg Args,
13778 SourceLocation RParenLoc) {
13779 assert(MemExprE->getType() == Context.BoundMemberTy ||((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13780, __PRETTY_FUNCTION__))
13780 MemExprE->getType() == Context.OverloadTy)((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13780, __PRETTY_FUNCTION__))
;
13781
13782 // Dig out the member expression. This holds both the object
13783 // argument and the member function we're referring to.
13784 Expr *NakedMemExpr = MemExprE->IgnoreParens();
13785
13786 // Determine whether this is a call to a pointer-to-member function.
13787 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13788 assert(op->getType() == Context.BoundMemberTy)((op->getType() == Context.BoundMemberTy) ? static_cast<
void> (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13788, __PRETTY_FUNCTION__))
;
13789 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)((op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI
) ? static_cast<void> (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13789, __PRETTY_FUNCTION__))
;
13790
13791 QualType fnType =
13792 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13793
13794 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13795 QualType resultType = proto->getCallResultType(Context);
13796 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13797
13798 // Check that the object type isn't more qualified than the
13799 // member function we're calling.
13800 Qualifiers funcQuals = proto->getMethodQuals();
13801
13802 QualType objectType = op->getLHS()->getType();
13803 if (op->getOpcode() == BO_PtrMemI)
13804 objectType = objectType->castAs<PointerType>()->getPointeeType();
13805 Qualifiers objectQuals = objectType.getQualifiers();
13806
13807 Qualifiers difference = objectQuals - funcQuals;
13808 difference.removeObjCGCAttr();
13809 difference.removeAddressSpace();
13810 if (difference) {
13811 std::string qualsString = difference.getAsString();
13812 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13813 << fnType.getUnqualifiedType()
13814 << qualsString
13815 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13816 }
13817
13818 CXXMemberCallExpr *call =
13819 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13820 valueKind, RParenLoc, proto->getNumParams());
13821
13822 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13823 call, nullptr))
13824 return ExprError();
13825
13826 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13827 return ExprError();
13828
13829 if (CheckOtherCall(call, proto))
13830 return ExprError();
13831
13832 return MaybeBindToTemporary(call);
13833 }
13834
13835 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13836 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13837 RParenLoc);
13838
13839 UnbridgedCastsSet UnbridgedCasts;
13840 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13841 return ExprError();
13842
13843 MemberExpr *MemExpr;
13844 CXXMethodDecl *Method = nullptr;
13845 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13846 NestedNameSpecifier *Qualifier = nullptr;
13847 if (isa<MemberExpr>(NakedMemExpr)) {
13848 MemExpr = cast<MemberExpr>(NakedMemExpr);
13849 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13850 FoundDecl = MemExpr->getFoundDecl();
13851 Qualifier = MemExpr->getQualifier();
13852 UnbridgedCasts.restore();
13853 } else {
13854 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13855 Qualifier = UnresExpr->getQualifier();
13856
13857 QualType ObjectType = UnresExpr->getBaseType();
13858 Expr::Classification ObjectClassification
13859 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13860 : UnresExpr->getBase()->Classify(Context);
13861
13862 // Add overload candidates
13863 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13864 OverloadCandidateSet::CSK_Normal);
13865
13866 // FIXME: avoid copy.
13867 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13868 if (UnresExpr->hasExplicitTemplateArgs()) {
13869 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13870 TemplateArgs = &TemplateArgsBuffer;
13871 }
13872
13873 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13874 E = UnresExpr->decls_end(); I != E; ++I) {
13875
13876 NamedDecl *Func = *I;
13877 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13878 if (isa<UsingShadowDecl>(Func))
13879 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13880
13881
13882 // Microsoft supports direct constructor calls.
13883 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13884 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13885 CandidateSet,
13886 /*SuppressUserConversions*/ false);
13887 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13888 // If explicit template arguments were provided, we can't call a
13889 // non-template member function.
13890 if (TemplateArgs)
13891 continue;
13892
13893 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13894 ObjectClassification, Args, CandidateSet,
13895 /*SuppressUserConversions=*/false);
13896 } else {
13897 AddMethodTemplateCandidate(
13898 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13899 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13900 /*SuppressUserConversions=*/false);
13901 }
13902 }
13903
13904 DeclarationName DeclName = UnresExpr->getMemberName();
13905
13906 UnbridgedCasts.restore();
13907
13908 OverloadCandidateSet::iterator Best;
13909 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13910 Best)) {
13911 case OR_Success:
13912 Method = cast<CXXMethodDecl>(Best->Function);
13913 FoundDecl = Best->FoundDecl;
13914 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13915 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13916 return ExprError();
13917 // If FoundDecl is different from Method (such as if one is a template
13918 // and the other a specialization), make sure DiagnoseUseOfDecl is
13919 // called on both.
13920 // FIXME: This would be more comprehensively addressed by modifying
13921 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13922 // being used.
13923 if (Method != FoundDecl.getDecl() &&
13924 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13925 return ExprError();
13926 break;
13927
13928 case OR_No_Viable_Function:
13929 CandidateSet.NoteCandidates(
13930 PartialDiagnosticAt(
13931 UnresExpr->getMemberLoc(),
13932 PDiag(diag::err_ovl_no_viable_member_function_in_call)
13933 << DeclName << MemExprE->getSourceRange()),
13934 *this, OCD_AllCandidates, Args);
13935 // FIXME: Leaking incoming expressions!
13936 return ExprError();
13937
13938 case OR_Ambiguous:
13939 CandidateSet.NoteCandidates(
13940 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13941 PDiag(diag::err_ovl_ambiguous_member_call)
13942 << DeclName << MemExprE->getSourceRange()),
13943 *this, OCD_AmbiguousCandidates, Args);
13944 // FIXME: Leaking incoming expressions!
13945 return ExprError();
13946
13947 case OR_Deleted:
13948 CandidateSet.NoteCandidates(
13949 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13950 PDiag(diag::err_ovl_deleted_member_call)
13951 << DeclName << MemExprE->getSourceRange()),
13952 *this, OCD_AllCandidates, Args);
13953 // FIXME: Leaking incoming expressions!
13954 return ExprError();
13955 }
13956
13957 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13958
13959 // If overload resolution picked a static member, build a
13960 // non-member call based on that function.
13961 if (Method->isStatic()) {
13962 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13963 RParenLoc);
13964 }
13965
13966 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13967 }
13968
13969 QualType ResultType = Method->getReturnType();
13970 ExprValueKind VK = Expr::getValueKindForType(ResultType);
13971 ResultType = ResultType.getNonLValueExprType(Context);
13972
13973 assert(Method && "Member call to something that isn't a method?")((Method && "Member call to something that isn't a method?"
) ? static_cast<void> (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13973, __PRETTY_FUNCTION__))
;
13974 const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13975 CXXMemberCallExpr *TheCall =
13976 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13977 RParenLoc, Proto->getNumParams());
13978
13979 // Check for a valid return type.
13980 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13981 TheCall, Method))
13982 return ExprError();
13983
13984 // Convert the object argument (for a non-static member function call).
13985 // We only need to do this if there was actually an overload; otherwise
13986 // it was done at lookup.
13987 if (!Method->isStatic()) {
13988 ExprResult ObjectArg =
13989 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13990 FoundDecl, Method);
13991 if (ObjectArg.isInvalid())
13992 return ExprError();
13993 MemExpr->setBase(ObjectArg.get());
13994 }
13995
13996 // Convert the rest of the arguments
13997 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13998 RParenLoc))
13999 return ExprError();
14000
14001 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14002
14003 if (CheckFunctionCall(Method, TheCall, Proto))
14004 return ExprError();
14005
14006 // In the case the method to call was not selected by the overloading
14007 // resolution process, we still need to handle the enable_if attribute. Do
14008 // that here, so it will not hide previous -- and more relevant -- errors.
14009 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14010 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
14011 Diag(MemE->getMemberLoc(),
14012 diag::err_ovl_no_viable_member_function_in_call)
14013 << Method << Method->getSourceRange();
14014 Diag(Method->getLocation(),
14015 diag::note_ovl_candidate_disabled_by_function_cond_attr)
14016 << Attr->getCond()->getSourceRange() << Attr->getMessage();
14017 return ExprError();
14018 }
14019 }
14020
14021 if ((isa<CXXConstructorDecl>(CurContext) ||
14022 isa<CXXDestructorDecl>(CurContext)) &&
14023 TheCall->getMethodDecl()->isPure()) {
14024 const CXXMethodDecl *MD = TheCall->getMethodDecl();
14025
14026 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14027 MemExpr->performsVirtualDispatch(getLangOpts())) {
14028 Diag(MemExpr->getBeginLoc(),
14029 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14030 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14031 << MD->getParent()->getDeclName();
14032
14033 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14034 if (getLangOpts().AppleKext)
14035 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14036 << MD->getParent()->getDeclName() << MD->getDeclName();
14037 }
14038 }
14039
14040 if (CXXDestructorDecl *DD =
14041 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14042 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14043 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14044 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14045 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14046 MemExpr->getMemberLoc());
14047 }
14048
14049 return MaybeBindToTemporary(TheCall);
14050}
14051
14052/// BuildCallToObjectOfClassType - Build a call to an object of class
14053/// type (C++ [over.call.object]), which can end up invoking an
14054/// overloaded function call operator (@c operator()) or performing a
14055/// user-defined conversion on the object argument.
14056ExprResult
14057Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14058 SourceLocation LParenLoc,
14059 MultiExprArg Args,
14060 SourceLocation RParenLoc) {
14061 if (checkPlaceholderForOverload(*this, Obj))
14062 return ExprError();
14063 ExprResult Object = Obj;
14064
14065 UnbridgedCastsSet UnbridgedCasts;
14066 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14067 return ExprError();
14068
14069 assert(Object.get()->getType()->isRecordType() &&((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14070, __PRETTY_FUNCTION__))
14070 "Requires object type argument")((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14070, __PRETTY_FUNCTION__))
;
14071 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
14072
14073 // C++ [over.call.object]p1:
14074 // If the primary-expression E in the function call syntax
14075 // evaluates to a class object of type "cv T", then the set of
14076 // candidate functions includes at least the function call
14077 // operators of T. The function call operators of T are obtained by
14078 // ordinary lookup of the name operator() in the context of
14079 // (E).operator().
14080 OverloadCandidateSet CandidateSet(LParenLoc,
14081 OverloadCandidateSet::CSK_Operator);
14082 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14083
14084 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14085 diag::err_incomplete_object_call, Object.get()))
14086 return true;
14087
14088 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14089 LookupQualifiedName(R, Record->getDecl());
14090 R.suppressDiagnostics();
14091
14092 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14093 Oper != OperEnd; ++Oper) {
14094 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14095 Object.get()->Classify(Context), Args, CandidateSet,
14096 /*SuppressUserConversion=*/false);
14097 }
14098
14099 // C++ [over.call.object]p2:
14100 // In addition, for each (non-explicit in C++0x) conversion function
14101 // declared in T of the form
14102 //
14103 // operator conversion-type-id () cv-qualifier;
14104 //
14105 // where cv-qualifier is the same cv-qualification as, or a
14106 // greater cv-qualification than, cv, and where conversion-type-id
14107 // denotes the type "pointer to function of (P1,...,Pn) returning
14108 // R", or the type "reference to pointer to function of
14109 // (P1,...,Pn) returning R", or the type "reference to function
14110 // of (P1,...,Pn) returning R", a surrogate call function [...]
14111 // is also considered as a candidate function. Similarly,
14112 // surrogate call functions are added to the set of candidate
14113 // functions for each conversion function declared in an
14114 // accessible base class provided the function is not hidden
14115 // within T by another intervening declaration.
14116 const auto &Conversions =
14117 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14118 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14119 NamedDecl *D = *I;
14120 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14121 if (isa<UsingShadowDecl>(D))
14122 D = cast<UsingShadowDecl>(D)->getTargetDecl();
14123
14124 // Skip over templated conversion functions; they aren't
14125 // surrogates.
14126 if (isa<FunctionTemplateDecl>(D))
14127 continue;
14128
14129 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14130 if (!Conv->isExplicit()) {
14131 // Strip the reference type (if any) and then the pointer type (if
14132 // any) to get down to what might be a function type.
14133 QualType ConvType = Conv->getConversionType().getNonReferenceType();
14134 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14135 ConvType = ConvPtrType->getPointeeType();
14136
14137 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14138 {
14139 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14140 Object.get(), Args, CandidateSet);
14141 }
14142 }
14143 }
14144
14145 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14146
14147 // Perform overload resolution.
14148 OverloadCandidateSet::iterator Best;
14149 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14150 Best)) {
14151 case OR_Success:
14152 // Overload resolution succeeded; we'll build the appropriate call
14153 // below.
14154 break;
14155
14156 case OR_No_Viable_Function: {
14157 PartialDiagnostic PD =
14158 CandidateSet.empty()
14159 ? (PDiag(diag::err_ovl_no_oper)
14160 << Object.get()->getType() << /*call*/ 1
14161 << Object.get()->getSourceRange())
14162 : (PDiag(diag::err_ovl_no_viable_object_call)
14163 << Object.get()->getType() << Object.get()->getSourceRange());
14164 CandidateSet.NoteCandidates(
14165 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14166 OCD_AllCandidates, Args);
14167 break;
14168 }
14169 case OR_Ambiguous:
14170 CandidateSet.NoteCandidates(
14171 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14172 PDiag(diag::err_ovl_ambiguous_object_call)
14173 << Object.get()->getType()
14174 << Object.get()->getSourceRange()),
14175 *this, OCD_AmbiguousCandidates, Args);
14176 break;
14177
14178 case OR_Deleted:
14179 CandidateSet.NoteCandidates(
14180 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14181 PDiag(diag::err_ovl_deleted_object_call)
14182 << Object.get()->getType()
14183 << Object.get()->getSourceRange()),
14184 *this, OCD_AllCandidates, Args);
14185 break;
14186 }
14187
14188 if (Best == CandidateSet.end())
14189 return true;
14190
14191 UnbridgedCasts.restore();
14192
14193 if (Best->Function == nullptr) {
14194 // Since there is no function declaration, this is one of the
14195 // surrogate candidates. Dig out the conversion function.
14196 CXXConversionDecl *Conv
14197 = cast<CXXConversionDecl>(
14198 Best->Conversions[0].UserDefined.ConversionFunction);
14199
14200 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14201 Best->FoundDecl);
14202 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14203 return ExprError();
14204 assert(Conv == Best->FoundDecl.getDecl() &&((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14205, __PRETTY_FUNCTION__))
14205 "Found Decl & conversion-to-functionptr should be same, right?!")((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14205, __PRETTY_FUNCTION__))
;
14206 // We selected one of the surrogate functions that converts the
14207 // object parameter to a function pointer. Perform the conversion
14208 // on the object argument, then let BuildCallExpr finish the job.
14209
14210 // Create an implicit member expr to refer to the conversion operator.
14211 // and then call it.
14212 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14213 Conv, HadMultipleCandidates);
14214 if (Call.isInvalid())
14215 return ExprError();
14216 // Record usage of conversion in an implicit cast.
14217 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14218 CK_UserDefinedConversion, Call.get(),
14219 nullptr, VK_RValue);
14220
14221 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14222 }
14223
14224 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14225
14226 // We found an overloaded operator(). Build a CXXOperatorCallExpr
14227 // that calls this method, using Object for the implicit object
14228 // parameter and passing along the remaining arguments.
14229 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14230
14231 // An error diagnostic has already been printed when parsing the declaration.
14232 if (Method->isInvalidDecl())
14233 return ExprError();
14234
14235 const FunctionProtoType *Proto =
14236 Method->getType()->getAs<FunctionProtoType>();
14237
14238 unsigned NumParams = Proto->getNumParams();
14239
14240 DeclarationNameInfo OpLocInfo(
14241 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14242 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14243 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14244 Obj, HadMultipleCandidates,
14245 OpLocInfo.getLoc(),
14246 OpLocInfo.getInfo());
14247 if (NewFn.isInvalid())
14248 return true;
14249
14250 // The number of argument slots to allocate in the call. If we have default
14251 // arguments we need to allocate space for them as well. We additionally
14252 // need one more slot for the object parameter.
14253 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14254
14255 // Build the full argument list for the method call (the implicit object
14256 // parameter is placed at the beginning of the list).
14257 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14258
14259 bool IsError = false;
14260
14261 // Initialize the implicit object parameter.
14262 ExprResult ObjRes =
14263 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14264 Best->FoundDecl, Method);
14265 if (ObjRes.isInvalid())
14266 IsError = true;
14267 else
14268 Object = ObjRes;
14269 MethodArgs[0] = Object.get();
14270
14271 // Check the argument types.
14272 for (unsigned i = 0; i != NumParams; i++) {
14273 Expr *Arg;
14274 if (i < Args.size()) {
14275 Arg = Args[i];
14276
14277 // Pass the argument.
14278
14279 ExprResult InputInit
14280 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14281 Context,
14282 Method->getParamDecl(i)),
14283 SourceLocation(), Arg);
14284
14285 IsError |= InputInit.isInvalid();
14286 Arg = InputInit.getAs<Expr>();
14287 } else {
14288 ExprResult DefArg
14289 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14290 if (DefArg.isInvalid()) {
14291 IsError = true;
14292 break;
14293 }
14294
14295 Arg = DefArg.getAs<Expr>();
14296 }
14297
14298 MethodArgs[i + 1] = Arg;
14299 }
14300
14301 // If this is a variadic call, handle args passed through "...".
14302 if (Proto->isVariadic()) {
14303 // Promote the arguments (C99 6.5.2.2p7).
14304 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14305 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14306 nullptr);
14307 IsError |= Arg.isInvalid();
14308 MethodArgs[i + 1] = Arg.get();
14309 }
14310 }
14311
14312 if (IsError)
14313 return true;
14314
14315 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14316
14317 // Once we've built TheCall, all of the expressions are properly owned.
14318 QualType ResultTy = Method->getReturnType();
14319 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14320 ResultTy = ResultTy.getNonLValueExprType(Context);
14321
14322 CXXOperatorCallExpr *TheCall =
14323 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14324 ResultTy, VK, RParenLoc, FPOptions());
14325
14326 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14327 return true;
14328
14329 if (CheckFunctionCall(Method, TheCall, Proto))
14330 return true;
14331
14332 return MaybeBindToTemporary(TheCall);
14333}
14334
14335/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14336/// (if one exists), where @c Base is an expression of class type and
14337/// @c Member is the name of the member we're trying to find.
14338ExprResult
14339Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14340 bool *NoArrowOperatorFound) {
14341 assert(Base->getType()->isRecordType() &&((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14342, __PRETTY_FUNCTION__))
14342 "left-hand side must have class type")((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14342, __PRETTY_FUNCTION__))
;
14343
14344 if (checkPlaceholderForOverload(*this, Base))
14345 return ExprError();
14346
14347 SourceLocation Loc = Base->getExprLoc();
14348
14349 // C++ [over.ref]p1:
14350 //
14351 // [...] An expression x->m is interpreted as (x.operator->())->m
14352 // for a class object x of type T if T::operator->() exists and if
14353 // the operator is selected as the best match function by the
14354 // overload resolution mechanism (13.3).
14355 DeclarationName OpName =
14356 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14357 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14358 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
14359
14360 if (RequireCompleteType(Loc, Base->getType(),
14361 diag::err_typecheck_incomplete_tag, Base))
14362 return ExprError();
14363
14364 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14365 LookupQualifiedName(R, BaseRecord->getDecl());
14366 R.suppressDiagnostics();
14367
14368 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14369 Oper != OperEnd; ++Oper) {
14370 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14371 None, CandidateSet, /*SuppressUserConversion=*/false);
14372 }
14373
14374 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14375
14376 // Perform overload resolution.
14377 OverloadCandidateSet::iterator Best;
14378 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14379 case OR_Success:
14380 // Overload resolution succeeded; we'll build the call below.
14381 break;
14382
14383 case OR_No_Viable_Function: {
14384 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14385 if (CandidateSet.empty()) {
14386 QualType BaseType = Base->getType();
14387 if (NoArrowOperatorFound) {
14388 // Report this specific error to the caller instead of emitting a
14389 // diagnostic, as requested.
14390 *NoArrowOperatorFound = true;
14391 return ExprError();
14392 }
14393 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14394 << BaseType << Base->getSourceRange();
14395 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14396 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14397 << FixItHint::CreateReplacement(OpLoc, ".");
14398 }
14399 } else
14400 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14401 << "operator->" << Base->getSourceRange();
14402 CandidateSet.NoteCandidates(*this, Base, Cands);
14403 return ExprError();
14404 }
14405 case OR_Ambiguous:
14406 CandidateSet.NoteCandidates(
14407 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14408 << "->" << Base->getType()
14409 << Base->getSourceRange()),
14410 *this, OCD_AmbiguousCandidates, Base);
14411 return ExprError();
14412
14413 case OR_Deleted:
14414 CandidateSet.NoteCandidates(
14415 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14416 << "->" << Base->getSourceRange()),
14417 *this, OCD_AllCandidates, Base);
14418 return ExprError();
14419 }
14420
14421 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14422
14423 // Convert the object parameter.
14424 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14425 ExprResult BaseResult =
14426 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14427 Best->FoundDecl, Method);
14428 if (BaseResult.isInvalid())
14429 return ExprError();
14430 Base = BaseResult.get();
14431
14432 // Build the operator call.
14433 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14434 Base, HadMultipleCandidates, OpLoc);
14435 if (FnExpr.isInvalid())
14436 return ExprError();
14437
14438 QualType ResultTy = Method->getReturnType();
14439 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14440 ResultTy = ResultTy.getNonLValueExprType(Context);
14441 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14442 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14443
14444 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14445 return ExprError();
14446
14447 if (CheckFunctionCall(Method, TheCall,
14448 Method->getType()->castAs<FunctionProtoType>()))
14449 return ExprError();
14450
14451 return MaybeBindToTemporary(TheCall);
14452}
14453
14454/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14455/// a literal operator described by the provided lookup results.
14456ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14457 DeclarationNameInfo &SuffixInfo,
14458 ArrayRef<Expr*> Args,
14459 SourceLocation LitEndLoc,
14460 TemplateArgumentListInfo *TemplateArgs) {
14461 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14462
14463 OverloadCandidateSet CandidateSet(UDSuffixLoc,
14464 OverloadCandidateSet::CSK_Normal);
14465 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14466 TemplateArgs);
14467
14468 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14469
14470 // Perform overload resolution. This will usually be trivial, but might need
14471 // to perform substitutions for a literal operator template.
14472 OverloadCandidateSet::iterator Best;
14473 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14474 case OR_Success:
14475 case OR_Deleted:
14476 break;
14477
14478 case OR_No_Viable_Function:
14479 CandidateSet.NoteCandidates(
14480 PartialDiagnosticAt(UDSuffixLoc,
14481 PDiag(diag::err_ovl_no_viable_function_in_call)
14482 << R.getLookupName()),
14483 *this, OCD_AllCandidates, Args);
14484 return ExprError();
14485
14486 case OR_Ambiguous:
14487 CandidateSet.NoteCandidates(
14488 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14489 << R.getLookupName()),
14490 *this, OCD_AmbiguousCandidates, Args);
14491 return ExprError();
14492 }
14493
14494 FunctionDecl *FD = Best->Function;
14495 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14496 nullptr, HadMultipleCandidates,
14497 SuffixInfo.getLoc(),
14498 SuffixInfo.getInfo());
14499 if (Fn.isInvalid())
14500 return true;
14501
14502 // Check the argument types. This should almost always be a no-op, except
14503 // that array-to-pointer decay is applied to string literals.
14504 Expr *ConvArgs[2];
14505 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14506 ExprResult InputInit = PerformCopyInitialization(
14507 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14508 SourceLocation(), Args[ArgIdx]);
14509 if (InputInit.isInvalid())
14510 return true;
14511 ConvArgs[ArgIdx] = InputInit.get();
14512 }
14513
14514 QualType ResultTy = FD->getReturnType();
14515 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14516 ResultTy = ResultTy.getNonLValueExprType(Context);
14517
14518 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14519 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14520 VK, LitEndLoc, UDSuffixLoc);
14521
14522 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14523 return ExprError();
14524
14525 if (CheckFunctionCall(FD, UDL, nullptr))
14526 return ExprError();
14527
14528 return MaybeBindToTemporary(UDL);
14529}
14530
14531/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14532/// given LookupResult is non-empty, it is assumed to describe a member which
14533/// will be invoked. Otherwise, the function will be found via argument
14534/// dependent lookup.
14535/// CallExpr is set to a valid expression and FRS_Success returned on success,
14536/// otherwise CallExpr is set to ExprError() and some non-success value
14537/// is returned.
14538Sema::ForRangeStatus
14539Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14540 SourceLocation RangeLoc,
14541 const DeclarationNameInfo &NameInfo,
14542 LookupResult &MemberLookup,
14543 OverloadCandidateSet *CandidateSet,
14544 Expr *Range, ExprResult *CallExpr) {
14545 Scope *S = nullptr;
14546
14547 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14548 if (!MemberLookup.empty()) {
14549 ExprResult MemberRef =
14550 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14551 /*IsPtr=*/false, CXXScopeSpec(),
14552 /*TemplateKWLoc=*/SourceLocation(),
14553 /*FirstQualifierInScope=*/nullptr,
14554 MemberLookup,
14555 /*TemplateArgs=*/nullptr, S);
14556 if (MemberRef.isInvalid()) {
14557 *CallExpr = ExprError();
14558 return FRS_DiagnosticIssued;
14559 }
14560 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14561 if (CallExpr->isInvalid()) {
14562 *CallExpr = ExprError();
14563 return FRS_DiagnosticIssued;
14564 }
14565 } else {
14566 UnresolvedSet<0> FoundNames;
14567 UnresolvedLookupExpr *Fn =
14568 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14569 NestedNameSpecifierLoc(), NameInfo,
14570 /*NeedsADL=*/true, /*Overloaded=*/false,
14571 FoundNames.begin(), FoundNames.end());
14572
14573 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14574 CandidateSet, CallExpr);
14575 if (CandidateSet->empty() || CandidateSetError) {
14576 *CallExpr = ExprError();
14577 return FRS_NoViableFunction;
14578 }
14579 OverloadCandidateSet::iterator Best;
14580 OverloadingResult OverloadResult =
14581 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14582
14583 if (OverloadResult == OR_No_Viable_Function) {
14584 *CallExpr = ExprError();
14585 return FRS_NoViableFunction;
14586 }
14587 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14588 Loc, nullptr, CandidateSet, &Best,
14589 OverloadResult,
14590 /*AllowTypoCorrection=*/false);
14591 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14592 *CallExpr = ExprError();
14593 return FRS_DiagnosticIssued;
14594 }
14595 }
14596 return FRS_Success;
14597}
14598
14599
14600/// FixOverloadedFunctionReference - E is an expression that refers to
14601/// a C++ overloaded function (possibly with some parentheses and
14602/// perhaps a '&' around it). We have resolved the overloaded function
14603/// to the function declaration Fn, so patch up the expression E to
14604/// refer (possibly indirectly) to Fn. Returns the new expr.
14605Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14606 FunctionDecl *Fn) {
14607 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14608 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14609 Found, Fn);
14610 if (SubExpr == PE->getSubExpr())
14611 return PE;
14612
14613 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14614 }
14615
14616 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14617 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14618 Found, Fn);
14619 assert(Context.hasSameType(ICE->getSubExpr()->getType(),((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14621, __PRETTY_FUNCTION__))
14620 SubExpr->getType()) &&((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14621, __PRETTY_FUNCTION__))
14621 "Implicit cast type cannot be determined from overload")((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14621, __PRETTY_FUNCTION__))
;
14622 assert(ICE->path_empty() && "fixing up hierarchy conversion?")((ICE->path_empty() && "fixing up hierarchy conversion?"
) ? static_cast<void> (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14622, __PRETTY_FUNCTION__))
;
14623 if (SubExpr == ICE->getSubExpr())
14624 return ICE;
14625
14626 return ImplicitCastExpr::Create(Context, ICE->getType(),
14627 ICE->getCastKind(),
14628 SubExpr, nullptr,
14629 ICE->getValueKind());
14630 }
14631
14632 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14633 if (!GSE->isResultDependent()) {
14634 Expr *SubExpr =
14635 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14636 if (SubExpr == GSE->getResultExpr())
14637 return GSE;
14638
14639 // Replace the resulting type information before rebuilding the generic
14640 // selection expression.
14641 ArrayRef<Expr *> A = GSE->getAssocExprs();
14642 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14643 unsigned ResultIdx = GSE->getResultIndex();
14644 AssocExprs[ResultIdx] = SubExpr;
14645
14646 return GenericSelectionExpr::Create(
14647 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14648 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14649 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14650 ResultIdx);
14651 }
14652 // Rather than fall through to the unreachable, return the original generic
14653 // selection expression.
14654 return GSE;
14655 }
14656
14657 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14658 assert(UnOp->getOpcode() == UO_AddrOf &&((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14659, __PRETTY_FUNCTION__))
14659 "Can only take the address of an overloaded function")((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14659, __PRETTY_FUNCTION__))
;
14660 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14661 if (Method->isStatic()) {
14662 // Do nothing: static member functions aren't any different
14663 // from non-member functions.
14664 } else {
14665 // Fix the subexpression, which really has to be an
14666 // UnresolvedLookupExpr holding an overloaded member function
14667 // or template.
14668 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14669 Found, Fn);
14670 if (SubExpr == UnOp->getSubExpr())
14671 return UnOp;
14672
14673 assert(isa<DeclRefExpr>(SubExpr)((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14674, __PRETTY_FUNCTION__))
14674 && "fixed to something other than a decl ref")((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14674, __PRETTY_FUNCTION__))
;
14675 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14676, __PRETTY_FUNCTION__))
14676 && "fixed to a member ref with no nested name qualifier")((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14676, __PRETTY_FUNCTION__))
;
14677
14678 // We have taken the address of a pointer to member
14679 // function. Perform the computation here so that we get the
14680 // appropriate pointer to member type.
14681 QualType ClassType
14682 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14683 QualType MemPtrType
14684 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14685 // Under the MS ABI, lock down the inheritance model now.
14686 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14687 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14688
14689 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14690 VK_RValue, OK_Ordinary,
14691 UnOp->getOperatorLoc(), false);
14692 }
14693 }
14694 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14695 Found, Fn);
14696 if (SubExpr == UnOp->getSubExpr())
14697 return UnOp;
14698
14699 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14700 Context.getPointerType(SubExpr->getType()),
14701 VK_RValue, OK_Ordinary,
14702 UnOp->getOperatorLoc(), false);
14703 }
14704
14705 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14706 // FIXME: avoid copy.
14707 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14708 if (ULE->hasExplicitTemplateArgs()) {
14709 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14710 TemplateArgs = &TemplateArgsBuffer;
14711 }
14712
14713 DeclRefExpr *DRE =
14714 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14715 ULE->getQualifierLoc(), Found.getDecl(),
14716 ULE->getTemplateKeywordLoc(), TemplateArgs);
14717 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14718 return DRE;
14719 }
14720
14721 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14722 // FIXME: avoid copy.
14723 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14724 if (MemExpr->hasExplicitTemplateArgs()) {
14725 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14726 TemplateArgs = &TemplateArgsBuffer;
14727 }
14728
14729 Expr *Base;
14730
14731 // If we're filling in a static method where we used to have an
14732 // implicit member access, rewrite to a simple decl ref.
14733 if (MemExpr->isImplicitAccess()) {
14734 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14735 DeclRefExpr *DRE = BuildDeclRefExpr(
14736 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14737 MemExpr->getQualifierLoc(), Found.getDecl(),
14738 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14739 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14740 return DRE;
14741 } else {
14742 SourceLocation Loc = MemExpr->getMemberLoc();
14743 if (MemExpr->getQualifier())
14744 Loc = MemExpr->getQualifierLoc().getBeginLoc();
14745 Base =
14746 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14747 }
14748 } else
14749 Base = MemExpr->getBase();
14750
14751 ExprValueKind valueKind;
14752 QualType type;
14753 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14754 valueKind = VK_LValue;
14755 type = Fn->getType();
14756 } else {
14757 valueKind = VK_RValue;
14758 type = Context.BoundMemberTy;
14759 }
14760
14761 return BuildMemberExpr(
14762 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14763 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14764 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14765 type, valueKind, OK_Ordinary, TemplateArgs);
14766 }
14767
14768 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14768)
;
14769}
14770
14771ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14772 DeclAccessPair Found,
14773 FunctionDecl *Fn) {
14774 return FixOverloadedFunctionReference(E.get(), Found, Fn);
14775}

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