Bug Summary

File:clang/include/clang/Sema/Sema.h
Warning:line 2138, column 12
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp

1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/CXXInheritance.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/DependenceFlags.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeOrdering.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/DiagnosticOptions.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Basic/SourceManager.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
32#include "llvm/ADT/DenseSet.h"
33#include "llvm/ADT/Optional.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/SmallPtrSet.h"
36#include "llvm/ADT/SmallString.h"
37#include <algorithm>
38#include <cstdlib>
39
40using namespace clang;
41using namespace sema;
42
43using AllowedExplicit = Sema::AllowedExplicit;
44
45static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47 return P->hasAttr<PassObjectSizeAttr>();
48 });
49}
50
51/// A convenience routine for creating a decayed reference to a function.
52static ExprResult
53CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
54 const Expr *Base, bool HadMultipleCandidates,
55 SourceLocation Loc = SourceLocation(),
56 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
57 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
58 return ExprError();
59 // If FoundDecl is different from Fn (such as if one is a template
60 // and the other a specialization), make sure DiagnoseUseOfDecl is
61 // called on both.
62 // FIXME: This would be more comprehensively addressed by modifying
63 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
64 // being used.
65 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
66 return ExprError();
67 DeclRefExpr *DRE = new (S.Context)
68 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
69 if (HadMultipleCandidates)
70 DRE->setHadMultipleCandidates(true);
71
72 S.MarkDeclRefReferenced(DRE, Base);
73 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
74 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
75 S.ResolveExceptionSpec(Loc, FPT);
76 DRE->setType(Fn->getType());
77 }
78 }
79 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
80 CK_FunctionToPointerDecay);
81}
82
83static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle,
87 bool AllowObjCWritebackConversion);
88
89static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
90 QualType &ToType,
91 bool InOverloadResolution,
92 StandardConversionSequence &SCS,
93 bool CStyle);
94static OverloadingResult
95IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96 UserDefinedConversionSequence& User,
97 OverloadCandidateSet& Conversions,
98 AllowedExplicit AllowExplicit,
99 bool AllowObjCConversionOnExplicit);
100
101static ImplicitConversionSequence::CompareKind
102CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
103 const StandardConversionSequence& SCS1,
104 const StandardConversionSequence& SCS2);
105
106static ImplicitConversionSequence::CompareKind
107CompareQualificationConversions(Sema &S,
108 const StandardConversionSequence& SCS1,
109 const StandardConversionSequence& SCS2);
110
111static ImplicitConversionSequence::CompareKind
112CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
113 const StandardConversionSequence& SCS1,
114 const StandardConversionSequence& SCS2);
115
116/// GetConversionRank - Retrieve the implicit conversion rank
117/// corresponding to the given implicit conversion kind.
118ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
119 static const ImplicitConversionRank
120 Rank[(int)ICK_Num_Conversion_Kinds] = {
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
124 ICR_Exact_Match,
125 ICR_Exact_Match,
126 ICR_Exact_Match,
127 ICR_Promotion,
128 ICR_Promotion,
129 ICR_Promotion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_OCL_Scalar_Widening,
142 ICR_Complex_Real_Conversion,
143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Writeback_Conversion,
146 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
147 // it was omitted by the patch that added
148 // ICK_Zero_Event_Conversion
149 ICR_C_Conversion,
150 ICR_C_Conversion_Extension
151 };
152 return Rank[(int)Kind];
153}
154
155/// GetImplicitConversionName - Return the name of this kind of
156/// implicit conversion.
157static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
159 "No conversion",
160 "Lvalue-to-rvalue",
161 "Array-to-pointer",
162 "Function-to-pointer",
163 "Function pointer conversion",
164 "Qualification",
165 "Integral promotion",
166 "Floating point promotion",
167 "Complex promotion",
168 "Integral conversion",
169 "Floating conversion",
170 "Complex conversion",
171 "Floating-integral conversion",
172 "Pointer conversion",
173 "Pointer-to-member conversion",
174 "Boolean conversion",
175 "Compatible-types conversion",
176 "Derived-to-base conversion",
177 "Vector conversion",
178 "SVE Vector conversion",
179 "Vector splat",
180 "Complex-real conversion",
181 "Block Pointer conversion",
182 "Transparent Union Conversion",
183 "Writeback conversion",
184 "OpenCL Zero Event Conversion",
185 "C specific type conversion",
186 "Incompatible pointer conversion"
187 };
188 return Name[Kind];
189}
190
191/// StandardConversionSequence - Set the standard conversion
192/// sequence to the identity conversion.
193void StandardConversionSequence::setAsIdentityConversion() {
194 First = ICK_Identity;
195 Second = ICK_Identity;
196 Third = ICK_Identity;
197 DeprecatedStringLiteralToCharPtr = false;
198 QualificationIncludesObjCLifetime = false;
199 ReferenceBinding = false;
200 DirectBinding = false;
201 IsLvalueReference = true;
202 BindsToFunctionLvalue = false;
203 BindsToRvalue = false;
204 BindsImplicitObjectArgumentWithoutRefQualifier = false;
205 ObjCLifetimeConversionBinding = false;
206 CopyConstructor = nullptr;
207}
208
209/// getRank - Retrieve the rank of this standard conversion sequence
210/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
211/// implicit conversions.
212ImplicitConversionRank StandardConversionSequence::getRank() const {
213 ImplicitConversionRank Rank = ICR_Exact_Match;
214 if (GetConversionRank(First) > Rank)
215 Rank = GetConversionRank(First);
216 if (GetConversionRank(Second) > Rank)
217 Rank = GetConversionRank(Second);
218 if (GetConversionRank(Third) > Rank)
219 Rank = GetConversionRank(Third);
220 return Rank;
221}
222
223/// isPointerConversionToBool - Determines whether this conversion is
224/// a conversion of a pointer or pointer-to-member to bool. This is
225/// used as part of the ranking of standard conversion sequences
226/// (C++ 13.3.3.2p4).
227bool StandardConversionSequence::isPointerConversionToBool() const {
228 // Note that FromType has not necessarily been transformed by the
229 // array-to-pointer or function-to-pointer implicit conversions, so
230 // check for their presence as well as checking whether FromType is
231 // a pointer.
232 if (getToType(1)->isBooleanType() &&
233 (getFromType()->isPointerType() ||
234 getFromType()->isMemberPointerType() ||
235 getFromType()->isObjCObjectPointerType() ||
236 getFromType()->isBlockPointerType() ||
237 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
238 return true;
239
240 return false;
241}
242
243/// isPointerConversionToVoidPointer - Determines whether this
244/// conversion is a conversion of a pointer to a void pointer. This is
245/// used as part of the ranking of standard conversion sequences (C++
246/// 13.3.3.2p4).
247bool
248StandardConversionSequence::
249isPointerConversionToVoidPointer(ASTContext& Context) const {
250 QualType FromType = getFromType();
251 QualType ToType = getToType(1);
252
253 // Note that FromType has not necessarily been transformed by the
254 // array-to-pointer implicit conversion, so check for its presence
255 // and redo the conversion to get a pointer.
256 if (First == ICK_Array_To_Pointer)
257 FromType = Context.getArrayDecayedType(FromType);
258
259 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
260 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
261 return ToPtrType->getPointeeType()->isVoidType();
262
263 return false;
264}
265
266/// Skip any implicit casts which could be either part of a narrowing conversion
267/// or after one in an implicit conversion.
268static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
269 const Expr *Converted) {
270 // We can have cleanups wrapping the converted expression; these need to be
271 // preserved so that destructors run if necessary.
272 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
273 Expr *Inner =
274 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
275 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
276 EWC->getObjects());
277 }
278
279 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280 switch (ICE->getCastKind()) {
281 case CK_NoOp:
282 case CK_IntegralCast:
283 case CK_IntegralToBoolean:
284 case CK_IntegralToFloating:
285 case CK_BooleanToSignedIntegral:
286 case CK_FloatingToIntegral:
287 case CK_FloatingToBoolean:
288 case CK_FloatingCast:
289 Converted = ICE->getSubExpr();
290 continue;
291
292 default:
293 return Converted;
294 }
295 }
296
297 return Converted;
298}
299
300/// Check if this standard conversion sequence represents a narrowing
301/// conversion, according to C++11 [dcl.init.list]p7.
302///
303/// \param Ctx The AST context.
304/// \param Converted The result of applying this standard conversion sequence.
305/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
306/// value of the expression prior to the narrowing conversion.
307/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
308/// type of the expression prior to the narrowing conversion.
309/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
310/// from floating point types to integral types should be ignored.
311NarrowingKind StandardConversionSequence::getNarrowingKind(
312 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
313 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
314 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")((Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"
) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 314, __PRETTY_FUNCTION__))
;
315
316 // C++11 [dcl.init.list]p7:
317 // A narrowing conversion is an implicit conversion ...
318 QualType FromType = getToType(0);
319 QualType ToType = getToType(1);
320
321 // A conversion to an enumeration type is narrowing if the conversion to
322 // the underlying type is narrowing. This only arises for expressions of
323 // the form 'Enum{init}'.
324 if (auto *ET = ToType->getAs<EnumType>())
325 ToType = ET->getDecl()->getIntegerType();
326
327 switch (Second) {
328 // 'bool' is an integral type; dispatch to the right place to handle it.
329 case ICK_Boolean_Conversion:
330 if (FromType->isRealFloatingType())
331 goto FloatingIntegralConversion;
332 if (FromType->isIntegralOrUnscopedEnumerationType())
333 goto IntegralConversion;
334 // -- from a pointer type or pointer-to-member type to bool, or
335 return NK_Type_Narrowing;
336
337 // -- from a floating-point type to an integer type, or
338 //
339 // -- from an integer type or unscoped enumeration type to a floating-point
340 // type, except where the source is a constant expression and the actual
341 // value after conversion will fit into the target type and will produce
342 // the original value when converted back to the original type, or
343 case ICK_Floating_Integral:
344 FloatingIntegralConversion:
345 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
346 return NK_Type_Narrowing;
347 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
348 ToType->isRealFloatingType()) {
349 if (IgnoreFloatToIntegralConversion)
350 return NK_Not_Narrowing;
351 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
352 assert(Initializer && "Unknown conversion expression")((Initializer && "Unknown conversion expression") ? static_cast
<void> (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 352, __PRETTY_FUNCTION__))
;
353
354 // If it's value-dependent, we can't tell whether it's narrowing.
355 if (Initializer->isValueDependent())
356 return NK_Dependent_Narrowing;
357
358 if (Optional<llvm::APSInt> IntConstantValue =
359 Initializer->getIntegerConstantExpr(Ctx)) {
360 // Convert the integer to the floating type.
361 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
362 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
363 llvm::APFloat::rmNearestTiesToEven);
364 // And back.
365 llvm::APSInt ConvertedValue = *IntConstantValue;
366 bool ignored;
367 Result.convertToInteger(ConvertedValue,
368 llvm::APFloat::rmTowardZero, &ignored);
369 // If the resulting value is different, this was a narrowing conversion.
370 if (*IntConstantValue != ConvertedValue) {
371 ConstantValue = APValue(*IntConstantValue);
372 ConstantType = Initializer->getType();
373 return NK_Constant_Narrowing;
374 }
375 } else {
376 // Variables are always narrowings.
377 return NK_Variable_Narrowing;
378 }
379 }
380 return NK_Not_Narrowing;
381
382 // -- from long double to double or float, or from double to float, except
383 // where the source is a constant expression and the actual value after
384 // conversion is within the range of values that can be represented (even
385 // if it cannot be represented exactly), or
386 case ICK_Floating_Conversion:
387 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
388 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
389 // FromType is larger than ToType.
390 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
391
392 // If it's value-dependent, we can't tell whether it's narrowing.
393 if (Initializer->isValueDependent())
394 return NK_Dependent_Narrowing;
395
396 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
397 // Constant!
398 assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail
("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 398, __PRETTY_FUNCTION__))
;
399 llvm::APFloat FloatVal = ConstantValue.getFloat();
400 // Convert the source value into the target type.
401 bool ignored;
402 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
403 Ctx.getFloatTypeSemantics(ToType),
404 llvm::APFloat::rmNearestTiesToEven, &ignored);
405 // If there was no overflow, the source value is within the range of
406 // values that can be represented.
407 if (ConvertStatus & llvm::APFloat::opOverflow) {
408 ConstantType = Initializer->getType();
409 return NK_Constant_Narrowing;
410 }
411 } else {
412 return NK_Variable_Narrowing;
413 }
414 }
415 return NK_Not_Narrowing;
416
417 // -- from an integer type or unscoped enumeration type to an integer type
418 // that cannot represent all the values of the original type, except where
419 // the source is a constant expression and the actual value after
420 // conversion will fit into the target type and will produce the original
421 // value when converted back to the original type.
422 case ICK_Integral_Conversion:
423 IntegralConversion: {
424 assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 424, __PRETTY_FUNCTION__))
;
425 assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 425, __PRETTY_FUNCTION__))
;
426 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
427 const unsigned FromWidth = Ctx.getIntWidth(FromType);
428 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
429 const unsigned ToWidth = Ctx.getIntWidth(ToType);
430
431 if (FromWidth > ToWidth ||
432 (FromWidth == ToWidth && FromSigned != ToSigned) ||
433 (FromSigned && !ToSigned)) {
434 // Not all values of FromType can be represented in ToType.
435 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
436
437 // If it's value-dependent, we can't tell whether it's narrowing.
438 if (Initializer->isValueDependent())
439 return NK_Dependent_Narrowing;
440
441 Optional<llvm::APSInt> OptInitializerValue;
442 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
443 // Such conversions on variables are always narrowing.
444 return NK_Variable_Narrowing;
445 }
446 llvm::APSInt &InitializerValue = *OptInitializerValue;
447 bool Narrowing = false;
448 if (FromWidth < ToWidth) {
449 // Negative -> unsigned is narrowing. Otherwise, more bits is never
450 // narrowing.
451 if (InitializerValue.isSigned() && InitializerValue.isNegative())
452 Narrowing = true;
453 } else {
454 // Add a bit to the InitializerValue so we don't have to worry about
455 // signed vs. unsigned comparisons.
456 InitializerValue = InitializerValue.extend(
457 InitializerValue.getBitWidth() + 1);
458 // Convert the initializer to and from the target width and signed-ness.
459 llvm::APSInt ConvertedValue = InitializerValue;
460 ConvertedValue = ConvertedValue.trunc(ToWidth);
461 ConvertedValue.setIsSigned(ToSigned);
462 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
463 ConvertedValue.setIsSigned(InitializerValue.isSigned());
464 // If the result is different, this was a narrowing conversion.
465 if (ConvertedValue != InitializerValue)
466 Narrowing = true;
467 }
468 if (Narrowing) {
469 ConstantType = Initializer->getType();
470 ConstantValue = APValue(InitializerValue);
471 return NK_Constant_Narrowing;
472 }
473 }
474 return NK_Not_Narrowing;
475 }
476
477 default:
478 // Other kinds of conversions are not narrowings.
479 return NK_Not_Narrowing;
480 }
481}
482
483/// dump - Print this standard conversion sequence to standard
484/// error. Useful for debugging overloading issues.
485LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
486 raw_ostream &OS = llvm::errs();
487 bool PrintedSomething = false;
488 if (First != ICK_Identity) {
489 OS << GetImplicitConversionName(First);
490 PrintedSomething = true;
491 }
492
493 if (Second != ICK_Identity) {
494 if (PrintedSomething) {
495 OS << " -> ";
496 }
497 OS << GetImplicitConversionName(Second);
498
499 if (CopyConstructor) {
500 OS << " (by copy constructor)";
501 } else if (DirectBinding) {
502 OS << " (direct reference binding)";
503 } else if (ReferenceBinding) {
504 OS << " (reference binding)";
505 }
506 PrintedSomething = true;
507 }
508
509 if (Third != ICK_Identity) {
510 if (PrintedSomething) {
511 OS << " -> ";
512 }
513 OS << GetImplicitConversionName(Third);
514 PrintedSomething = true;
515 }
516
517 if (!PrintedSomething) {
518 OS << "No conversions required";
519 }
520}
521
522/// dump - Print this user-defined conversion sequence to standard
523/// error. Useful for debugging overloading issues.
524void UserDefinedConversionSequence::dump() const {
525 raw_ostream &OS = llvm::errs();
526 if (Before.First || Before.Second || Before.Third) {
527 Before.dump();
528 OS << " -> ";
529 }
530 if (ConversionFunction)
531 OS << '\'' << *ConversionFunction << '\'';
532 else
533 OS << "aggregate initialization";
534 if (After.First || After.Second || After.Third) {
535 OS << " -> ";
536 After.dump();
537 }
538}
539
540/// dump - Print this implicit conversion sequence to standard
541/// error. Useful for debugging overloading issues.
542void ImplicitConversionSequence::dump() const {
543 raw_ostream &OS = llvm::errs();
544 if (isStdInitializerListElement())
545 OS << "Worst std::initializer_list element conversion: ";
546 switch (ConversionKind) {
547 case StandardConversion:
548 OS << "Standard conversion: ";
549 Standard.dump();
550 break;
551 case UserDefinedConversion:
552 OS << "User-defined conversion: ";
553 UserDefined.dump();
554 break;
555 case EllipsisConversion:
556 OS << "Ellipsis conversion";
557 break;
558 case AmbiguousConversion:
559 OS << "Ambiguous conversion";
560 break;
561 case BadConversion:
562 OS << "Bad conversion";
563 break;
564 }
565
566 OS << "\n";
567}
568
569void AmbiguousConversionSequence::construct() {
570 new (&conversions()) ConversionSet();
571}
572
573void AmbiguousConversionSequence::destruct() {
574 conversions().~ConversionSet();
575}
576
577void
578AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
579 FromTypePtr = O.FromTypePtr;
580 ToTypePtr = O.ToTypePtr;
581 new (&conversions()) ConversionSet(O.conversions());
582}
583
584namespace {
585 // Structure used by DeductionFailureInfo to store
586 // template argument information.
587 struct DFIArguments {
588 TemplateArgument FirstArg;
589 TemplateArgument SecondArg;
590 };
591 // Structure used by DeductionFailureInfo to store
592 // template parameter and template argument information.
593 struct DFIParamWithArguments : DFIArguments {
594 TemplateParameter Param;
595 };
596 // Structure used by DeductionFailureInfo to store template argument
597 // information and the index of the problematic call argument.
598 struct DFIDeducedMismatchArgs : DFIArguments {
599 TemplateArgumentList *TemplateArgs;
600 unsigned CallArgIndex;
601 };
602 // Structure used by DeductionFailureInfo to store information about
603 // unsatisfied constraints.
604 struct CNSInfo {
605 TemplateArgumentList *TemplateArgs;
606 ConstraintSatisfaction Satisfaction;
607 };
608}
609
610/// Convert from Sema's representation of template deduction information
611/// to the form used in overload-candidate information.
612DeductionFailureInfo
613clang::MakeDeductionFailureInfo(ASTContext &Context,
614 Sema::TemplateDeductionResult TDK,
615 TemplateDeductionInfo &Info) {
616 DeductionFailureInfo Result;
617 Result.Result = static_cast<unsigned>(TDK);
618 Result.HasDiagnostic = false;
619 switch (TDK) {
620 case Sema::TDK_Invalid:
621 case Sema::TDK_InstantiationDepth:
622 case Sema::TDK_TooManyArguments:
623 case Sema::TDK_TooFewArguments:
624 case Sema::TDK_MiscellaneousDeductionFailure:
625 case Sema::TDK_CUDATargetMismatch:
626 Result.Data = nullptr;
627 break;
628
629 case Sema::TDK_Incomplete:
630 case Sema::TDK_InvalidExplicitArguments:
631 Result.Data = Info.Param.getOpaqueValue();
632 break;
633
634 case Sema::TDK_DeducedMismatch:
635 case Sema::TDK_DeducedMismatchNested: {
636 // FIXME: Should allocate from normal heap so that we can free this later.
637 auto *Saved = new (Context) DFIDeducedMismatchArgs;
638 Saved->FirstArg = Info.FirstArg;
639 Saved->SecondArg = Info.SecondArg;
640 Saved->TemplateArgs = Info.take();
641 Saved->CallArgIndex = Info.CallArgIndex;
642 Result.Data = Saved;
643 break;
644 }
645
646 case Sema::TDK_NonDeducedMismatch: {
647 // FIXME: Should allocate from normal heap so that we can free this later.
648 DFIArguments *Saved = new (Context) DFIArguments;
649 Saved->FirstArg = Info.FirstArg;
650 Saved->SecondArg = Info.SecondArg;
651 Result.Data = Saved;
652 break;
653 }
654
655 case Sema::TDK_IncompletePack:
656 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
657 case Sema::TDK_Inconsistent:
658 case Sema::TDK_Underqualified: {
659 // FIXME: Should allocate from normal heap so that we can free this later.
660 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
661 Saved->Param = Info.Param;
662 Saved->FirstArg = Info.FirstArg;
663 Saved->SecondArg = Info.SecondArg;
664 Result.Data = Saved;
665 break;
666 }
667
668 case Sema::TDK_SubstitutionFailure:
669 Result.Data = Info.take();
670 if (Info.hasSFINAEDiagnostic()) {
671 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672 SourceLocation(), PartialDiagnostic::NullDiagnostic());
673 Info.takeSFINAEDiagnostic(*Diag);
674 Result.HasDiagnostic = true;
675 }
676 break;
677
678 case Sema::TDK_ConstraintsNotSatisfied: {
679 CNSInfo *Saved = new (Context) CNSInfo;
680 Saved->TemplateArgs = Info.take();
681 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
682 Result.Data = Saved;
683 break;
684 }
685
686 case Sema::TDK_Success:
687 case Sema::TDK_NonDependentConversionFailure:
688 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 688)
;
689 }
690
691 return Result;
692}
693
694void DeductionFailureInfo::Destroy() {
695 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696 case Sema::TDK_Success:
697 case Sema::TDK_Invalid:
698 case Sema::TDK_InstantiationDepth:
699 case Sema::TDK_Incomplete:
700 case Sema::TDK_TooManyArguments:
701 case Sema::TDK_TooFewArguments:
702 case Sema::TDK_InvalidExplicitArguments:
703 case Sema::TDK_CUDATargetMismatch:
704 case Sema::TDK_NonDependentConversionFailure:
705 break;
706
707 case Sema::TDK_IncompletePack:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_DeducedMismatch:
711 case Sema::TDK_DeducedMismatchNested:
712 case Sema::TDK_NonDeducedMismatch:
713 // FIXME: Destroy the data?
714 Data = nullptr;
715 break;
716
717 case Sema::TDK_SubstitutionFailure:
718 // FIXME: Destroy the template argument list?
719 Data = nullptr;
720 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721 Diag->~PartialDiagnosticAt();
722 HasDiagnostic = false;
723 }
724 break;
725
726 case Sema::TDK_ConstraintsNotSatisfied:
727 // FIXME: Destroy the template argument list?
728 Data = nullptr;
729 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730 Diag->~PartialDiagnosticAt();
731 HasDiagnostic = false;
732 }
733 break;
734
735 // Unhandled
736 case Sema::TDK_MiscellaneousDeductionFailure:
737 break;
738 }
739}
740
741PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
742 if (HasDiagnostic)
743 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
744 return nullptr;
745}
746
747TemplateParameter DeductionFailureInfo::getTemplateParameter() {
748 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
749 case Sema::TDK_Success:
750 case Sema::TDK_Invalid:
751 case Sema::TDK_InstantiationDepth:
752 case Sema::TDK_TooManyArguments:
753 case Sema::TDK_TooFewArguments:
754 case Sema::TDK_SubstitutionFailure:
755 case Sema::TDK_DeducedMismatch:
756 case Sema::TDK_DeducedMismatchNested:
757 case Sema::TDK_NonDeducedMismatch:
758 case Sema::TDK_CUDATargetMismatch:
759 case Sema::TDK_NonDependentConversionFailure:
760 case Sema::TDK_ConstraintsNotSatisfied:
761 return TemplateParameter();
762
763 case Sema::TDK_Incomplete:
764 case Sema::TDK_InvalidExplicitArguments:
765 return TemplateParameter::getFromOpaqueValue(Data);
766
767 case Sema::TDK_IncompletePack:
768 case Sema::TDK_Inconsistent:
769 case Sema::TDK_Underqualified:
770 return static_cast<DFIParamWithArguments*>(Data)->Param;
771
772 // Unhandled
773 case Sema::TDK_MiscellaneousDeductionFailure:
774 break;
775 }
776
777 return TemplateParameter();
778}
779
780TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
781 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
782 case Sema::TDK_Success:
783 case Sema::TDK_Invalid:
784 case Sema::TDK_InstantiationDepth:
785 case Sema::TDK_TooManyArguments:
786 case Sema::TDK_TooFewArguments:
787 case Sema::TDK_Incomplete:
788 case Sema::TDK_IncompletePack:
789 case Sema::TDK_InvalidExplicitArguments:
790 case Sema::TDK_Inconsistent:
791 case Sema::TDK_Underqualified:
792 case Sema::TDK_NonDeducedMismatch:
793 case Sema::TDK_CUDATargetMismatch:
794 case Sema::TDK_NonDependentConversionFailure:
795 return nullptr;
796
797 case Sema::TDK_DeducedMismatch:
798 case Sema::TDK_DeducedMismatchNested:
799 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
800
801 case Sema::TDK_SubstitutionFailure:
802 return static_cast<TemplateArgumentList*>(Data);
803
804 case Sema::TDK_ConstraintsNotSatisfied:
805 return static_cast<CNSInfo*>(Data)->TemplateArgs;
806
807 // Unhandled
808 case Sema::TDK_MiscellaneousDeductionFailure:
809 break;
810 }
811
812 return nullptr;
813}
814
815const TemplateArgument *DeductionFailureInfo::getFirstArg() {
816 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
817 case Sema::TDK_Success:
818 case Sema::TDK_Invalid:
819 case Sema::TDK_InstantiationDepth:
820 case Sema::TDK_Incomplete:
821 case Sema::TDK_TooManyArguments:
822 case Sema::TDK_TooFewArguments:
823 case Sema::TDK_InvalidExplicitArguments:
824 case Sema::TDK_SubstitutionFailure:
825 case Sema::TDK_CUDATargetMismatch:
826 case Sema::TDK_NonDependentConversionFailure:
827 case Sema::TDK_ConstraintsNotSatisfied:
828 return nullptr;
829
830 case Sema::TDK_IncompletePack:
831 case Sema::TDK_Inconsistent:
832 case Sema::TDK_Underqualified:
833 case Sema::TDK_DeducedMismatch:
834 case Sema::TDK_DeducedMismatchNested:
835 case Sema::TDK_NonDeducedMismatch:
836 return &static_cast<DFIArguments*>(Data)->FirstArg;
837
838 // Unhandled
839 case Sema::TDK_MiscellaneousDeductionFailure:
840 break;
841 }
842
843 return nullptr;
844}
845
846const TemplateArgument *DeductionFailureInfo::getSecondArg() {
847 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
848 case Sema::TDK_Success:
849 case Sema::TDK_Invalid:
850 case Sema::TDK_InstantiationDepth:
851 case Sema::TDK_Incomplete:
852 case Sema::TDK_IncompletePack:
853 case Sema::TDK_TooManyArguments:
854 case Sema::TDK_TooFewArguments:
855 case Sema::TDK_InvalidExplicitArguments:
856 case Sema::TDK_SubstitutionFailure:
857 case Sema::TDK_CUDATargetMismatch:
858 case Sema::TDK_NonDependentConversionFailure:
859 case Sema::TDK_ConstraintsNotSatisfied:
860 return nullptr;
861
862 case Sema::TDK_Inconsistent:
863 case Sema::TDK_Underqualified:
864 case Sema::TDK_DeducedMismatch:
865 case Sema::TDK_DeducedMismatchNested:
866 case Sema::TDK_NonDeducedMismatch:
867 return &static_cast<DFIArguments*>(Data)->SecondArg;
868
869 // Unhandled
870 case Sema::TDK_MiscellaneousDeductionFailure:
871 break;
872 }
873
874 return nullptr;
875}
876
877llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
878 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
879 case Sema::TDK_DeducedMismatch:
880 case Sema::TDK_DeducedMismatchNested:
881 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
882
883 default:
884 return llvm::None;
885 }
886}
887
888bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
889 OverloadedOperatorKind Op) {
890 if (!AllowRewrittenCandidates)
891 return false;
892 return Op == OO_EqualEqual || Op == OO_Spaceship;
893}
894
895bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
896 ASTContext &Ctx, const FunctionDecl *FD) {
897 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
898 return false;
899 // Don't bother adding a reversed candidate that can never be a better
900 // match than the non-reversed version.
901 return FD->getNumParams() != 2 ||
902 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
903 FD->getParamDecl(1)->getType()) ||
904 FD->hasAttr<EnableIfAttr>();
905}
906
907void OverloadCandidateSet::destroyCandidates() {
908 for (iterator i = begin(), e = end(); i != e; ++i) {
909 for (auto &C : i->Conversions)
910 C.~ImplicitConversionSequence();
911 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
912 i->DeductionFailure.Destroy();
913 }
914}
915
916void OverloadCandidateSet::clear(CandidateSetKind CSK) {
917 destroyCandidates();
918 SlabAllocator.Reset();
919 NumInlineBytesUsed = 0;
920 Candidates.clear();
921 Functions.clear();
922 Kind = CSK;
923}
924
925namespace {
926 class UnbridgedCastsSet {
927 struct Entry {
928 Expr **Addr;
929 Expr *Saved;
930 };
931 SmallVector<Entry, 2> Entries;
932
933 public:
934 void save(Sema &S, Expr *&E) {
935 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 935, __PRETTY_FUNCTION__))
;
936 Entry entry = { &E, E };
937 Entries.push_back(entry);
938 E = S.stripARCUnbridgedCast(E);
939 }
940
941 void restore() {
942 for (SmallVectorImpl<Entry>::iterator
943 i = Entries.begin(), e = Entries.end(); i != e; ++i)
944 *i->Addr = i->Saved;
945 }
946 };
947}
948
949/// checkPlaceholderForOverload - Do any interesting placeholder-like
950/// preprocessing on the given expression.
951///
952/// \param unbridgedCasts a collection to which to add unbridged casts;
953/// without this, they will be immediately diagnosed as errors
954///
955/// Return true on unrecoverable error.
956static bool
957checkPlaceholderForOverload(Sema &S, Expr *&E,
958 UnbridgedCastsSet *unbridgedCasts = nullptr) {
959 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
960 // We can't handle overloaded expressions here because overload
961 // resolution might reasonably tweak them.
962 if (placeholder->getKind() == BuiltinType::Overload) return false;
963
964 // If the context potentially accepts unbridged ARC casts, strip
965 // the unbridged cast and add it to the collection for later restoration.
966 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
967 unbridgedCasts) {
968 unbridgedCasts->save(S, E);
969 return false;
970 }
971
972 // Go ahead and check everything else.
973 ExprResult result = S.CheckPlaceholderExpr(E);
974 if (result.isInvalid())
975 return true;
976
977 E = result.get();
978 return false;
979 }
980
981 // Nothing to do.
982 return false;
983}
984
985/// checkArgPlaceholdersForOverload - Check a set of call operands for
986/// placeholders.
987static bool checkArgPlaceholdersForOverload(Sema &S,
988 MultiExprArg Args,
989 UnbridgedCastsSet &unbridged) {
990 for (unsigned i = 0, e = Args.size(); i != e; ++i)
991 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
992 return true;
993
994 return false;
995}
996
997/// Determine whether the given New declaration is an overload of the
998/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
999/// New and Old cannot be overloaded, e.g., if New has the same signature as
1000/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1001/// functions (or function templates) at all. When it does return Ovl_Match or
1002/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1003/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1004/// declaration.
1005///
1006/// Example: Given the following input:
1007///
1008/// void f(int, float); // #1
1009/// void f(int, int); // #2
1010/// int f(int, int); // #3
1011///
1012/// When we process #1, there is no previous declaration of "f", so IsOverload
1013/// will not be used.
1014///
1015/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1016/// the parameter types, we see that #1 and #2 are overloaded (since they have
1017/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1018/// unchanged.
1019///
1020/// When we process #3, Old is an overload set containing #1 and #2. We compare
1021/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1022/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1023/// functions are not part of the signature), IsOverload returns Ovl_Match and
1024/// MatchedDecl will be set to point to the FunctionDecl for #2.
1025///
1026/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1027/// by a using declaration. The rules for whether to hide shadow declarations
1028/// ignore some properties which otherwise figure into a function template's
1029/// signature.
1030Sema::OverloadKind
1031Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1032 NamedDecl *&Match, bool NewIsUsingDecl) {
1033 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1034 I != E; ++I) {
1035 NamedDecl *OldD = *I;
1036
1037 bool OldIsUsingDecl = false;
1038 if (isa<UsingShadowDecl>(OldD)) {
1039 OldIsUsingDecl = true;
1040
1041 // We can always introduce two using declarations into the same
1042 // context, even if they have identical signatures.
1043 if (NewIsUsingDecl) continue;
1044
1045 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1046 }
1047
1048 // A using-declaration does not conflict with another declaration
1049 // if one of them is hidden.
1050 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1051 continue;
1052
1053 // If either declaration was introduced by a using declaration,
1054 // we'll need to use slightly different rules for matching.
1055 // Essentially, these rules are the normal rules, except that
1056 // function templates hide function templates with different
1057 // return types or template parameter lists.
1058 bool UseMemberUsingDeclRules =
1059 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1060 !New->getFriendObjectKind();
1061
1062 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1063 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1064 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1065 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1066 continue;
1067 }
1068
1069 if (!isa<FunctionTemplateDecl>(OldD) &&
1070 !shouldLinkPossiblyHiddenDecl(*I, New))
1071 continue;
1072
1073 Match = *I;
1074 return Ovl_Match;
1075 }
1076
1077 // Builtins that have custom typechecking or have a reference should
1078 // not be overloadable or redeclarable.
1079 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1080 Match = *I;
1081 return Ovl_NonFunction;
1082 }
1083 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1084 // We can overload with these, which can show up when doing
1085 // redeclaration checks for UsingDecls.
1086 assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast<
void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1086, __PRETTY_FUNCTION__))
;
1087 } else if (isa<TagDecl>(OldD)) {
1088 // We can always overload with tags by hiding them.
1089 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1090 // Optimistically assume that an unresolved using decl will
1091 // overload; if it doesn't, we'll have to diagnose during
1092 // template instantiation.
1093 //
1094 // Exception: if the scope is dependent and this is not a class
1095 // member, the using declaration can only introduce an enumerator.
1096 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1097 Match = *I;
1098 return Ovl_NonFunction;
1099 }
1100 } else {
1101 // (C++ 13p1):
1102 // Only function declarations can be overloaded; object and type
1103 // declarations cannot be overloaded.
1104 Match = *I;
1105 return Ovl_NonFunction;
1106 }
1107 }
1108
1109 // C++ [temp.friend]p1:
1110 // For a friend function declaration that is not a template declaration:
1111 // -- if the name of the friend is a qualified or unqualified template-id,
1112 // [...], otherwise
1113 // -- if the name of the friend is a qualified-id and a matching
1114 // non-template function is found in the specified class or namespace,
1115 // the friend declaration refers to that function, otherwise,
1116 // -- if the name of the friend is a qualified-id and a matching function
1117 // template is found in the specified class or namespace, the friend
1118 // declaration refers to the deduced specialization of that function
1119 // template, otherwise
1120 // -- the name shall be an unqualified-id [...]
1121 // If we get here for a qualified friend declaration, we've just reached the
1122 // third bullet. If the type of the friend is dependent, skip this lookup
1123 // until instantiation.
1124 if (New->getFriendObjectKind() && New->getQualifier() &&
1125 !New->getDescribedFunctionTemplate() &&
1126 !New->getDependentSpecializationInfo() &&
1127 !New->getType()->isDependentType()) {
1128 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1129 TemplateSpecResult.addAllDecls(Old);
1130 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1131 /*QualifiedFriend*/true)) {
1132 New->setInvalidDecl();
1133 return Ovl_Overload;
1134 }
1135
1136 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1137 return Ovl_Match;
1138 }
1139
1140 return Ovl_Overload;
1141}
1142
1143bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1144 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1145 bool ConsiderRequiresClauses) {
1146 // C++ [basic.start.main]p2: This function shall not be overloaded.
1147 if (New->isMain())
1148 return false;
1149
1150 // MSVCRT user defined entry points cannot be overloaded.
1151 if (New->isMSVCRTEntryPoint())
1152 return false;
1153
1154 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1155 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1156
1157 // C++ [temp.fct]p2:
1158 // A function template can be overloaded with other function templates
1159 // and with normal (non-template) functions.
1160 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1161 return true;
1162
1163 // Is the function New an overload of the function Old?
1164 QualType OldQType = Context.getCanonicalType(Old->getType());
1165 QualType NewQType = Context.getCanonicalType(New->getType());
1166
1167 // Compare the signatures (C++ 1.3.10) of the two functions to
1168 // determine whether they are overloads. If we find any mismatch
1169 // in the signature, they are overloads.
1170
1171 // If either of these functions is a K&R-style function (no
1172 // prototype), then we consider them to have matching signatures.
1173 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1174 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1175 return false;
1176
1177 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1178 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1179
1180 // The signature of a function includes the types of its
1181 // parameters (C++ 1.3.10), which includes the presence or absence
1182 // of the ellipsis; see C++ DR 357).
1183 if (OldQType != NewQType &&
1184 (OldType->getNumParams() != NewType->getNumParams() ||
1185 OldType->isVariadic() != NewType->isVariadic() ||
1186 !FunctionParamTypesAreEqual(OldType, NewType)))
1187 return true;
1188
1189 // C++ [temp.over.link]p4:
1190 // The signature of a function template consists of its function
1191 // signature, its return type and its template parameter list. The names
1192 // of the template parameters are significant only for establishing the
1193 // relationship between the template parameters and the rest of the
1194 // signature.
1195 //
1196 // We check the return type and template parameter lists for function
1197 // templates first; the remaining checks follow.
1198 //
1199 // However, we don't consider either of these when deciding whether
1200 // a member introduced by a shadow declaration is hidden.
1201 if (!UseMemberUsingDeclRules && NewTemplate &&
1202 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1203 OldTemplate->getTemplateParameters(),
1204 false, TPL_TemplateMatch) ||
1205 !Context.hasSameType(Old->getDeclaredReturnType(),
1206 New->getDeclaredReturnType())))
1207 return true;
1208
1209 // If the function is a class member, its signature includes the
1210 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1211 //
1212 // As part of this, also check whether one of the member functions
1213 // is static, in which case they are not overloads (C++
1214 // 13.1p2). While not part of the definition of the signature,
1215 // this check is important to determine whether these functions
1216 // can be overloaded.
1217 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1218 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1219 if (OldMethod && NewMethod &&
1220 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1221 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1222 if (!UseMemberUsingDeclRules &&
1223 (OldMethod->getRefQualifier() == RQ_None ||
1224 NewMethod->getRefQualifier() == RQ_None)) {
1225 // C++0x [over.load]p2:
1226 // - Member function declarations with the same name and the same
1227 // parameter-type-list as well as member function template
1228 // declarations with the same name, the same parameter-type-list, and
1229 // the same template parameter lists cannot be overloaded if any of
1230 // them, but not all, have a ref-qualifier (8.3.5).
1231 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1232 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1233 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1234 }
1235 return true;
1236 }
1237
1238 // We may not have applied the implicit const for a constexpr member
1239 // function yet (because we haven't yet resolved whether this is a static
1240 // or non-static member function). Add it now, on the assumption that this
1241 // is a redeclaration of OldMethod.
1242 auto OldQuals = OldMethod->getMethodQualifiers();
1243 auto NewQuals = NewMethod->getMethodQualifiers();
1244 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1245 !isa<CXXConstructorDecl>(NewMethod))
1246 NewQuals.addConst();
1247 // We do not allow overloading based off of '__restrict'.
1248 OldQuals.removeRestrict();
1249 NewQuals.removeRestrict();
1250 if (OldQuals != NewQuals)
1251 return true;
1252 }
1253
1254 // Though pass_object_size is placed on parameters and takes an argument, we
1255 // consider it to be a function-level modifier for the sake of function
1256 // identity. Either the function has one or more parameters with
1257 // pass_object_size or it doesn't.
1258 if (functionHasPassObjectSizeParams(New) !=
1259 functionHasPassObjectSizeParams(Old))
1260 return true;
1261
1262 // enable_if attributes are an order-sensitive part of the signature.
1263 for (specific_attr_iterator<EnableIfAttr>
1264 NewI = New->specific_attr_begin<EnableIfAttr>(),
1265 NewE = New->specific_attr_end<EnableIfAttr>(),
1266 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1267 OldE = Old->specific_attr_end<EnableIfAttr>();
1268 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1269 if (NewI == NewE || OldI == OldE)
1270 return true;
1271 llvm::FoldingSetNodeID NewID, OldID;
1272 NewI->getCond()->Profile(NewID, Context, true);
1273 OldI->getCond()->Profile(OldID, Context, true);
1274 if (NewID != OldID)
1275 return true;
1276 }
1277
1278 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1279 // Don't allow overloading of destructors. (In theory we could, but it
1280 // would be a giant change to clang.)
1281 if (!isa<CXXDestructorDecl>(New)) {
1282 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1283 OldTarget = IdentifyCUDATarget(Old);
1284 if (NewTarget != CFT_InvalidTarget) {
1285 assert((OldTarget != CFT_InvalidTarget) &&(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1286, __PRETTY_FUNCTION__))
1286 "Unexpected invalid target.")(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1286, __PRETTY_FUNCTION__))
;
1287
1288 // Allow overloading of functions with same signature and different CUDA
1289 // target attributes.
1290 if (NewTarget != OldTarget)
1291 return true;
1292 }
1293 }
1294 }
1295
1296 if (ConsiderRequiresClauses) {
1297 Expr *NewRC = New->getTrailingRequiresClause(),
1298 *OldRC = Old->getTrailingRequiresClause();
1299 if ((NewRC != nullptr) != (OldRC != nullptr))
1300 // RC are most certainly different - these are overloads.
1301 return true;
1302
1303 if (NewRC) {
1304 llvm::FoldingSetNodeID NewID, OldID;
1305 NewRC->Profile(NewID, Context, /*Canonical=*/true);
1306 OldRC->Profile(OldID, Context, /*Canonical=*/true);
1307 if (NewID != OldID)
1308 // RCs are not equivalent - these are overloads.
1309 return true;
1310 }
1311 }
1312
1313 // The signatures match; this is not an overload.
1314 return false;
1315}
1316
1317/// Tries a user-defined conversion from From to ToType.
1318///
1319/// Produces an implicit conversion sequence for when a standard conversion
1320/// is not an option. See TryImplicitConversion for more information.
1321static ImplicitConversionSequence
1322TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1323 bool SuppressUserConversions,
1324 AllowedExplicit AllowExplicit,
1325 bool InOverloadResolution,
1326 bool CStyle,
1327 bool AllowObjCWritebackConversion,
1328 bool AllowObjCConversionOnExplicit) {
1329 ImplicitConversionSequence ICS;
1330
1331 if (SuppressUserConversions) {
1332 // We're not in the case above, so there is no conversion that
1333 // we can perform.
1334 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1335 return ICS;
1336 }
1337
1338 // Attempt user-defined conversion.
1339 OverloadCandidateSet Conversions(From->getExprLoc(),
1340 OverloadCandidateSet::CSK_Normal);
1341 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1342 Conversions, AllowExplicit,
1343 AllowObjCConversionOnExplicit)) {
1344 case OR_Success:
1345 case OR_Deleted:
1346 ICS.setUserDefined();
1347 // C++ [over.ics.user]p4:
1348 // A conversion of an expression of class type to the same class
1349 // type is given Exact Match rank, and a conversion of an
1350 // expression of class type to a base class of that type is
1351 // given Conversion rank, in spite of the fact that a copy
1352 // constructor (i.e., a user-defined conversion function) is
1353 // called for those cases.
1354 if (CXXConstructorDecl *Constructor
1355 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1356 QualType FromCanon
1357 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1358 QualType ToCanon
1359 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1360 if (Constructor->isCopyConstructor() &&
1361 (FromCanon == ToCanon ||
1362 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1363 // Turn this into a "standard" conversion sequence, so that it
1364 // gets ranked with standard conversion sequences.
1365 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1366 ICS.setStandard();
1367 ICS.Standard.setAsIdentityConversion();
1368 ICS.Standard.setFromType(From->getType());
1369 ICS.Standard.setAllToTypes(ToType);
1370 ICS.Standard.CopyConstructor = Constructor;
1371 ICS.Standard.FoundCopyConstructor = Found;
1372 if (ToCanon != FromCanon)
1373 ICS.Standard.Second = ICK_Derived_To_Base;
1374 }
1375 }
1376 break;
1377
1378 case OR_Ambiguous:
1379 ICS.setAmbiguous();
1380 ICS.Ambiguous.setFromType(From->getType());
1381 ICS.Ambiguous.setToType(ToType);
1382 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1383 Cand != Conversions.end(); ++Cand)
1384 if (Cand->Best)
1385 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1386 break;
1387
1388 // Fall through.
1389 case OR_No_Viable_Function:
1390 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1391 break;
1392 }
1393
1394 return ICS;
1395}
1396
1397/// TryImplicitConversion - Attempt to perform an implicit conversion
1398/// from the given expression (Expr) to the given type (ToType). This
1399/// function returns an implicit conversion sequence that can be used
1400/// to perform the initialization. Given
1401///
1402/// void f(float f);
1403/// void g(int i) { f(i); }
1404///
1405/// this routine would produce an implicit conversion sequence to
1406/// describe the initialization of f from i, which will be a standard
1407/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1408/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1409//
1410/// Note that this routine only determines how the conversion can be
1411/// performed; it does not actually perform the conversion. As such,
1412/// it will not produce any diagnostics if no conversion is available,
1413/// but will instead return an implicit conversion sequence of kind
1414/// "BadConversion".
1415///
1416/// If @p SuppressUserConversions, then user-defined conversions are
1417/// not permitted.
1418/// If @p AllowExplicit, then explicit user-defined conversions are
1419/// permitted.
1420///
1421/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1422/// writeback conversion, which allows __autoreleasing id* parameters to
1423/// be initialized with __strong id* or __weak id* arguments.
1424static ImplicitConversionSequence
1425TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1426 bool SuppressUserConversions,
1427 AllowedExplicit AllowExplicit,
1428 bool InOverloadResolution,
1429 bool CStyle,
1430 bool AllowObjCWritebackConversion,
1431 bool AllowObjCConversionOnExplicit) {
1432 ImplicitConversionSequence ICS;
1433 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1434 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1435 ICS.setStandard();
1436 return ICS;
1437 }
1438
1439 if (!S.getLangOpts().CPlusPlus) {
1440 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1441 return ICS;
1442 }
1443
1444 // C++ [over.ics.user]p4:
1445 // A conversion of an expression of class type to the same class
1446 // type is given Exact Match rank, and a conversion of an
1447 // expression of class type to a base class of that type is
1448 // given Conversion rank, in spite of the fact that a copy/move
1449 // constructor (i.e., a user-defined conversion function) is
1450 // called for those cases.
1451 QualType FromType = From->getType();
1452 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1453 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1454 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1455 ICS.setStandard();
1456 ICS.Standard.setAsIdentityConversion();
1457 ICS.Standard.setFromType(FromType);
1458 ICS.Standard.setAllToTypes(ToType);
1459
1460 // We don't actually check at this point whether there is a valid
1461 // copy/move constructor, since overloading just assumes that it
1462 // exists. When we actually perform initialization, we'll find the
1463 // appropriate constructor to copy the returned object, if needed.
1464 ICS.Standard.CopyConstructor = nullptr;
1465
1466 // Determine whether this is considered a derived-to-base conversion.
1467 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1468 ICS.Standard.Second = ICK_Derived_To_Base;
1469
1470 return ICS;
1471 }
1472
1473 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1474 AllowExplicit, InOverloadResolution, CStyle,
1475 AllowObjCWritebackConversion,
1476 AllowObjCConversionOnExplicit);
1477}
1478
1479ImplicitConversionSequence
1480Sema::TryImplicitConversion(Expr *From, QualType ToType,
1481 bool SuppressUserConversions,
1482 AllowedExplicit AllowExplicit,
1483 bool InOverloadResolution,
1484 bool CStyle,
1485 bool AllowObjCWritebackConversion) {
1486 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1487 AllowExplicit, InOverloadResolution, CStyle,
1488 AllowObjCWritebackConversion,
1489 /*AllowObjCConversionOnExplicit=*/false);
1490}
1491
1492/// PerformImplicitConversion - Perform an implicit conversion of the
1493/// expression From to the type ToType. Returns the
1494/// converted expression. Flavor is the kind of conversion we're
1495/// performing, used in the error message. If @p AllowExplicit,
1496/// explicit user-defined conversions are permitted.
1497ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1498 AssignmentAction Action,
1499 bool AllowExplicit) {
1500 if (checkPlaceholderForOverload(*this, From))
1501 return ExprError();
1502
1503 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1504 bool AllowObjCWritebackConversion
1505 = getLangOpts().ObjCAutoRefCount &&
1506 (Action == AA_Passing || Action == AA_Sending);
1507 if (getLangOpts().ObjC)
1508 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1509 From->getType(), From);
1510 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1511 *this, From, ToType,
1512 /*SuppressUserConversions=*/false,
1513 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1514 /*InOverloadResolution=*/false,
1515 /*CStyle=*/false, AllowObjCWritebackConversion,
1516 /*AllowObjCConversionOnExplicit=*/false);
1517 return PerformImplicitConversion(From, ToType, ICS, Action);
1518}
1519
1520/// Determine whether the conversion from FromType to ToType is a valid
1521/// conversion that strips "noexcept" or "noreturn" off the nested function
1522/// type.
1523bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1524 QualType &ResultTy) {
1525 if (Context.hasSameUnqualifiedType(FromType, ToType))
1526 return false;
1527
1528 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1529 // or F(t noexcept) -> F(t)
1530 // where F adds one of the following at most once:
1531 // - a pointer
1532 // - a member pointer
1533 // - a block pointer
1534 // Changes here need matching changes in FindCompositePointerType.
1535 CanQualType CanTo = Context.getCanonicalType(ToType);
1536 CanQualType CanFrom = Context.getCanonicalType(FromType);
1537 Type::TypeClass TyClass = CanTo->getTypeClass();
1538 if (TyClass != CanFrom->getTypeClass()) return false;
1539 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1540 if (TyClass == Type::Pointer) {
1541 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1542 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1543 } else if (TyClass == Type::BlockPointer) {
1544 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1545 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1546 } else if (TyClass == Type::MemberPointer) {
1547 auto ToMPT = CanTo.castAs<MemberPointerType>();
1548 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1549 // A function pointer conversion cannot change the class of the function.
1550 if (ToMPT->getClass() != FromMPT->getClass())
1551 return false;
1552 CanTo = ToMPT->getPointeeType();
1553 CanFrom = FromMPT->getPointeeType();
1554 } else {
1555 return false;
1556 }
1557
1558 TyClass = CanTo->getTypeClass();
1559 if (TyClass != CanFrom->getTypeClass()) return false;
1560 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1561 return false;
1562 }
1563
1564 const auto *FromFn = cast<FunctionType>(CanFrom);
1565 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1566
1567 const auto *ToFn = cast<FunctionType>(CanTo);
1568 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1569
1570 bool Changed = false;
1571
1572 // Drop 'noreturn' if not present in target type.
1573 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1574 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1575 Changed = true;
1576 }
1577
1578 // Drop 'noexcept' if not present in target type.
1579 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1580 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1581 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1582 FromFn = cast<FunctionType>(
1583 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1584 EST_None)
1585 .getTypePtr());
1586 Changed = true;
1587 }
1588
1589 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1590 // only if the ExtParameterInfo lists of the two function prototypes can be
1591 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1592 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1593 bool CanUseToFPT, CanUseFromFPT;
1594 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1595 CanUseFromFPT, NewParamInfos) &&
1596 CanUseToFPT && !CanUseFromFPT) {
1597 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1598 ExtInfo.ExtParameterInfos =
1599 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1600 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1601 FromFPT->getParamTypes(), ExtInfo);
1602 FromFn = QT->getAs<FunctionType>();
1603 Changed = true;
1604 }
1605 }
1606
1607 if (!Changed)
1608 return false;
1609
1610 assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void>
(0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1610, __PRETTY_FUNCTION__))
;
1611 if (QualType(FromFn, 0) != CanTo) return false;
1612
1613 ResultTy = ToType;
1614 return true;
1615}
1616
1617/// Determine whether the conversion from FromType to ToType is a valid
1618/// vector conversion.
1619///
1620/// \param ICK Will be set to the vector conversion kind, if this is a vector
1621/// conversion.
1622static bool IsVectorConversion(Sema &S, QualType FromType,
1623 QualType ToType, ImplicitConversionKind &ICK) {
1624 // We need at least one of these types to be a vector type to have a vector
1625 // conversion.
1626 if (!ToType->isVectorType() && !FromType->isVectorType())
1627 return false;
1628
1629 // Identical types require no conversions.
1630 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1631 return false;
1632
1633 // There are no conversions between extended vector types, only identity.
1634 if (ToType->isExtVectorType()) {
1635 // There are no conversions between extended vector types other than the
1636 // identity conversion.
1637 if (FromType->isExtVectorType())
1638 return false;
1639
1640 // Vector splat from any arithmetic type to a vector.
1641 if (FromType->isArithmeticType()) {
1642 ICK = ICK_Vector_Splat;
1643 return true;
1644 }
1645 }
1646
1647 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1648 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1649 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1650 ICK = ICK_SVE_Vector_Conversion;
1651 return true;
1652 }
1653
1654 // We can perform the conversion between vector types in the following cases:
1655 // 1)vector types are equivalent AltiVec and GCC vector types
1656 // 2)lax vector conversions are permitted and the vector types are of the
1657 // same size
1658 // 3)the destination type does not have the ARM MVE strict-polymorphism
1659 // attribute, which inhibits lax vector conversion for overload resolution
1660 // only
1661 if (ToType->isVectorType() && FromType->isVectorType()) {
1662 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1663 (S.isLaxVectorConversion(FromType, ToType) &&
1664 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1665 ICK = ICK_Vector_Conversion;
1666 return true;
1667 }
1668 }
1669
1670 return false;
1671}
1672
1673static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1674 bool InOverloadResolution,
1675 StandardConversionSequence &SCS,
1676 bool CStyle);
1677
1678/// IsStandardConversion - Determines whether there is a standard
1679/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1680/// expression From to the type ToType. Standard conversion sequences
1681/// only consider non-class types; for conversions that involve class
1682/// types, use TryImplicitConversion. If a conversion exists, SCS will
1683/// contain the standard conversion sequence required to perform this
1684/// conversion and this routine will return true. Otherwise, this
1685/// routine will return false and the value of SCS is unspecified.
1686static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1687 bool InOverloadResolution,
1688 StandardConversionSequence &SCS,
1689 bool CStyle,
1690 bool AllowObjCWritebackConversion) {
1691 QualType FromType = From->getType();
1692
1693 // Standard conversions (C++ [conv])
1694 SCS.setAsIdentityConversion();
1695 SCS.IncompatibleObjC = false;
1696 SCS.setFromType(FromType);
1697 SCS.CopyConstructor = nullptr;
1698
1699 // There are no standard conversions for class types in C++, so
1700 // abort early. When overloading in C, however, we do permit them.
1701 if (S.getLangOpts().CPlusPlus &&
1702 (FromType->isRecordType() || ToType->isRecordType()))
1703 return false;
1704
1705 // The first conversion can be an lvalue-to-rvalue conversion,
1706 // array-to-pointer conversion, or function-to-pointer conversion
1707 // (C++ 4p1).
1708
1709 if (FromType == S.Context.OverloadTy) {
1710 DeclAccessPair AccessPair;
1711 if (FunctionDecl *Fn
1712 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1713 AccessPair)) {
1714 // We were able to resolve the address of the overloaded function,
1715 // so we can convert to the type of that function.
1716 FromType = Fn->getType();
1717 SCS.setFromType(FromType);
1718
1719 // we can sometimes resolve &foo<int> regardless of ToType, so check
1720 // if the type matches (identity) or we are converting to bool
1721 if (!S.Context.hasSameUnqualifiedType(
1722 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1723 QualType resultTy;
1724 // if the function type matches except for [[noreturn]], it's ok
1725 if (!S.IsFunctionConversion(FromType,
1726 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1727 // otherwise, only a boolean conversion is standard
1728 if (!ToType->isBooleanType())
1729 return false;
1730 }
1731
1732 // Check if the "from" expression is taking the address of an overloaded
1733 // function and recompute the FromType accordingly. Take advantage of the
1734 // fact that non-static member functions *must* have such an address-of
1735 // expression.
1736 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1737 if (Method && !Method->isStatic()) {
1738 assert(isa<UnaryOperator>(From->IgnoreParens()) &&((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1739, __PRETTY_FUNCTION__))
1739 "Non-unary operator on non-static member address")((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1739, __PRETTY_FUNCTION__))
;
1740 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1742, __PRETTY_FUNCTION__))
1741 == UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1742, __PRETTY_FUNCTION__))
1742 "Non-address-of operator on non-static member address")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1742, __PRETTY_FUNCTION__))
;
1743 const Type *ClassType
1744 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1745 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1746 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1747 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1749, __PRETTY_FUNCTION__))
1748 UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1749, __PRETTY_FUNCTION__))
1749 "Non-address-of operator for overloaded function expression")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1749, __PRETTY_FUNCTION__))
;
1750 FromType = S.Context.getPointerType(FromType);
1751 }
1752
1753 // Check that we've computed the proper type after overload resolution.
1754 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1755 // be calling it from within an NDEBUG block.
1756 assert(S.Context.hasSameType(((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1758, __PRETTY_FUNCTION__))
1757 FromType,((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1758, __PRETTY_FUNCTION__))
1758 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 1758, __PRETTY_FUNCTION__))
;
1759 } else {
1760 return false;
1761 }
1762 }
1763 // Lvalue-to-rvalue conversion (C++11 4.1):
1764 // A glvalue (3.10) of a non-function, non-array type T can
1765 // be converted to a prvalue.
1766 bool argIsLValue = From->isGLValue();
1767 if (argIsLValue &&
1768 !FromType->isFunctionType() && !FromType->isArrayType() &&
1769 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1770 SCS.First = ICK_Lvalue_To_Rvalue;
1771
1772 // C11 6.3.2.1p2:
1773 // ... if the lvalue has atomic type, the value has the non-atomic version
1774 // of the type of the lvalue ...
1775 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1776 FromType = Atomic->getValueType();
1777
1778 // If T is a non-class type, the type of the rvalue is the
1779 // cv-unqualified version of T. Otherwise, the type of the rvalue
1780 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1781 // just strip the qualifiers because they don't matter.
1782 FromType = FromType.getUnqualifiedType();
1783 } else if (FromType->isArrayType()) {
1784 // Array-to-pointer conversion (C++ 4.2)
1785 SCS.First = ICK_Array_To_Pointer;
1786
1787 // An lvalue or rvalue of type "array of N T" or "array of unknown
1788 // bound of T" can be converted to an rvalue of type "pointer to
1789 // T" (C++ 4.2p1).
1790 FromType = S.Context.getArrayDecayedType(FromType);
1791
1792 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1793 // This conversion is deprecated in C++03 (D.4)
1794 SCS.DeprecatedStringLiteralToCharPtr = true;
1795
1796 // For the purpose of ranking in overload resolution
1797 // (13.3.3.1.1), this conversion is considered an
1798 // array-to-pointer conversion followed by a qualification
1799 // conversion (4.4). (C++ 4.2p2)
1800 SCS.Second = ICK_Identity;
1801 SCS.Third = ICK_Qualification;
1802 SCS.QualificationIncludesObjCLifetime = false;
1803 SCS.setAllToTypes(FromType);
1804 return true;
1805 }
1806 } else if (FromType->isFunctionType() && argIsLValue) {
1807 // Function-to-pointer conversion (C++ 4.3).
1808 SCS.First = ICK_Function_To_Pointer;
1809
1810 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1811 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1812 if (!S.checkAddressOfFunctionIsAvailable(FD))
1813 return false;
1814
1815 // An lvalue of function type T can be converted to an rvalue of
1816 // type "pointer to T." The result is a pointer to the
1817 // function. (C++ 4.3p1).
1818 FromType = S.Context.getPointerType(FromType);
1819 } else {
1820 // We don't require any conversions for the first step.
1821 SCS.First = ICK_Identity;
1822 }
1823 SCS.setToType(0, FromType);
1824
1825 // The second conversion can be an integral promotion, floating
1826 // point promotion, integral conversion, floating point conversion,
1827 // floating-integral conversion, pointer conversion,
1828 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1829 // For overloading in C, this can also be a "compatible-type"
1830 // conversion.
1831 bool IncompatibleObjC = false;
1832 ImplicitConversionKind SecondICK = ICK_Identity;
1833 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1834 // The unqualified versions of the types are the same: there's no
1835 // conversion to do.
1836 SCS.Second = ICK_Identity;
1837 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1838 // Integral promotion (C++ 4.5).
1839 SCS.Second = ICK_Integral_Promotion;
1840 FromType = ToType.getUnqualifiedType();
1841 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1842 // Floating point promotion (C++ 4.6).
1843 SCS.Second = ICK_Floating_Promotion;
1844 FromType = ToType.getUnqualifiedType();
1845 } else if (S.IsComplexPromotion(FromType, ToType)) {
1846 // Complex promotion (Clang extension)
1847 SCS.Second = ICK_Complex_Promotion;
1848 FromType = ToType.getUnqualifiedType();
1849 } else if (ToType->isBooleanType() &&
1850 (FromType->isArithmeticType() ||
1851 FromType->isAnyPointerType() ||
1852 FromType->isBlockPointerType() ||
1853 FromType->isMemberPointerType())) {
1854 // Boolean conversions (C++ 4.12).
1855 SCS.Second = ICK_Boolean_Conversion;
1856 FromType = S.Context.BoolTy;
1857 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1858 ToType->isIntegralType(S.Context)) {
1859 // Integral conversions (C++ 4.7).
1860 SCS.Second = ICK_Integral_Conversion;
1861 FromType = ToType.getUnqualifiedType();
1862 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1863 // Complex conversions (C99 6.3.1.6)
1864 SCS.Second = ICK_Complex_Conversion;
1865 FromType = ToType.getUnqualifiedType();
1866 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1867 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1868 // Complex-real conversions (C99 6.3.1.7)
1869 SCS.Second = ICK_Complex_Real;
1870 FromType = ToType.getUnqualifiedType();
1871 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1872 // FIXME: disable conversions between long double and __float128 if
1873 // their representation is different until there is back end support
1874 // We of course allow this conversion if long double is really double.
1875
1876 // Conversions between bfloat and other floats are not permitted.
1877 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1878 return false;
1879 if (&S.Context.getFloatTypeSemantics(FromType) !=
1880 &S.Context.getFloatTypeSemantics(ToType)) {
1881 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1882 ToType == S.Context.LongDoubleTy) ||
1883 (FromType == S.Context.LongDoubleTy &&
1884 ToType == S.Context.Float128Ty));
1885 if (Float128AndLongDouble &&
1886 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1887 &llvm::APFloat::PPCDoubleDouble()))
1888 return false;
1889 }
1890 // Floating point conversions (C++ 4.8).
1891 SCS.Second = ICK_Floating_Conversion;
1892 FromType = ToType.getUnqualifiedType();
1893 } else if ((FromType->isRealFloatingType() &&
1894 ToType->isIntegralType(S.Context)) ||
1895 (FromType->isIntegralOrUnscopedEnumerationType() &&
1896 ToType->isRealFloatingType())) {
1897 // Conversions between bfloat and int are not permitted.
1898 if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1899 return false;
1900
1901 // Floating-integral conversions (C++ 4.9).
1902 SCS.Second = ICK_Floating_Integral;
1903 FromType = ToType.getUnqualifiedType();
1904 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1905 SCS.Second = ICK_Block_Pointer_Conversion;
1906 } else if (AllowObjCWritebackConversion &&
1907 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1908 SCS.Second = ICK_Writeback_Conversion;
1909 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1910 FromType, IncompatibleObjC)) {
1911 // Pointer conversions (C++ 4.10).
1912 SCS.Second = ICK_Pointer_Conversion;
1913 SCS.IncompatibleObjC = IncompatibleObjC;
1914 FromType = FromType.getUnqualifiedType();
1915 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1916 InOverloadResolution, FromType)) {
1917 // Pointer to member conversions (4.11).
1918 SCS.Second = ICK_Pointer_Member;
1919 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1920 SCS.Second = SecondICK;
1921 FromType = ToType.getUnqualifiedType();
1922 } else if (!S.getLangOpts().CPlusPlus &&
1923 S.Context.typesAreCompatible(ToType, FromType)) {
1924 // Compatible conversions (Clang extension for C function overloading)
1925 SCS.Second = ICK_Compatible_Conversion;
1926 FromType = ToType.getUnqualifiedType();
1927 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1928 InOverloadResolution,
1929 SCS, CStyle)) {
1930 SCS.Second = ICK_TransparentUnionConversion;
1931 FromType = ToType;
1932 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1933 CStyle)) {
1934 // tryAtomicConversion has updated the standard conversion sequence
1935 // appropriately.
1936 return true;
1937 } else if (ToType->isEventT() &&
1938 From->isIntegerConstantExpr(S.getASTContext()) &&
1939 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1940 SCS.Second = ICK_Zero_Event_Conversion;
1941 FromType = ToType;
1942 } else if (ToType->isQueueT() &&
1943 From->isIntegerConstantExpr(S.getASTContext()) &&
1944 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1945 SCS.Second = ICK_Zero_Queue_Conversion;
1946 FromType = ToType;
1947 } else if (ToType->isSamplerT() &&
1948 From->isIntegerConstantExpr(S.getASTContext())) {
1949 SCS.Second = ICK_Compatible_Conversion;
1950 FromType = ToType;
1951 } else {
1952 // No second conversion required.
1953 SCS.Second = ICK_Identity;
1954 }
1955 SCS.setToType(1, FromType);
1956
1957 // The third conversion can be a function pointer conversion or a
1958 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1959 bool ObjCLifetimeConversion;
1960 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1961 // Function pointer conversions (removing 'noexcept') including removal of
1962 // 'noreturn' (Clang extension).
1963 SCS.Third = ICK_Function_Conversion;
1964 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1965 ObjCLifetimeConversion)) {
1966 SCS.Third = ICK_Qualification;
1967 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1968 FromType = ToType;
1969 } else {
1970 // No conversion required
1971 SCS.Third = ICK_Identity;
1972 }
1973
1974 // C++ [over.best.ics]p6:
1975 // [...] Any difference in top-level cv-qualification is
1976 // subsumed by the initialization itself and does not constitute
1977 // a conversion. [...]
1978 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1979 QualType CanonTo = S.Context.getCanonicalType(ToType);
1980 if (CanonFrom.getLocalUnqualifiedType()
1981 == CanonTo.getLocalUnqualifiedType() &&
1982 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1983 FromType = ToType;
1984 CanonFrom = CanonTo;
1985 }
1986
1987 SCS.setToType(2, FromType);
1988
1989 if (CanonFrom == CanonTo)
1990 return true;
1991
1992 // If we have not converted the argument type to the parameter type,
1993 // this is a bad conversion sequence, unless we're resolving an overload in C.
1994 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1995 return false;
1996
1997 ExprResult ER = ExprResult{From};
1998 Sema::AssignConvertType Conv =
1999 S.CheckSingleAssignmentConstraints(ToType, ER,
2000 /*Diagnose=*/false,
2001 /*DiagnoseCFAudited=*/false,
2002 /*ConvertRHS=*/false);
2003 ImplicitConversionKind SecondConv;
2004 switch (Conv) {
2005 case Sema::Compatible:
2006 SecondConv = ICK_C_Only_Conversion;
2007 break;
2008 // For our purposes, discarding qualifiers is just as bad as using an
2009 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2010 // qualifiers, as well.
2011 case Sema::CompatiblePointerDiscardsQualifiers:
2012 case Sema::IncompatiblePointer:
2013 case Sema::IncompatiblePointerSign:
2014 SecondConv = ICK_Incompatible_Pointer_Conversion;
2015 break;
2016 default:
2017 return false;
2018 }
2019
2020 // First can only be an lvalue conversion, so we pretend that this was the
2021 // second conversion. First should already be valid from earlier in the
2022 // function.
2023 SCS.Second = SecondConv;
2024 SCS.setToType(1, ToType);
2025
2026 // Third is Identity, because Second should rank us worse than any other
2027 // conversion. This could also be ICK_Qualification, but it's simpler to just
2028 // lump everything in with the second conversion, and we don't gain anything
2029 // from making this ICK_Qualification.
2030 SCS.Third = ICK_Identity;
2031 SCS.setToType(2, ToType);
2032 return true;
2033}
2034
2035static bool
2036IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2037 QualType &ToType,
2038 bool InOverloadResolution,
2039 StandardConversionSequence &SCS,
2040 bool CStyle) {
2041
2042 const RecordType *UT = ToType->getAsUnionType();
2043 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2044 return false;
2045 // The field to initialize within the transparent union.
2046 RecordDecl *UD = UT->getDecl();
2047 // It's compatible if the expression matches any of the fields.
2048 for (const auto *it : UD->fields()) {
2049 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2050 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2051 ToType = it->getType();
2052 return true;
2053 }
2054 }
2055 return false;
2056}
2057
2058/// IsIntegralPromotion - Determines whether the conversion from the
2059/// expression From (whose potentially-adjusted type is FromType) to
2060/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2061/// sets PromotedType to the promoted type.
2062bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2063 const BuiltinType *To = ToType->getAs<BuiltinType>();
2064 // All integers are built-in.
2065 if (!To) {
2066 return false;
2067 }
2068
2069 // An rvalue of type char, signed char, unsigned char, short int, or
2070 // unsigned short int can be converted to an rvalue of type int if
2071 // int can represent all the values of the source type; otherwise,
2072 // the source rvalue can be converted to an rvalue of type unsigned
2073 // int (C++ 4.5p1).
2074 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2075 !FromType->isEnumeralType()) {
2076 if (// We can promote any signed, promotable integer type to an int
2077 (FromType->isSignedIntegerType() ||
2078 // We can promote any unsigned integer type whose size is
2079 // less than int to an int.
2080 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2081 return To->getKind() == BuiltinType::Int;
2082 }
2083
2084 return To->getKind() == BuiltinType::UInt;
2085 }
2086
2087 // C++11 [conv.prom]p3:
2088 // A prvalue of an unscoped enumeration type whose underlying type is not
2089 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2090 // following types that can represent all the values of the enumeration
2091 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2092 // unsigned int, long int, unsigned long int, long long int, or unsigned
2093 // long long int. If none of the types in that list can represent all the
2094 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2095 // type can be converted to an rvalue a prvalue of the extended integer type
2096 // with lowest integer conversion rank (4.13) greater than the rank of long
2097 // long in which all the values of the enumeration can be represented. If
2098 // there are two such extended types, the signed one is chosen.
2099 // C++11 [conv.prom]p4:
2100 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2101 // can be converted to a prvalue of its underlying type. Moreover, if
2102 // integral promotion can be applied to its underlying type, a prvalue of an
2103 // unscoped enumeration type whose underlying type is fixed can also be
2104 // converted to a prvalue of the promoted underlying type.
2105 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2106 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2107 // provided for a scoped enumeration.
2108 if (FromEnumType->getDecl()->isScoped())
2109 return false;
2110
2111 // We can perform an integral promotion to the underlying type of the enum,
2112 // even if that's not the promoted type. Note that the check for promoting
2113 // the underlying type is based on the type alone, and does not consider
2114 // the bitfield-ness of the actual source expression.
2115 if (FromEnumType->getDecl()->isFixed()) {
2116 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2117 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2118 IsIntegralPromotion(nullptr, Underlying, ToType);
2119 }
2120
2121 // We have already pre-calculated the promotion type, so this is trivial.
2122 if (ToType->isIntegerType() &&
2123 isCompleteType(From->getBeginLoc(), FromType))
2124 return Context.hasSameUnqualifiedType(
2125 ToType, FromEnumType->getDecl()->getPromotionType());
2126
2127 // C++ [conv.prom]p5:
2128 // If the bit-field has an enumerated type, it is treated as any other
2129 // value of that type for promotion purposes.
2130 //
2131 // ... so do not fall through into the bit-field checks below in C++.
2132 if (getLangOpts().CPlusPlus)
2133 return false;
2134 }
2135
2136 // C++0x [conv.prom]p2:
2137 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2138 // to an rvalue a prvalue of the first of the following types that can
2139 // represent all the values of its underlying type: int, unsigned int,
2140 // long int, unsigned long int, long long int, or unsigned long long int.
2141 // If none of the types in that list can represent all the values of its
2142 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2143 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2144 // type.
2145 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2146 ToType->isIntegerType()) {
2147 // Determine whether the type we're converting from is signed or
2148 // unsigned.
2149 bool FromIsSigned = FromType->isSignedIntegerType();
2150 uint64_t FromSize = Context.getTypeSize(FromType);
2151
2152 // The types we'll try to promote to, in the appropriate
2153 // order. Try each of these types.
2154 QualType PromoteTypes[6] = {
2155 Context.IntTy, Context.UnsignedIntTy,
2156 Context.LongTy, Context.UnsignedLongTy ,
2157 Context.LongLongTy, Context.UnsignedLongLongTy
2158 };
2159 for (int Idx = 0; Idx < 6; ++Idx) {
2160 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2161 if (FromSize < ToSize ||
2162 (FromSize == ToSize &&
2163 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2164 // We found the type that we can promote to. If this is the
2165 // type we wanted, we have a promotion. Otherwise, no
2166 // promotion.
2167 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2168 }
2169 }
2170 }
2171
2172 // An rvalue for an integral bit-field (9.6) can be converted to an
2173 // rvalue of type int if int can represent all the values of the
2174 // bit-field; otherwise, it can be converted to unsigned int if
2175 // unsigned int can represent all the values of the bit-field. If
2176 // the bit-field is larger yet, no integral promotion applies to
2177 // it. If the bit-field has an enumerated type, it is treated as any
2178 // other value of that type for promotion purposes (C++ 4.5p3).
2179 // FIXME: We should delay checking of bit-fields until we actually perform the
2180 // conversion.
2181 //
2182 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2183 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2184 // bit-fields and those whose underlying type is larger than int) for GCC
2185 // compatibility.
2186 if (From) {
2187 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2188 Optional<llvm::APSInt> BitWidth;
2189 if (FromType->isIntegralType(Context) &&
2190 (BitWidth =
2191 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2192 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2193 ToSize = Context.getTypeSize(ToType);
2194
2195 // Are we promoting to an int from a bitfield that fits in an int?
2196 if (*BitWidth < ToSize ||
2197 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2198 return To->getKind() == BuiltinType::Int;
2199 }
2200
2201 // Are we promoting to an unsigned int from an unsigned bitfield
2202 // that fits into an unsigned int?
2203 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2204 return To->getKind() == BuiltinType::UInt;
2205 }
2206
2207 return false;
2208 }
2209 }
2210 }
2211
2212 // An rvalue of type bool can be converted to an rvalue of type int,
2213 // with false becoming zero and true becoming one (C++ 4.5p4).
2214 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2215 return true;
2216 }
2217
2218 return false;
2219}
2220
2221/// IsFloatingPointPromotion - Determines whether the conversion from
2222/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2223/// returns true and sets PromotedType to the promoted type.
2224bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2225 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2226 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2227 /// An rvalue of type float can be converted to an rvalue of type
2228 /// double. (C++ 4.6p1).
2229 if (FromBuiltin->getKind() == BuiltinType::Float &&
2230 ToBuiltin->getKind() == BuiltinType::Double)
2231 return true;
2232
2233 // C99 6.3.1.5p1:
2234 // When a float is promoted to double or long double, or a
2235 // double is promoted to long double [...].
2236 if (!getLangOpts().CPlusPlus &&
2237 (FromBuiltin->getKind() == BuiltinType::Float ||
2238 FromBuiltin->getKind() == BuiltinType::Double) &&
2239 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2240 ToBuiltin->getKind() == BuiltinType::Float128))
2241 return true;
2242
2243 // Half can be promoted to float.
2244 if (!getLangOpts().NativeHalfType &&
2245 FromBuiltin->getKind() == BuiltinType::Half &&
2246 ToBuiltin->getKind() == BuiltinType::Float)
2247 return true;
2248 }
2249
2250 return false;
2251}
2252
2253/// Determine if a conversion is a complex promotion.
2254///
2255/// A complex promotion is defined as a complex -> complex conversion
2256/// where the conversion between the underlying real types is a
2257/// floating-point or integral promotion.
2258bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2259 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2260 if (!FromComplex)
2261 return false;
2262
2263 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2264 if (!ToComplex)
2265 return false;
2266
2267 return IsFloatingPointPromotion(FromComplex->getElementType(),
2268 ToComplex->getElementType()) ||
2269 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2270 ToComplex->getElementType());
2271}
2272
2273/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2274/// the pointer type FromPtr to a pointer to type ToPointee, with the
2275/// same type qualifiers as FromPtr has on its pointee type. ToType,
2276/// if non-empty, will be a pointer to ToType that may or may not have
2277/// the right set of qualifiers on its pointee.
2278///
2279static QualType
2280BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2281 QualType ToPointee, QualType ToType,
2282 ASTContext &Context,
2283 bool StripObjCLifetime = false) {
2284 assert((FromPtr->getTypeClass() == Type::Pointer ||(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 2286, __PRETTY_FUNCTION__))
2285 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 2286, __PRETTY_FUNCTION__))
2286 "Invalid similarly-qualified pointer type")(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 2286, __PRETTY_FUNCTION__))
;
2287
2288 /// Conversions to 'id' subsume cv-qualifier conversions.
2289 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2290 return ToType.getUnqualifiedType();
2291
2292 QualType CanonFromPointee
2293 = Context.getCanonicalType(FromPtr->getPointeeType());
2294 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2295 Qualifiers Quals = CanonFromPointee.getQualifiers();
2296
2297 if (StripObjCLifetime)
2298 Quals.removeObjCLifetime();
2299
2300 // Exact qualifier match -> return the pointer type we're converting to.
2301 if (CanonToPointee.getLocalQualifiers() == Quals) {
2302 // ToType is exactly what we need. Return it.
2303 if (!ToType.isNull())
2304 return ToType.getUnqualifiedType();
2305
2306 // Build a pointer to ToPointee. It has the right qualifiers
2307 // already.
2308 if (isa<ObjCObjectPointerType>(ToType))
2309 return Context.getObjCObjectPointerType(ToPointee);
2310 return Context.getPointerType(ToPointee);
2311 }
2312
2313 // Just build a canonical type that has the right qualifiers.
2314 QualType QualifiedCanonToPointee
2315 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2316
2317 if (isa<ObjCObjectPointerType>(ToType))
2318 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2319 return Context.getPointerType(QualifiedCanonToPointee);
2320}
2321
2322static bool isNullPointerConstantForConversion(Expr *Expr,
2323 bool InOverloadResolution,
2324 ASTContext &Context) {
2325 // Handle value-dependent integral null pointer constants correctly.
2326 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2327 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2328 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2329 return !InOverloadResolution;
2330
2331 return Expr->isNullPointerConstant(Context,
2332 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2333 : Expr::NPC_ValueDependentIsNull);
2334}
2335
2336/// IsPointerConversion - Determines whether the conversion of the
2337/// expression From, which has the (possibly adjusted) type FromType,
2338/// can be converted to the type ToType via a pointer conversion (C++
2339/// 4.10). If so, returns true and places the converted type (that
2340/// might differ from ToType in its cv-qualifiers at some level) into
2341/// ConvertedType.
2342///
2343/// This routine also supports conversions to and from block pointers
2344/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2345/// pointers to interfaces. FIXME: Once we've determined the
2346/// appropriate overloading rules for Objective-C, we may want to
2347/// split the Objective-C checks into a different routine; however,
2348/// GCC seems to consider all of these conversions to be pointer
2349/// conversions, so for now they live here. IncompatibleObjC will be
2350/// set if the conversion is an allowed Objective-C conversion that
2351/// should result in a warning.
2352bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2353 bool InOverloadResolution,
2354 QualType& ConvertedType,
2355 bool &IncompatibleObjC) {
2356 IncompatibleObjC = false;
2357 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2358 IncompatibleObjC))
2359 return true;
2360
2361 // Conversion from a null pointer constant to any Objective-C pointer type.
2362 if (ToType->isObjCObjectPointerType() &&
2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2364 ConvertedType = ToType;
2365 return true;
2366 }
2367
2368 // Blocks: Block pointers can be converted to void*.
2369 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2370 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2371 ConvertedType = ToType;
2372 return true;
2373 }
2374 // Blocks: A null pointer constant can be converted to a block
2375 // pointer type.
2376 if (ToType->isBlockPointerType() &&
2377 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2378 ConvertedType = ToType;
2379 return true;
2380 }
2381
2382 // If the left-hand-side is nullptr_t, the right side can be a null
2383 // pointer constant.
2384 if (ToType->isNullPtrType() &&
2385 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2386 ConvertedType = ToType;
2387 return true;
2388 }
2389
2390 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2391 if (!ToTypePtr)
2392 return false;
2393
2394 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2395 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2396 ConvertedType = ToType;
2397 return true;
2398 }
2399
2400 // Beyond this point, both types need to be pointers
2401 // , including objective-c pointers.
2402 QualType ToPointeeType = ToTypePtr->getPointeeType();
2403 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2404 !getLangOpts().ObjCAutoRefCount) {
2405 ConvertedType = BuildSimilarlyQualifiedPointerType(
2406 FromType->getAs<ObjCObjectPointerType>(),
2407 ToPointeeType,
2408 ToType, Context);
2409 return true;
2410 }
2411 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2412 if (!FromTypePtr)
2413 return false;
2414
2415 QualType FromPointeeType = FromTypePtr->getPointeeType();
2416
2417 // If the unqualified pointee types are the same, this can't be a
2418 // pointer conversion, so don't do all of the work below.
2419 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2420 return false;
2421
2422 // An rvalue of type "pointer to cv T," where T is an object type,
2423 // can be converted to an rvalue of type "pointer to cv void" (C++
2424 // 4.10p2).
2425 if (FromPointeeType->isIncompleteOrObjectType() &&
2426 ToPointeeType->isVoidType()) {
2427 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2428 ToPointeeType,
2429 ToType, Context,
2430 /*StripObjCLifetime=*/true);
2431 return true;
2432 }
2433
2434 // MSVC allows implicit function to void* type conversion.
2435 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2436 ToPointeeType->isVoidType()) {
2437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2438 ToPointeeType,
2439 ToType, Context);
2440 return true;
2441 }
2442
2443 // When we're overloading in C, we allow a special kind of pointer
2444 // conversion for compatible-but-not-identical pointee types.
2445 if (!getLangOpts().CPlusPlus &&
2446 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2447 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2448 ToPointeeType,
2449 ToType, Context);
2450 return true;
2451 }
2452
2453 // C++ [conv.ptr]p3:
2454 //
2455 // An rvalue of type "pointer to cv D," where D is a class type,
2456 // can be converted to an rvalue of type "pointer to cv B," where
2457 // B is a base class (clause 10) of D. If B is an inaccessible
2458 // (clause 11) or ambiguous (10.2) base class of D, a program that
2459 // necessitates this conversion is ill-formed. The result of the
2460 // conversion is a pointer to the base class sub-object of the
2461 // derived class object. The null pointer value is converted to
2462 // the null pointer value of the destination type.
2463 //
2464 // Note that we do not check for ambiguity or inaccessibility
2465 // here. That is handled by CheckPointerConversion.
2466 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2467 ToPointeeType->isRecordType() &&
2468 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2469 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2470 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2471 ToPointeeType,
2472 ToType, Context);
2473 return true;
2474 }
2475
2476 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2477 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2478 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2479 ToPointeeType,
2480 ToType, Context);
2481 return true;
2482 }
2483
2484 return false;
2485}
2486
2487/// Adopt the given qualifiers for the given type.
2488static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2489 Qualifiers TQs = T.getQualifiers();
2490
2491 // Check whether qualifiers already match.
2492 if (TQs == Qs)
2493 return T;
2494
2495 if (Qs.compatiblyIncludes(TQs))
2496 return Context.getQualifiedType(T, Qs);
2497
2498 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2499}
2500
2501/// isObjCPointerConversion - Determines whether this is an
2502/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2503/// with the same arguments and return values.
2504bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2505 QualType& ConvertedType,
2506 bool &IncompatibleObjC) {
2507 if (!getLangOpts().ObjC)
2508 return false;
2509
2510 // The set of qualifiers on the type we're converting from.
2511 Qualifiers FromQualifiers = FromType.getQualifiers();
2512
2513 // First, we handle all conversions on ObjC object pointer types.
2514 const ObjCObjectPointerType* ToObjCPtr =
2515 ToType->getAs<ObjCObjectPointerType>();
2516 const ObjCObjectPointerType *FromObjCPtr =
2517 FromType->getAs<ObjCObjectPointerType>();
2518
2519 if (ToObjCPtr && FromObjCPtr) {
2520 // If the pointee types are the same (ignoring qualifications),
2521 // then this is not a pointer conversion.
2522 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2523 FromObjCPtr->getPointeeType()))
2524 return false;
2525
2526 // Conversion between Objective-C pointers.
2527 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2528 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2529 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2530 if (getLangOpts().CPlusPlus && LHS && RHS &&
2531 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2532 FromObjCPtr->getPointeeType()))
2533 return false;
2534 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2535 ToObjCPtr->getPointeeType(),
2536 ToType, Context);
2537 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2538 return true;
2539 }
2540
2541 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2542 // Okay: this is some kind of implicit downcast of Objective-C
2543 // interfaces, which is permitted. However, we're going to
2544 // complain about it.
2545 IncompatibleObjC = true;
2546 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2547 ToObjCPtr->getPointeeType(),
2548 ToType, Context);
2549 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2550 return true;
2551 }
2552 }
2553 // Beyond this point, both types need to be C pointers or block pointers.
2554 QualType ToPointeeType;
2555 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2556 ToPointeeType = ToCPtr->getPointeeType();
2557 else if (const BlockPointerType *ToBlockPtr =
2558 ToType->getAs<BlockPointerType>()) {
2559 // Objective C++: We're able to convert from a pointer to any object
2560 // to a block pointer type.
2561 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2562 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2563 return true;
2564 }
2565 ToPointeeType = ToBlockPtr->getPointeeType();
2566 }
2567 else if (FromType->getAs<BlockPointerType>() &&
2568 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2569 // Objective C++: We're able to convert from a block pointer type to a
2570 // pointer to any object.
2571 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2572 return true;
2573 }
2574 else
2575 return false;
2576
2577 QualType FromPointeeType;
2578 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2579 FromPointeeType = FromCPtr->getPointeeType();
2580 else if (const BlockPointerType *FromBlockPtr =
2581 FromType->getAs<BlockPointerType>())
2582 FromPointeeType = FromBlockPtr->getPointeeType();
2583 else
2584 return false;
2585
2586 // If we have pointers to pointers, recursively check whether this
2587 // is an Objective-C conversion.
2588 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2589 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2590 IncompatibleObjC)) {
2591 // We always complain about this conversion.
2592 IncompatibleObjC = true;
2593 ConvertedType = Context.getPointerType(ConvertedType);
2594 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2595 return true;
2596 }
2597 // Allow conversion of pointee being objective-c pointer to another one;
2598 // as in I* to id.
2599 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2600 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2601 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2602 IncompatibleObjC)) {
2603
2604 ConvertedType = Context.getPointerType(ConvertedType);
2605 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2606 return true;
2607 }
2608
2609 // If we have pointers to functions or blocks, check whether the only
2610 // differences in the argument and result types are in Objective-C
2611 // pointer conversions. If so, we permit the conversion (but
2612 // complain about it).
2613 const FunctionProtoType *FromFunctionType
2614 = FromPointeeType->getAs<FunctionProtoType>();
2615 const FunctionProtoType *ToFunctionType
2616 = ToPointeeType->getAs<FunctionProtoType>();
2617 if (FromFunctionType && ToFunctionType) {
2618 // If the function types are exactly the same, this isn't an
2619 // Objective-C pointer conversion.
2620 if (Context.getCanonicalType(FromPointeeType)
2621 == Context.getCanonicalType(ToPointeeType))
2622 return false;
2623
2624 // Perform the quick checks that will tell us whether these
2625 // function types are obviously different.
2626 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2627 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2628 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2629 return false;
2630
2631 bool HasObjCConversion = false;
2632 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2633 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2634 // Okay, the types match exactly. Nothing to do.
2635 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2636 ToFunctionType->getReturnType(),
2637 ConvertedType, IncompatibleObjC)) {
2638 // Okay, we have an Objective-C pointer conversion.
2639 HasObjCConversion = true;
2640 } else {
2641 // Function types are too different. Abort.
2642 return false;
2643 }
2644
2645 // Check argument types.
2646 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2647 ArgIdx != NumArgs; ++ArgIdx) {
2648 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2649 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2650 if (Context.getCanonicalType(FromArgType)
2651 == Context.getCanonicalType(ToArgType)) {
2652 // Okay, the types match exactly. Nothing to do.
2653 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2654 ConvertedType, IncompatibleObjC)) {
2655 // Okay, we have an Objective-C pointer conversion.
2656 HasObjCConversion = true;
2657 } else {
2658 // Argument types are too different. Abort.
2659 return false;
2660 }
2661 }
2662
2663 if (HasObjCConversion) {
2664 // We had an Objective-C conversion. Allow this pointer
2665 // conversion, but complain about it.
2666 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2667 IncompatibleObjC = true;
2668 return true;
2669 }
2670 }
2671
2672 return false;
2673}
2674
2675/// Determine whether this is an Objective-C writeback conversion,
2676/// used for parameter passing when performing automatic reference counting.
2677///
2678/// \param FromType The type we're converting form.
2679///
2680/// \param ToType The type we're converting to.
2681///
2682/// \param ConvertedType The type that will be produced after applying
2683/// this conversion.
2684bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2685 QualType &ConvertedType) {
2686 if (!getLangOpts().ObjCAutoRefCount ||
2687 Context.hasSameUnqualifiedType(FromType, ToType))
2688 return false;
2689
2690 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2691 QualType ToPointee;
2692 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2693 ToPointee = ToPointer->getPointeeType();
2694 else
2695 return false;
2696
2697 Qualifiers ToQuals = ToPointee.getQualifiers();
2698 if (!ToPointee->isObjCLifetimeType() ||
2699 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2700 !ToQuals.withoutObjCLifetime().empty())
2701 return false;
2702
2703 // Argument must be a pointer to __strong to __weak.
2704 QualType FromPointee;
2705 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2706 FromPointee = FromPointer->getPointeeType();
2707 else
2708 return false;
2709
2710 Qualifiers FromQuals = FromPointee.getQualifiers();
2711 if (!FromPointee->isObjCLifetimeType() ||
2712 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2713 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2714 return false;
2715
2716 // Make sure that we have compatible qualifiers.
2717 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2718 if (!ToQuals.compatiblyIncludes(FromQuals))
2719 return false;
2720
2721 // Remove qualifiers from the pointee type we're converting from; they
2722 // aren't used in the compatibility check belong, and we'll be adding back
2723 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2724 FromPointee = FromPointee.getUnqualifiedType();
2725
2726 // The unqualified form of the pointee types must be compatible.
2727 ToPointee = ToPointee.getUnqualifiedType();
2728 bool IncompatibleObjC;
2729 if (Context.typesAreCompatible(FromPointee, ToPointee))
2730 FromPointee = ToPointee;
2731 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2732 IncompatibleObjC))
2733 return false;
2734
2735 /// Construct the type we're converting to, which is a pointer to
2736 /// __autoreleasing pointee.
2737 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2738 ConvertedType = Context.getPointerType(FromPointee);
2739 return true;
2740}
2741
2742bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2743 QualType& ConvertedType) {
2744 QualType ToPointeeType;
2745 if (const BlockPointerType *ToBlockPtr =
2746 ToType->getAs<BlockPointerType>())
2747 ToPointeeType = ToBlockPtr->getPointeeType();
2748 else
2749 return false;
2750
2751 QualType FromPointeeType;
2752 if (const BlockPointerType *FromBlockPtr =
2753 FromType->getAs<BlockPointerType>())
2754 FromPointeeType = FromBlockPtr->getPointeeType();
2755 else
2756 return false;
2757 // We have pointer to blocks, check whether the only
2758 // differences in the argument and result types are in Objective-C
2759 // pointer conversions. If so, we permit the conversion.
2760
2761 const FunctionProtoType *FromFunctionType
2762 = FromPointeeType->getAs<FunctionProtoType>();
2763 const FunctionProtoType *ToFunctionType
2764 = ToPointeeType->getAs<FunctionProtoType>();
2765
2766 if (!FromFunctionType || !ToFunctionType)
2767 return false;
2768
2769 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2770 return true;
2771
2772 // Perform the quick checks that will tell us whether these
2773 // function types are obviously different.
2774 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2775 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2776 return false;
2777
2778 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2779 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2780 if (FromEInfo != ToEInfo)
2781 return false;
2782
2783 bool IncompatibleObjC = false;
2784 if (Context.hasSameType(FromFunctionType->getReturnType(),
2785 ToFunctionType->getReturnType())) {
2786 // Okay, the types match exactly. Nothing to do.
2787 } else {
2788 QualType RHS = FromFunctionType->getReturnType();
2789 QualType LHS = ToFunctionType->getReturnType();
2790 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2791 !RHS.hasQualifiers() && LHS.hasQualifiers())
2792 LHS = LHS.getUnqualifiedType();
2793
2794 if (Context.hasSameType(RHS,LHS)) {
2795 // OK exact match.
2796 } else if (isObjCPointerConversion(RHS, LHS,
2797 ConvertedType, IncompatibleObjC)) {
2798 if (IncompatibleObjC)
2799 return false;
2800 // Okay, we have an Objective-C pointer conversion.
2801 }
2802 else
2803 return false;
2804 }
2805
2806 // Check argument types.
2807 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2808 ArgIdx != NumArgs; ++ArgIdx) {
2809 IncompatibleObjC = false;
2810 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2811 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2812 if (Context.hasSameType(FromArgType, ToArgType)) {
2813 // Okay, the types match exactly. Nothing to do.
2814 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2815 ConvertedType, IncompatibleObjC)) {
2816 if (IncompatibleObjC)
2817 return false;
2818 // Okay, we have an Objective-C pointer conversion.
2819 } else
2820 // Argument types are too different. Abort.
2821 return false;
2822 }
2823
2824 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2825 bool CanUseToFPT, CanUseFromFPT;
2826 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2827 CanUseToFPT, CanUseFromFPT,
2828 NewParamInfos))
2829 return false;
2830
2831 ConvertedType = ToType;
2832 return true;
2833}
2834
2835enum {
2836 ft_default,
2837 ft_different_class,
2838 ft_parameter_arity,
2839 ft_parameter_mismatch,
2840 ft_return_type,
2841 ft_qualifer_mismatch,
2842 ft_noexcept
2843};
2844
2845/// Attempts to get the FunctionProtoType from a Type. Handles
2846/// MemberFunctionPointers properly.
2847static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2848 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2849 return FPT;
2850
2851 if (auto *MPT = FromType->getAs<MemberPointerType>())
2852 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2853
2854 return nullptr;
2855}
2856
2857/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2858/// function types. Catches different number of parameter, mismatch in
2859/// parameter types, and different return types.
2860void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2861 QualType FromType, QualType ToType) {
2862 // If either type is not valid, include no extra info.
2863 if (FromType.isNull() || ToType.isNull()) {
2864 PDiag << ft_default;
2865 return;
2866 }
2867
2868 // Get the function type from the pointers.
2869 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2870 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2871 *ToMember = ToType->castAs<MemberPointerType>();
2872 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2873 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2874 << QualType(FromMember->getClass(), 0);
2875 return;
2876 }
2877 FromType = FromMember->getPointeeType();
2878 ToType = ToMember->getPointeeType();
2879 }
2880
2881 if (FromType->isPointerType())
2882 FromType = FromType->getPointeeType();
2883 if (ToType->isPointerType())
2884 ToType = ToType->getPointeeType();
2885
2886 // Remove references.
2887 FromType = FromType.getNonReferenceType();
2888 ToType = ToType.getNonReferenceType();
2889
2890 // Don't print extra info for non-specialized template functions.
2891 if (FromType->isInstantiationDependentType() &&
2892 !FromType->getAs<TemplateSpecializationType>()) {
2893 PDiag << ft_default;
2894 return;
2895 }
2896
2897 // No extra info for same types.
2898 if (Context.hasSameType(FromType, ToType)) {
2899 PDiag << ft_default;
2900 return;
2901 }
2902
2903 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2904 *ToFunction = tryGetFunctionProtoType(ToType);
2905
2906 // Both types need to be function types.
2907 if (!FromFunction || !ToFunction) {
2908 PDiag << ft_default;
2909 return;
2910 }
2911
2912 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2913 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2914 << FromFunction->getNumParams();
2915 return;
2916 }
2917
2918 // Handle different parameter types.
2919 unsigned ArgPos;
2920 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2921 PDiag << ft_parameter_mismatch << ArgPos + 1
2922 << ToFunction->getParamType(ArgPos)
2923 << FromFunction->getParamType(ArgPos);
2924 return;
2925 }
2926
2927 // Handle different return type.
2928 if (!Context.hasSameType(FromFunction->getReturnType(),
2929 ToFunction->getReturnType())) {
2930 PDiag << ft_return_type << ToFunction->getReturnType()
2931 << FromFunction->getReturnType();
2932 return;
2933 }
2934
2935 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2936 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2937 << FromFunction->getMethodQuals();
2938 return;
2939 }
2940
2941 // Handle exception specification differences on canonical type (in C++17
2942 // onwards).
2943 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2944 ->isNothrow() !=
2945 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2946 ->isNothrow()) {
2947 PDiag << ft_noexcept;
2948 return;
2949 }
2950
2951 // Unable to find a difference, so add no extra info.
2952 PDiag << ft_default;
2953}
2954
2955/// FunctionParamTypesAreEqual - This routine checks two function proto types
2956/// for equality of their argument types. Caller has already checked that
2957/// they have same number of arguments. If the parameters are different,
2958/// ArgPos will have the parameter index of the first different parameter.
2959bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2960 const FunctionProtoType *NewType,
2961 unsigned *ArgPos) {
2962 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2963 N = NewType->param_type_begin(),
2964 E = OldType->param_type_end();
2965 O && (O != E); ++O, ++N) {
2966 // Ignore address spaces in pointee type. This is to disallow overloading
2967 // on __ptr32/__ptr64 address spaces.
2968 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2969 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2970
2971 if (!Context.hasSameType(Old, New)) {
2972 if (ArgPos)
2973 *ArgPos = O - OldType->param_type_begin();
2974 return false;
2975 }
2976 }
2977 return true;
2978}
2979
2980/// CheckPointerConversion - Check the pointer conversion from the
2981/// expression From to the type ToType. This routine checks for
2982/// ambiguous or inaccessible derived-to-base pointer
2983/// conversions for which IsPointerConversion has already returned
2984/// true. It returns true and produces a diagnostic if there was an
2985/// error, or returns false otherwise.
2986bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2987 CastKind &Kind,
2988 CXXCastPath& BasePath,
2989 bool IgnoreBaseAccess,
2990 bool Diagnose) {
2991 QualType FromType = From->getType();
2992 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2993
2994 Kind = CK_BitCast;
2995
2996 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2997 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2998 Expr::NPCK_ZeroExpression) {
2999 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3000 DiagRuntimeBehavior(From->getExprLoc(), From,
3001 PDiag(diag::warn_impcast_bool_to_null_pointer)
3002 << ToType << From->getSourceRange());
3003 else if (!isUnevaluatedContext())
3004 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3005 << ToType << From->getSourceRange();
3006 }
3007 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3008 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3009 QualType FromPointeeType = FromPtrType->getPointeeType(),
3010 ToPointeeType = ToPtrType->getPointeeType();
3011
3012 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3013 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3014 // We must have a derived-to-base conversion. Check an
3015 // ambiguous or inaccessible conversion.
3016 unsigned InaccessibleID = 0;
3017 unsigned AmbiguousID = 0;
3018 if (Diagnose) {
3019 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3020 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3021 }
3022 if (CheckDerivedToBaseConversion(
3023 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3024 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3025 &BasePath, IgnoreBaseAccess))
3026 return true;
3027
3028 // The conversion was successful.
3029 Kind = CK_DerivedToBase;
3030 }
3031
3032 if (Diagnose && !IsCStyleOrFunctionalCast &&
3033 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3034 assert(getLangOpts().MSVCCompat &&((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3035, __PRETTY_FUNCTION__))
3035 "this should only be possible with MSVCCompat!")((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3035, __PRETTY_FUNCTION__))
;
3036 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3037 << From->getSourceRange();
3038 }
3039 }
3040 } else if (const ObjCObjectPointerType *ToPtrType =
3041 ToType->getAs<ObjCObjectPointerType>()) {
3042 if (const ObjCObjectPointerType *FromPtrType =
3043 FromType->getAs<ObjCObjectPointerType>()) {
3044 // Objective-C++ conversions are always okay.
3045 // FIXME: We should have a different class of conversions for the
3046 // Objective-C++ implicit conversions.
3047 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3048 return false;
3049 } else if (FromType->isBlockPointerType()) {
3050 Kind = CK_BlockPointerToObjCPointerCast;
3051 } else {
3052 Kind = CK_CPointerToObjCPointerCast;
3053 }
3054 } else if (ToType->isBlockPointerType()) {
3055 if (!FromType->isBlockPointerType())
3056 Kind = CK_AnyPointerToBlockPointerCast;
3057 }
3058
3059 // We shouldn't fall into this case unless it's valid for other
3060 // reasons.
3061 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3062 Kind = CK_NullToPointer;
3063
3064 return false;
3065}
3066
3067/// IsMemberPointerConversion - Determines whether the conversion of the
3068/// expression From, which has the (possibly adjusted) type FromType, can be
3069/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3070/// If so, returns true and places the converted type (that might differ from
3071/// ToType in its cv-qualifiers at some level) into ConvertedType.
3072bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3073 QualType ToType,
3074 bool InOverloadResolution,
3075 QualType &ConvertedType) {
3076 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3077 if (!ToTypePtr)
3078 return false;
3079
3080 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3081 if (From->isNullPointerConstant(Context,
3082 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3083 : Expr::NPC_ValueDependentIsNull)) {
3084 ConvertedType = ToType;
3085 return true;
3086 }
3087
3088 // Otherwise, both types have to be member pointers.
3089 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3090 if (!FromTypePtr)
3091 return false;
3092
3093 // A pointer to member of B can be converted to a pointer to member of D,
3094 // where D is derived from B (C++ 4.11p2).
3095 QualType FromClass(FromTypePtr->getClass(), 0);
3096 QualType ToClass(ToTypePtr->getClass(), 0);
3097
3098 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3099 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3100 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3101 ToClass.getTypePtr());
3102 return true;
3103 }
3104
3105 return false;
3106}
3107
3108/// CheckMemberPointerConversion - Check the member pointer conversion from the
3109/// expression From to the type ToType. This routine checks for ambiguous or
3110/// virtual or inaccessible base-to-derived member pointer conversions
3111/// for which IsMemberPointerConversion has already returned true. It returns
3112/// true and produces a diagnostic if there was an error, or returns false
3113/// otherwise.
3114bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3115 CastKind &Kind,
3116 CXXCastPath &BasePath,
3117 bool IgnoreBaseAccess) {
3118 QualType FromType = From->getType();
3119 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3120 if (!FromPtrType) {
3121 // This must be a null pointer to member pointer conversion
3122 assert(From->isNullPointerConstant(Context,((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
3123 Expr::NPC_ValueDependentIsNull) &&((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
3124 "Expr must be null pointer constant!")((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
;
3125 Kind = CK_NullToMemberPointer;
3126 return false;
3127 }
3128
3129 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3130 assert(ToPtrType && "No member pointer cast has a target type "((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
3131 "that is not a member pointer.")((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
;
3132
3133 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3134 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3135
3136 // FIXME: What about dependent types?
3137 assert(FromClass->isRecordType() && "Pointer into non-class.")((FromClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3137, __PRETTY_FUNCTION__))
;
3138 assert(ToClass->isRecordType() && "Pointer into non-class.")((ToClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3138, __PRETTY_FUNCTION__))
;
3139
3140 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3141 /*DetectVirtual=*/true);
3142 bool DerivationOkay =
3143 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3144 assert(DerivationOkay &&((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3145, __PRETTY_FUNCTION__))
3145 "Should not have been called if derivation isn't OK.")((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3145, __PRETTY_FUNCTION__))
;
3146 (void)DerivationOkay;
3147
3148 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3149 getUnqualifiedType())) {
3150 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3151 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3152 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3153 return true;
3154 }
3155
3156 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3157 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3158 << FromClass << ToClass << QualType(VBase, 0)
3159 << From->getSourceRange();
3160 return true;
3161 }
3162
3163 if (!IgnoreBaseAccess)
3164 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3165 Paths.front(),
3166 diag::err_downcast_from_inaccessible_base);
3167
3168 // Must be a base to derived member conversion.
3169 BuildBasePathArray(Paths, BasePath);
3170 Kind = CK_BaseToDerivedMemberPointer;
3171 return false;
3172}
3173
3174/// Determine whether the lifetime conversion between the two given
3175/// qualifiers sets is nontrivial.
3176static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3177 Qualifiers ToQuals) {
3178 // Converting anything to const __unsafe_unretained is trivial.
3179 if (ToQuals.hasConst() &&
3180 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3181 return false;
3182
3183 return true;
3184}
3185
3186/// Perform a single iteration of the loop for checking if a qualification
3187/// conversion is valid.
3188///
3189/// Specifically, check whether any change between the qualifiers of \p
3190/// FromType and \p ToType is permissible, given knowledge about whether every
3191/// outer layer is const-qualified.
3192static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3193 bool CStyle, bool IsTopLevel,
3194 bool &PreviousToQualsIncludeConst,
3195 bool &ObjCLifetimeConversion) {
3196 Qualifiers FromQuals = FromType.getQualifiers();
3197 Qualifiers ToQuals = ToType.getQualifiers();
3198
3199 // Ignore __unaligned qualifier if this type is void.
3200 if (ToType.getUnqualifiedType()->isVoidType())
3201 FromQuals.removeUnaligned();
3202
3203 // Objective-C ARC:
3204 // Check Objective-C lifetime conversions.
3205 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3206 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3207 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3208 ObjCLifetimeConversion = true;
3209 FromQuals.removeObjCLifetime();
3210 ToQuals.removeObjCLifetime();
3211 } else {
3212 // Qualification conversions cannot cast between different
3213 // Objective-C lifetime qualifiers.
3214 return false;
3215 }
3216 }
3217
3218 // Allow addition/removal of GC attributes but not changing GC attributes.
3219 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3220 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3221 FromQuals.removeObjCGCAttr();
3222 ToQuals.removeObjCGCAttr();
3223 }
3224
3225 // -- for every j > 0, if const is in cv 1,j then const is in cv
3226 // 2,j, and similarly for volatile.
3227 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3228 return false;
3229
3230 // If address spaces mismatch:
3231 // - in top level it is only valid to convert to addr space that is a
3232 // superset in all cases apart from C-style casts where we allow
3233 // conversions between overlapping address spaces.
3234 // - in non-top levels it is not a valid conversion.
3235 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3236 (!IsTopLevel ||
3237 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3238 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3239 return false;
3240
3241 // -- if the cv 1,j and cv 2,j are different, then const is in
3242 // every cv for 0 < k < j.
3243 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3244 !PreviousToQualsIncludeConst)
3245 return false;
3246
3247 // Keep track of whether all prior cv-qualifiers in the "to" type
3248 // include const.
3249 PreviousToQualsIncludeConst =
3250 PreviousToQualsIncludeConst && ToQuals.hasConst();
3251 return true;
3252}
3253
3254/// IsQualificationConversion - Determines whether the conversion from
3255/// an rvalue of type FromType to ToType is a qualification conversion
3256/// (C++ 4.4).
3257///
3258/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3259/// when the qualification conversion involves a change in the Objective-C
3260/// object lifetime.
3261bool
3262Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3263 bool CStyle, bool &ObjCLifetimeConversion) {
3264 FromType = Context.getCanonicalType(FromType);
3265 ToType = Context.getCanonicalType(ToType);
3266 ObjCLifetimeConversion = false;
3267
3268 // If FromType and ToType are the same type, this is not a
3269 // qualification conversion.
3270 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3271 return false;
3272
3273 // (C++ 4.4p4):
3274 // A conversion can add cv-qualifiers at levels other than the first
3275 // in multi-level pointers, subject to the following rules: [...]
3276 bool PreviousToQualsIncludeConst = true;
3277 bool UnwrappedAnyPointer = false;
3278 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3279 if (!isQualificationConversionStep(
3280 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3281 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3282 return false;
3283 UnwrappedAnyPointer = true;
3284 }
3285
3286 // We are left with FromType and ToType being the pointee types
3287 // after unwrapping the original FromType and ToType the same number
3288 // of times. If we unwrapped any pointers, and if FromType and
3289 // ToType have the same unqualified type (since we checked
3290 // qualifiers above), then this is a qualification conversion.
3291 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3292}
3293
3294/// - Determine whether this is a conversion from a scalar type to an
3295/// atomic type.
3296///
3297/// If successful, updates \c SCS's second and third steps in the conversion
3298/// sequence to finish the conversion.
3299static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3300 bool InOverloadResolution,
3301 StandardConversionSequence &SCS,
3302 bool CStyle) {
3303 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3304 if (!ToAtomic)
3305 return false;
3306
3307 StandardConversionSequence InnerSCS;
3308 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3309 InOverloadResolution, InnerSCS,
3310 CStyle, /*AllowObjCWritebackConversion=*/false))
3311 return false;
3312
3313 SCS.Second = InnerSCS.Second;
3314 SCS.setToType(1, InnerSCS.getToType(1));
3315 SCS.Third = InnerSCS.Third;
3316 SCS.QualificationIncludesObjCLifetime
3317 = InnerSCS.QualificationIncludesObjCLifetime;
3318 SCS.setToType(2, InnerSCS.getToType(2));
3319 return true;
3320}
3321
3322static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3323 CXXConstructorDecl *Constructor,
3324 QualType Type) {
3325 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3326 if (CtorType->getNumParams() > 0) {
3327 QualType FirstArg = CtorType->getParamType(0);
3328 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3329 return true;
3330 }
3331 return false;
3332}
3333
3334static OverloadingResult
3335IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3336 CXXRecordDecl *To,
3337 UserDefinedConversionSequence &User,
3338 OverloadCandidateSet &CandidateSet,
3339 bool AllowExplicit) {
3340 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3341 for (auto *D : S.LookupConstructors(To)) {
3342 auto Info = getConstructorInfo(D);
3343 if (!Info)
3344 continue;
3345
3346 bool Usable = !Info.Constructor->isInvalidDecl() &&
3347 S.isInitListConstructor(Info.Constructor);
3348 if (Usable) {
3349 // If the first argument is (a reference to) the target type,
3350 // suppress conversions.
3351 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3352 S.Context, Info.Constructor, ToType);
3353 if (Info.ConstructorTmpl)
3354 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3355 /*ExplicitArgs*/ nullptr, From,
3356 CandidateSet, SuppressUserConversions,
3357 /*PartialOverloading*/ false,
3358 AllowExplicit);
3359 else
3360 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3361 CandidateSet, SuppressUserConversions,
3362 /*PartialOverloading*/ false, AllowExplicit);
3363 }
3364 }
3365
3366 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3367
3368 OverloadCandidateSet::iterator Best;
3369 switch (auto Result =
3370 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3371 case OR_Deleted:
3372 case OR_Success: {
3373 // Record the standard conversion we used and the conversion function.
3374 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3375 QualType ThisType = Constructor->getThisType();
3376 // Initializer lists don't have conversions as such.
3377 User.Before.setAsIdentityConversion();
3378 User.HadMultipleCandidates = HadMultipleCandidates;
3379 User.ConversionFunction = Constructor;
3380 User.FoundConversionFunction = Best->FoundDecl;
3381 User.After.setAsIdentityConversion();
3382 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3383 User.After.setAllToTypes(ToType);
3384 return Result;
3385 }
3386
3387 case OR_No_Viable_Function:
3388 return OR_No_Viable_Function;
3389 case OR_Ambiguous:
3390 return OR_Ambiguous;
3391 }
3392
3393 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3393)
;
3394}
3395
3396/// Determines whether there is a user-defined conversion sequence
3397/// (C++ [over.ics.user]) that converts expression From to the type
3398/// ToType. If such a conversion exists, User will contain the
3399/// user-defined conversion sequence that performs such a conversion
3400/// and this routine will return true. Otherwise, this routine returns
3401/// false and User is unspecified.
3402///
3403/// \param AllowExplicit true if the conversion should consider C++0x
3404/// "explicit" conversion functions as well as non-explicit conversion
3405/// functions (C++0x [class.conv.fct]p2).
3406///
3407/// \param AllowObjCConversionOnExplicit true if the conversion should
3408/// allow an extra Objective-C pointer conversion on uses of explicit
3409/// constructors. Requires \c AllowExplicit to also be set.
3410static OverloadingResult
3411IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3412 UserDefinedConversionSequence &User,
3413 OverloadCandidateSet &CandidateSet,
3414 AllowedExplicit AllowExplicit,
3415 bool AllowObjCConversionOnExplicit) {
3416 assert(AllowExplicit != AllowedExplicit::None ||((AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit
) ? static_cast<void> (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3417, __PRETTY_FUNCTION__))
3417 !AllowObjCConversionOnExplicit)((AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit
) ? static_cast<void> (0) : __assert_fail ("AllowExplicit != AllowedExplicit::None || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3417, __PRETTY_FUNCTION__))
;
3418 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3419
3420 // Whether we will only visit constructors.
3421 bool ConstructorsOnly = false;
3422
3423 // If the type we are conversion to is a class type, enumerate its
3424 // constructors.
3425 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3426 // C++ [over.match.ctor]p1:
3427 // When objects of class type are direct-initialized (8.5), or
3428 // copy-initialized from an expression of the same or a
3429 // derived class type (8.5), overload resolution selects the
3430 // constructor. [...] For copy-initialization, the candidate
3431 // functions are all the converting constructors (12.3.1) of
3432 // that class. The argument list is the expression-list within
3433 // the parentheses of the initializer.
3434 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3435 (From->getType()->getAs<RecordType>() &&
3436 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3437 ConstructorsOnly = true;
3438
3439 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3440 // We're not going to find any constructors.
3441 } else if (CXXRecordDecl *ToRecordDecl
3442 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3443
3444 Expr **Args = &From;
3445 unsigned NumArgs = 1;
3446 bool ListInitializing = false;
3447 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3448 // But first, see if there is an init-list-constructor that will work.
3449 OverloadingResult Result = IsInitializerListConstructorConversion(
3450 S, From, ToType, ToRecordDecl, User, CandidateSet,
3451 AllowExplicit == AllowedExplicit::All);
3452 if (Result != OR_No_Viable_Function)
3453 return Result;
3454 // Never mind.
3455 CandidateSet.clear(
3456 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3457
3458 // If we're list-initializing, we pass the individual elements as
3459 // arguments, not the entire list.
3460 Args = InitList->getInits();
3461 NumArgs = InitList->getNumInits();
3462 ListInitializing = true;
3463 }
3464
3465 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3466 auto Info = getConstructorInfo(D);
3467 if (!Info)
3468 continue;
3469
3470 bool Usable = !Info.Constructor->isInvalidDecl();
3471 if (!ListInitializing)
3472 Usable = Usable && Info.Constructor->isConvertingConstructor(
3473 /*AllowExplicit*/ true);
3474 if (Usable) {
3475 bool SuppressUserConversions = !ConstructorsOnly;
3476 if (SuppressUserConversions && ListInitializing) {
3477 SuppressUserConversions = false;
3478 if (NumArgs == 1) {
3479 // If the first argument is (a reference to) the target type,
3480 // suppress conversions.
3481 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3482 S.Context, Info.Constructor, ToType);
3483 }
3484 }
3485 if (Info.ConstructorTmpl)
3486 S.AddTemplateOverloadCandidate(
3487 Info.ConstructorTmpl, Info.FoundDecl,
3488 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3489 CandidateSet, SuppressUserConversions,
3490 /*PartialOverloading*/ false,
3491 AllowExplicit == AllowedExplicit::All);
3492 else
3493 // Allow one user-defined conversion when user specifies a
3494 // From->ToType conversion via an static cast (c-style, etc).
3495 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3496 llvm::makeArrayRef(Args, NumArgs),
3497 CandidateSet, SuppressUserConversions,
3498 /*PartialOverloading*/ false,
3499 AllowExplicit == AllowedExplicit::All);
3500 }
3501 }
3502 }
3503 }
3504
3505 // Enumerate conversion functions, if we're allowed to.
3506 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3507 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3508 // No conversion functions from incomplete types.
3509 } else if (const RecordType *FromRecordType =
3510 From->getType()->getAs<RecordType>()) {
3511 if (CXXRecordDecl *FromRecordDecl
3512 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3513 // Add all of the conversion functions as candidates.
3514 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3515 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3516 DeclAccessPair FoundDecl = I.getPair();
3517 NamedDecl *D = FoundDecl.getDecl();
3518 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3519 if (isa<UsingShadowDecl>(D))
3520 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3521
3522 CXXConversionDecl *Conv;
3523 FunctionTemplateDecl *ConvTemplate;
3524 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3525 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3526 else
3527 Conv = cast<CXXConversionDecl>(D);
3528
3529 if (ConvTemplate)
3530 S.AddTemplateConversionCandidate(
3531 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3532 CandidateSet, AllowObjCConversionOnExplicit,
3533 AllowExplicit != AllowedExplicit::None);
3534 else
3535 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3536 CandidateSet, AllowObjCConversionOnExplicit,
3537 AllowExplicit != AllowedExplicit::None);
3538 }
3539 }
3540 }
3541
3542 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3543
3544 OverloadCandidateSet::iterator Best;
3545 switch (auto Result =
3546 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3547 case OR_Success:
3548 case OR_Deleted:
3549 // Record the standard conversion we used and the conversion function.
3550 if (CXXConstructorDecl *Constructor
3551 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3552 // C++ [over.ics.user]p1:
3553 // If the user-defined conversion is specified by a
3554 // constructor (12.3.1), the initial standard conversion
3555 // sequence converts the source type to the type required by
3556 // the argument of the constructor.
3557 //
3558 QualType ThisType = Constructor->getThisType();
3559 if (isa<InitListExpr>(From)) {
3560 // Initializer lists don't have conversions as such.
3561 User.Before.setAsIdentityConversion();
3562 } else {
3563 if (Best->Conversions[0].isEllipsis())
3564 User.EllipsisConversion = true;
3565 else {
3566 User.Before = Best->Conversions[0].Standard;
3567 User.EllipsisConversion = false;
3568 }
3569 }
3570 User.HadMultipleCandidates = HadMultipleCandidates;
3571 User.ConversionFunction = Constructor;
3572 User.FoundConversionFunction = Best->FoundDecl;
3573 User.After.setAsIdentityConversion();
3574 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3575 User.After.setAllToTypes(ToType);
3576 return Result;
3577 }
3578 if (CXXConversionDecl *Conversion
3579 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3580 // C++ [over.ics.user]p1:
3581 //
3582 // [...] If the user-defined conversion is specified by a
3583 // conversion function (12.3.2), the initial standard
3584 // conversion sequence converts the source type to the
3585 // implicit object parameter of the conversion function.
3586 User.Before = Best->Conversions[0].Standard;
3587 User.HadMultipleCandidates = HadMultipleCandidates;
3588 User.ConversionFunction = Conversion;
3589 User.FoundConversionFunction = Best->FoundDecl;
3590 User.EllipsisConversion = false;
3591
3592 // C++ [over.ics.user]p2:
3593 // The second standard conversion sequence converts the
3594 // result of the user-defined conversion to the target type
3595 // for the sequence. Since an implicit conversion sequence
3596 // is an initialization, the special rules for
3597 // initialization by user-defined conversion apply when
3598 // selecting the best user-defined conversion for a
3599 // user-defined conversion sequence (see 13.3.3 and
3600 // 13.3.3.1).
3601 User.After = Best->FinalConversion;
3602 return Result;
3603 }
3604 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3604)
;
3605
3606 case OR_No_Viable_Function:
3607 return OR_No_Viable_Function;
3608
3609 case OR_Ambiguous:
3610 return OR_Ambiguous;
3611 }
3612
3613 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 3613)
;
3614}
3615
3616bool
3617Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3618 ImplicitConversionSequence ICS;
3619 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3620 OverloadCandidateSet::CSK_Normal);
3621 OverloadingResult OvResult =
3622 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3623 CandidateSet, AllowedExplicit::None, false);
3624
3625 if (!(OvResult == OR_Ambiguous ||
3626 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3627 return false;
3628
3629 auto Cands = CandidateSet.CompleteCandidates(
3630 *this,
3631 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3632 From);
3633 if (OvResult == OR_Ambiguous)
3634 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3635 << From->getType() << ToType << From->getSourceRange();
3636 else { // OR_No_Viable_Function && !CandidateSet.empty()
3637 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3638 diag::err_typecheck_nonviable_condition_incomplete,
3639 From->getType(), From->getSourceRange()))
3640 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3641 << false << From->getType() << From->getSourceRange() << ToType;
3642 }
3643
3644 CandidateSet.NoteCandidates(
3645 *this, From, Cands);
3646 return true;
3647}
3648
3649// Helper for compareConversionFunctions that gets the FunctionType that the
3650// conversion-operator return value 'points' to, or nullptr.
3651static const FunctionType *
3652getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3653 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3654 const PointerType *RetPtrTy =
3655 ConvFuncTy->getReturnType()->getAs<PointerType>();
3656
3657 if (!RetPtrTy)
3658 return nullptr;
3659
3660 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3661}
3662
3663/// Compare the user-defined conversion functions or constructors
3664/// of two user-defined conversion sequences to determine whether any ordering
3665/// is possible.
3666static ImplicitConversionSequence::CompareKind
3667compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3668 FunctionDecl *Function2) {
3669 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3670 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3671 if (!Conv1 || !Conv2)
3672 return ImplicitConversionSequence::Indistinguishable;
3673
3674 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3675 return ImplicitConversionSequence::Indistinguishable;
3676
3677 // Objective-C++:
3678 // If both conversion functions are implicitly-declared conversions from
3679 // a lambda closure type to a function pointer and a block pointer,
3680 // respectively, always prefer the conversion to a function pointer,
3681 // because the function pointer is more lightweight and is more likely
3682 // to keep code working.
3683 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3684 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3685 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3686 if (Block1 != Block2)
3687 return Block1 ? ImplicitConversionSequence::Worse
3688 : ImplicitConversionSequence::Better;
3689 }
3690
3691 // In order to support multiple calling conventions for the lambda conversion
3692 // operator (such as when the free and member function calling convention is
3693 // different), prefer the 'free' mechanism, followed by the calling-convention
3694 // of operator(). The latter is in place to support the MSVC-like solution of
3695 // defining ALL of the possible conversions in regards to calling-convention.
3696 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3697 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3698
3699 if (Conv1FuncRet && Conv2FuncRet &&
3700 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3701 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3702 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3703
3704 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3705 const FunctionProtoType *CallOpProto =
3706 CallOp->getType()->getAs<FunctionProtoType>();
3707
3708 CallingConv CallOpCC =
3709 CallOp->getType()->getAs<FunctionType>()->getCallConv();
3710 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3711 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3712 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3713 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3714
3715 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3716 for (CallingConv CC : PrefOrder) {
3717 if (Conv1CC == CC)
3718 return ImplicitConversionSequence::Better;
3719 if (Conv2CC == CC)
3720 return ImplicitConversionSequence::Worse;
3721 }
3722 }
3723
3724 return ImplicitConversionSequence::Indistinguishable;
3725}
3726
3727static bool hasDeprecatedStringLiteralToCharPtrConversion(
3728 const ImplicitConversionSequence &ICS) {
3729 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3730 (ICS.isUserDefined() &&
3731 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3732}
3733
3734/// CompareImplicitConversionSequences - Compare two implicit
3735/// conversion sequences to determine whether one is better than the
3736/// other or if they are indistinguishable (C++ 13.3.3.2).
3737static ImplicitConversionSequence::CompareKind
3738CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3739 const ImplicitConversionSequence& ICS1,
3740 const ImplicitConversionSequence& ICS2)
3741{
3742 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3743 // conversion sequences (as defined in 13.3.3.1)
3744 // -- a standard conversion sequence (13.3.3.1.1) is a better
3745 // conversion sequence than a user-defined conversion sequence or
3746 // an ellipsis conversion sequence, and
3747 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3748 // conversion sequence than an ellipsis conversion sequence
3749 // (13.3.3.1.3).
3750 //
3751 // C++0x [over.best.ics]p10:
3752 // For the purpose of ranking implicit conversion sequences as
3753 // described in 13.3.3.2, the ambiguous conversion sequence is
3754 // treated as a user-defined sequence that is indistinguishable
3755 // from any other user-defined conversion sequence.
3756
3757 // String literal to 'char *' conversion has been deprecated in C++03. It has
3758 // been removed from C++11. We still accept this conversion, if it happens at
3759 // the best viable function. Otherwise, this conversion is considered worse
3760 // than ellipsis conversion. Consider this as an extension; this is not in the
3761 // standard. For example:
3762 //
3763 // int &f(...); // #1
3764 // void f(char*); // #2
3765 // void g() { int &r = f("foo"); }
3766 //
3767 // In C++03, we pick #2 as the best viable function.
3768 // In C++11, we pick #1 as the best viable function, because ellipsis
3769 // conversion is better than string-literal to char* conversion (since there
3770 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3771 // convert arguments, #2 would be the best viable function in C++11.
3772 // If the best viable function has this conversion, a warning will be issued
3773 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3774
3775 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3776 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3777 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3778 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3779 ? ImplicitConversionSequence::Worse
3780 : ImplicitConversionSequence::Better;
3781
3782 if (ICS1.getKindRank() < ICS2.getKindRank())
3783 return ImplicitConversionSequence::Better;
3784 if (ICS2.getKindRank() < ICS1.getKindRank())
3785 return ImplicitConversionSequence::Worse;
3786
3787 // The following checks require both conversion sequences to be of
3788 // the same kind.
3789 if (ICS1.getKind() != ICS2.getKind())
3790 return ImplicitConversionSequence::Indistinguishable;
3791
3792 ImplicitConversionSequence::CompareKind Result =
3793 ImplicitConversionSequence::Indistinguishable;
3794
3795 // Two implicit conversion sequences of the same form are
3796 // indistinguishable conversion sequences unless one of the
3797 // following rules apply: (C++ 13.3.3.2p3):
3798
3799 // List-initialization sequence L1 is a better conversion sequence than
3800 // list-initialization sequence L2 if:
3801 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3802 // if not that,
3803 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3804 // and N1 is smaller than N2.,
3805 // even if one of the other rules in this paragraph would otherwise apply.
3806 if (!ICS1.isBad()) {
3807 if (ICS1.isStdInitializerListElement() &&
3808 !ICS2.isStdInitializerListElement())
3809 return ImplicitConversionSequence::Better;
3810 if (!ICS1.isStdInitializerListElement() &&
3811 ICS2.isStdInitializerListElement())
3812 return ImplicitConversionSequence::Worse;
3813 }
3814
3815 if (ICS1.isStandard())
3816 // Standard conversion sequence S1 is a better conversion sequence than
3817 // standard conversion sequence S2 if [...]
3818 Result = CompareStandardConversionSequences(S, Loc,
3819 ICS1.Standard, ICS2.Standard);
3820 else if (ICS1.isUserDefined()) {
3821 // User-defined conversion sequence U1 is a better conversion
3822 // sequence than another user-defined conversion sequence U2 if
3823 // they contain the same user-defined conversion function or
3824 // constructor and if the second standard conversion sequence of
3825 // U1 is better than the second standard conversion sequence of
3826 // U2 (C++ 13.3.3.2p3).
3827 if (ICS1.UserDefined.ConversionFunction ==
3828 ICS2.UserDefined.ConversionFunction)
3829 Result = CompareStandardConversionSequences(S, Loc,
3830 ICS1.UserDefined.After,
3831 ICS2.UserDefined.After);
3832 else
3833 Result = compareConversionFunctions(S,
3834 ICS1.UserDefined.ConversionFunction,
3835 ICS2.UserDefined.ConversionFunction);
3836 }
3837
3838 return Result;
3839}
3840
3841// Per 13.3.3.2p3, compare the given standard conversion sequences to
3842// determine if one is a proper subset of the other.
3843static ImplicitConversionSequence::CompareKind
3844compareStandardConversionSubsets(ASTContext &Context,
3845 const StandardConversionSequence& SCS1,
3846 const StandardConversionSequence& SCS2) {
3847 ImplicitConversionSequence::CompareKind Result
3848 = ImplicitConversionSequence::Indistinguishable;
3849
3850 // the identity conversion sequence is considered to be a subsequence of
3851 // any non-identity conversion sequence
3852 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3853 return ImplicitConversionSequence::Better;
3854 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3855 return ImplicitConversionSequence::Worse;
3856
3857 if (SCS1.Second != SCS2.Second) {
3858 if (SCS1.Second == ICK_Identity)
3859 Result = ImplicitConversionSequence::Better;
3860 else if (SCS2.Second == ICK_Identity)
3861 Result = ImplicitConversionSequence::Worse;
3862 else
3863 return ImplicitConversionSequence::Indistinguishable;
3864 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3865 return ImplicitConversionSequence::Indistinguishable;
3866
3867 if (SCS1.Third == SCS2.Third) {
3868 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3869 : ImplicitConversionSequence::Indistinguishable;
3870 }
3871
3872 if (SCS1.Third == ICK_Identity)
3873 return Result == ImplicitConversionSequence::Worse
3874 ? ImplicitConversionSequence::Indistinguishable
3875 : ImplicitConversionSequence::Better;
3876
3877 if (SCS2.Third == ICK_Identity)
3878 return Result == ImplicitConversionSequence::Better
3879 ? ImplicitConversionSequence::Indistinguishable
3880 : ImplicitConversionSequence::Worse;
3881
3882 return ImplicitConversionSequence::Indistinguishable;
3883}
3884
3885/// Determine whether one of the given reference bindings is better
3886/// than the other based on what kind of bindings they are.
3887static bool
3888isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3889 const StandardConversionSequence &SCS2) {
3890 // C++0x [over.ics.rank]p3b4:
3891 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3892 // implicit object parameter of a non-static member function declared
3893 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3894 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3895 // lvalue reference to a function lvalue and S2 binds an rvalue
3896 // reference*.
3897 //
3898 // FIXME: Rvalue references. We're going rogue with the above edits,
3899 // because the semantics in the current C++0x working paper (N3225 at the
3900 // time of this writing) break the standard definition of std::forward
3901 // and std::reference_wrapper when dealing with references to functions.
3902 // Proposed wording changes submitted to CWG for consideration.
3903 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3904 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3905 return false;
3906
3907 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3908 SCS2.IsLvalueReference) ||
3909 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3910 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3911}
3912
3913enum class FixedEnumPromotion {
3914 None,
3915 ToUnderlyingType,
3916 ToPromotedUnderlyingType
3917};
3918
3919/// Returns kind of fixed enum promotion the \a SCS uses.
3920static FixedEnumPromotion
3921getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3922
3923 if (SCS.Second != ICK_Integral_Promotion)
3924 return FixedEnumPromotion::None;
3925
3926 QualType FromType = SCS.getFromType();
3927 if (!FromType->isEnumeralType())
3928 return FixedEnumPromotion::None;
3929
3930 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3931 if (!Enum->isFixed())
3932 return FixedEnumPromotion::None;
3933
3934 QualType UnderlyingType = Enum->getIntegerType();
3935 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3936 return FixedEnumPromotion::ToUnderlyingType;
3937
3938 return FixedEnumPromotion::ToPromotedUnderlyingType;
3939}
3940
3941/// CompareStandardConversionSequences - Compare two standard
3942/// conversion sequences to determine whether one is better than the
3943/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3944static ImplicitConversionSequence::CompareKind
3945CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3946 const StandardConversionSequence& SCS1,
3947 const StandardConversionSequence& SCS2)
3948{
3949 // Standard conversion sequence S1 is a better conversion sequence
3950 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3951
3952 // -- S1 is a proper subsequence of S2 (comparing the conversion
3953 // sequences in the canonical form defined by 13.3.3.1.1,
3954 // excluding any Lvalue Transformation; the identity conversion
3955 // sequence is considered to be a subsequence of any
3956 // non-identity conversion sequence) or, if not that,
3957 if (ImplicitConversionSequence::CompareKind CK
3958 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3959 return CK;
3960
3961 // -- the rank of S1 is better than the rank of S2 (by the rules
3962 // defined below), or, if not that,
3963 ImplicitConversionRank Rank1 = SCS1.getRank();
3964 ImplicitConversionRank Rank2 = SCS2.getRank();
3965 if (Rank1 < Rank2)
3966 return ImplicitConversionSequence::Better;
3967 else if (Rank2 < Rank1)
3968 return ImplicitConversionSequence::Worse;
3969
3970 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3971 // are indistinguishable unless one of the following rules
3972 // applies:
3973
3974 // A conversion that is not a conversion of a pointer, or
3975 // pointer to member, to bool is better than another conversion
3976 // that is such a conversion.
3977 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3978 return SCS2.isPointerConversionToBool()
3979 ? ImplicitConversionSequence::Better
3980 : ImplicitConversionSequence::Worse;
3981
3982 // C++14 [over.ics.rank]p4b2:
3983 // This is retroactively applied to C++11 by CWG 1601.
3984 //
3985 // A conversion that promotes an enumeration whose underlying type is fixed
3986 // to its underlying type is better than one that promotes to the promoted
3987 // underlying type, if the two are different.
3988 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3989 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3990 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3991 FEP1 != FEP2)
3992 return FEP1 == FixedEnumPromotion::ToUnderlyingType
3993 ? ImplicitConversionSequence::Better
3994 : ImplicitConversionSequence::Worse;
3995
3996 // C++ [over.ics.rank]p4b2:
3997 //
3998 // If class B is derived directly or indirectly from class A,
3999 // conversion of B* to A* is better than conversion of B* to
4000 // void*, and conversion of A* to void* is better than conversion
4001 // of B* to void*.
4002 bool SCS1ConvertsToVoid
4003 = SCS1.isPointerConversionToVoidPointer(S.Context);
4004 bool SCS2ConvertsToVoid
4005 = SCS2.isPointerConversionToVoidPointer(S.Context);
4006 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4007 // Exactly one of the conversion sequences is a conversion to
4008 // a void pointer; it's the worse conversion.
4009 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4010 : ImplicitConversionSequence::Worse;
4011 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4012 // Neither conversion sequence converts to a void pointer; compare
4013 // their derived-to-base conversions.
4014 if (ImplicitConversionSequence::CompareKind DerivedCK
4015 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4016 return DerivedCK;
4017 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4018 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4019 // Both conversion sequences are conversions to void
4020 // pointers. Compare the source types to determine if there's an
4021 // inheritance relationship in their sources.
4022 QualType FromType1 = SCS1.getFromType();
4023 QualType FromType2 = SCS2.getFromType();
4024
4025 // Adjust the types we're converting from via the array-to-pointer
4026 // conversion, if we need to.
4027 if (SCS1.First == ICK_Array_To_Pointer)
4028 FromType1 = S.Context.getArrayDecayedType(FromType1);
4029 if (SCS2.First == ICK_Array_To_Pointer)
4030 FromType2 = S.Context.getArrayDecayedType(FromType2);
4031
4032 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4033 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4034
4035 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4036 return ImplicitConversionSequence::Better;
4037 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4038 return ImplicitConversionSequence::Worse;
4039
4040 // Objective-C++: If one interface is more specific than the
4041 // other, it is the better one.
4042 const ObjCObjectPointerType* FromObjCPtr1
4043 = FromType1->getAs<ObjCObjectPointerType>();
4044 const ObjCObjectPointerType* FromObjCPtr2
4045 = FromType2->getAs<ObjCObjectPointerType>();
4046 if (FromObjCPtr1 && FromObjCPtr2) {
4047 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4048 FromObjCPtr2);
4049 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4050 FromObjCPtr1);
4051 if (AssignLeft != AssignRight) {
4052 return AssignLeft? ImplicitConversionSequence::Better
4053 : ImplicitConversionSequence::Worse;
4054 }
4055 }
4056 }
4057
4058 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4059 // Check for a better reference binding based on the kind of bindings.
4060 if (isBetterReferenceBindingKind(SCS1, SCS2))
4061 return ImplicitConversionSequence::Better;
4062 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4063 return ImplicitConversionSequence::Worse;
4064 }
4065
4066 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4067 // bullet 3).
4068 if (ImplicitConversionSequence::CompareKind QualCK
4069 = CompareQualificationConversions(S, SCS1, SCS2))
4070 return QualCK;
4071
4072 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4073 // C++ [over.ics.rank]p3b4:
4074 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4075 // which the references refer are the same type except for
4076 // top-level cv-qualifiers, and the type to which the reference
4077 // initialized by S2 refers is more cv-qualified than the type
4078 // to which the reference initialized by S1 refers.
4079 QualType T1 = SCS1.getToType(2);
4080 QualType T2 = SCS2.getToType(2);
4081 T1 = S.Context.getCanonicalType(T1);
4082 T2 = S.Context.getCanonicalType(T2);
4083 Qualifiers T1Quals, T2Quals;
4084 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4085 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4086 if (UnqualT1 == UnqualT2) {
4087 // Objective-C++ ARC: If the references refer to objects with different
4088 // lifetimes, prefer bindings that don't change lifetime.
4089 if (SCS1.ObjCLifetimeConversionBinding !=
4090 SCS2.ObjCLifetimeConversionBinding) {
4091 return SCS1.ObjCLifetimeConversionBinding
4092 ? ImplicitConversionSequence::Worse
4093 : ImplicitConversionSequence::Better;
4094 }
4095
4096 // If the type is an array type, promote the element qualifiers to the
4097 // type for comparison.
4098 if (isa<ArrayType>(T1) && T1Quals)
4099 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4100 if (isa<ArrayType>(T2) && T2Quals)
4101 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4102 if (T2.isMoreQualifiedThan(T1))
4103 return ImplicitConversionSequence::Better;
4104 if (T1.isMoreQualifiedThan(T2))
4105 return ImplicitConversionSequence::Worse;
4106 }
4107 }
4108
4109 // In Microsoft mode, prefer an integral conversion to a
4110 // floating-to-integral conversion if the integral conversion
4111 // is between types of the same size.
4112 // For example:
4113 // void f(float);
4114 // void f(int);
4115 // int main {
4116 // long a;
4117 // f(a);
4118 // }
4119 // Here, MSVC will call f(int) instead of generating a compile error
4120 // as clang will do in standard mode.
4121 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4122 SCS2.Second == ICK_Floating_Integral &&
4123 S.Context.getTypeSize(SCS1.getFromType()) ==
4124 S.Context.getTypeSize(SCS1.getToType(2)))
4125 return ImplicitConversionSequence::Better;
4126
4127 // Prefer a compatible vector conversion over a lax vector conversion
4128 // For example:
4129 //
4130 // typedef float __v4sf __attribute__((__vector_size__(16)));
4131 // void f(vector float);
4132 // void f(vector signed int);
4133 // int main() {
4134 // __v4sf a;
4135 // f(a);
4136 // }
4137 // Here, we'd like to choose f(vector float) and not
4138 // report an ambiguous call error
4139 if (SCS1.Second == ICK_Vector_Conversion &&
4140 SCS2.Second == ICK_Vector_Conversion) {
4141 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4142 SCS1.getFromType(), SCS1.getToType(2));
4143 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4144 SCS2.getFromType(), SCS2.getToType(2));
4145
4146 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4147 return SCS1IsCompatibleVectorConversion
4148 ? ImplicitConversionSequence::Better
4149 : ImplicitConversionSequence::Worse;
4150 }
4151
4152 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4153 SCS2.Second == ICK_SVE_Vector_Conversion) {
4154 bool SCS1IsCompatibleSVEVectorConversion =
4155 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4156 bool SCS2IsCompatibleSVEVectorConversion =
4157 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4158
4159 if (SCS1IsCompatibleSVEVectorConversion !=
4160 SCS2IsCompatibleSVEVectorConversion)
4161 return SCS1IsCompatibleSVEVectorConversion
4162 ? ImplicitConversionSequence::Better
4163 : ImplicitConversionSequence::Worse;
4164 }
4165
4166 return ImplicitConversionSequence::Indistinguishable;
4167}
4168
4169/// CompareQualificationConversions - Compares two standard conversion
4170/// sequences to determine whether they can be ranked based on their
4171/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4172static ImplicitConversionSequence::CompareKind
4173CompareQualificationConversions(Sema &S,
4174 const StandardConversionSequence& SCS1,
4175 const StandardConversionSequence& SCS2) {
4176 // C++ 13.3.3.2p3:
4177 // -- S1 and S2 differ only in their qualification conversion and
4178 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
4179 // cv-qualification signature of type T1 is a proper subset of
4180 // the cv-qualification signature of type T2, and S1 is not the
4181 // deprecated string literal array-to-pointer conversion (4.2).
4182 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4183 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4184 return ImplicitConversionSequence::Indistinguishable;
4185
4186 // FIXME: the example in the standard doesn't use a qualification
4187 // conversion (!)
4188 QualType T1 = SCS1.getToType(2);
4189 QualType T2 = SCS2.getToType(2);
4190 T1 = S.Context.getCanonicalType(T1);
4191 T2 = S.Context.getCanonicalType(T2);
4192 assert(!T1->isReferenceType() && !T2->isReferenceType())((!T1->isReferenceType() && !T2->isReferenceType
()) ? static_cast<void> (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 4192, __PRETTY_FUNCTION__))
;
4193 Qualifiers T1Quals, T2Quals;
4194 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4195 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4196
4197 // If the types are the same, we won't learn anything by unwrapping
4198 // them.
4199 if (UnqualT1 == UnqualT2)
4200 return ImplicitConversionSequence::Indistinguishable;
4201
4202 ImplicitConversionSequence::CompareKind Result
4203 = ImplicitConversionSequence::Indistinguishable;
4204
4205 // Objective-C++ ARC:
4206 // Prefer qualification conversions not involving a change in lifetime
4207 // to qualification conversions that do not change lifetime.
4208 if (SCS1.QualificationIncludesObjCLifetime !=
4209 SCS2.QualificationIncludesObjCLifetime) {
4210 Result = SCS1.QualificationIncludesObjCLifetime
4211 ? ImplicitConversionSequence::Worse
4212 : ImplicitConversionSequence::Better;
4213 }
4214
4215 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4216 // Within each iteration of the loop, we check the qualifiers to
4217 // determine if this still looks like a qualification
4218 // conversion. Then, if all is well, we unwrap one more level of
4219 // pointers or pointers-to-members and do it all again
4220 // until there are no more pointers or pointers-to-members left
4221 // to unwrap. This essentially mimics what
4222 // IsQualificationConversion does, but here we're checking for a
4223 // strict subset of qualifiers.
4224 if (T1.getQualifiers().withoutObjCLifetime() ==
4225 T2.getQualifiers().withoutObjCLifetime())
4226 // The qualifiers are the same, so this doesn't tell us anything
4227 // about how the sequences rank.
4228 // ObjC ownership quals are omitted above as they interfere with
4229 // the ARC overload rule.
4230 ;
4231 else if (T2.isMoreQualifiedThan(T1)) {
4232 // T1 has fewer qualifiers, so it could be the better sequence.
4233 if (Result == ImplicitConversionSequence::Worse)
4234 // Neither has qualifiers that are a subset of the other's
4235 // qualifiers.
4236 return ImplicitConversionSequence::Indistinguishable;
4237
4238 Result = ImplicitConversionSequence::Better;
4239 } else if (T1.isMoreQualifiedThan(T2)) {
4240 // T2 has fewer qualifiers, so it could be the better sequence.
4241 if (Result == ImplicitConversionSequence::Better)
4242 // Neither has qualifiers that are a subset of the other's
4243 // qualifiers.
4244 return ImplicitConversionSequence::Indistinguishable;
4245
4246 Result = ImplicitConversionSequence::Worse;
4247 } else {
4248 // Qualifiers are disjoint.
4249 return ImplicitConversionSequence::Indistinguishable;
4250 }
4251
4252 // If the types after this point are equivalent, we're done.
4253 if (S.Context.hasSameUnqualifiedType(T1, T2))
4254 break;
4255 }
4256
4257 // Check that the winning standard conversion sequence isn't using
4258 // the deprecated string literal array to pointer conversion.
4259 switch (Result) {
4260 case ImplicitConversionSequence::Better:
4261 if (SCS1.DeprecatedStringLiteralToCharPtr)
4262 Result = ImplicitConversionSequence::Indistinguishable;
4263 break;
4264
4265 case ImplicitConversionSequence::Indistinguishable:
4266 break;
4267
4268 case ImplicitConversionSequence::Worse:
4269 if (SCS2.DeprecatedStringLiteralToCharPtr)
4270 Result = ImplicitConversionSequence::Indistinguishable;
4271 break;
4272 }
4273
4274 return Result;
4275}
4276
4277/// CompareDerivedToBaseConversions - Compares two standard conversion
4278/// sequences to determine whether they can be ranked based on their
4279/// various kinds of derived-to-base conversions (C++
4280/// [over.ics.rank]p4b3). As part of these checks, we also look at
4281/// conversions between Objective-C interface types.
4282static ImplicitConversionSequence::CompareKind
4283CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4284 const StandardConversionSequence& SCS1,
4285 const StandardConversionSequence& SCS2) {
4286 QualType FromType1 = SCS1.getFromType();
4287 QualType ToType1 = SCS1.getToType(1);
4288 QualType FromType2 = SCS2.getFromType();
4289 QualType ToType2 = SCS2.getToType(1);
4290
4291 // Adjust the types we're converting from via the array-to-pointer
4292 // conversion, if we need to.
4293 if (SCS1.First == ICK_Array_To_Pointer)
4294 FromType1 = S.Context.getArrayDecayedType(FromType1);
4295 if (SCS2.First == ICK_Array_To_Pointer)
4296 FromType2 = S.Context.getArrayDecayedType(FromType2);
4297
4298 // Canonicalize all of the types.
4299 FromType1 = S.Context.getCanonicalType(FromType1);
4300 ToType1 = S.Context.getCanonicalType(ToType1);
4301 FromType2 = S.Context.getCanonicalType(FromType2);
4302 ToType2 = S.Context.getCanonicalType(ToType2);
4303
4304 // C++ [over.ics.rank]p4b3:
4305 //
4306 // If class B is derived directly or indirectly from class A and
4307 // class C is derived directly or indirectly from B,
4308 //
4309 // Compare based on pointer conversions.
4310 if (SCS1.Second == ICK_Pointer_Conversion &&
4311 SCS2.Second == ICK_Pointer_Conversion &&
4312 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4313 FromType1->isPointerType() && FromType2->isPointerType() &&
4314 ToType1->isPointerType() && ToType2->isPointerType()) {
4315 QualType FromPointee1 =
4316 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4317 QualType ToPointee1 =
4318 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4319 QualType FromPointee2 =
4320 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4321 QualType ToPointee2 =
4322 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4323
4324 // -- conversion of C* to B* is better than conversion of C* to A*,
4325 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4326 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4327 return ImplicitConversionSequence::Better;
4328 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4329 return ImplicitConversionSequence::Worse;
4330 }
4331
4332 // -- conversion of B* to A* is better than conversion of C* to A*,
4333 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4334 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4335 return ImplicitConversionSequence::Better;
4336 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4337 return ImplicitConversionSequence::Worse;
4338 }
4339 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4340 SCS2.Second == ICK_Pointer_Conversion) {
4341 const ObjCObjectPointerType *FromPtr1
4342 = FromType1->getAs<ObjCObjectPointerType>();
4343 const ObjCObjectPointerType *FromPtr2
4344 = FromType2->getAs<ObjCObjectPointerType>();
4345 const ObjCObjectPointerType *ToPtr1
4346 = ToType1->getAs<ObjCObjectPointerType>();
4347 const ObjCObjectPointerType *ToPtr2
4348 = ToType2->getAs<ObjCObjectPointerType>();
4349
4350 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4351 // Apply the same conversion ranking rules for Objective-C pointer types
4352 // that we do for C++ pointers to class types. However, we employ the
4353 // Objective-C pseudo-subtyping relationship used for assignment of
4354 // Objective-C pointer types.
4355 bool FromAssignLeft
4356 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4357 bool FromAssignRight
4358 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4359 bool ToAssignLeft
4360 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4361 bool ToAssignRight
4362 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4363
4364 // A conversion to an a non-id object pointer type or qualified 'id'
4365 // type is better than a conversion to 'id'.
4366 if (ToPtr1->isObjCIdType() &&
4367 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4368 return ImplicitConversionSequence::Worse;
4369 if (ToPtr2->isObjCIdType() &&
4370 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4371 return ImplicitConversionSequence::Better;
4372
4373 // A conversion to a non-id object pointer type is better than a
4374 // conversion to a qualified 'id' type
4375 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4376 return ImplicitConversionSequence::Worse;
4377 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4378 return ImplicitConversionSequence::Better;
4379
4380 // A conversion to an a non-Class object pointer type or qualified 'Class'
4381 // type is better than a conversion to 'Class'.
4382 if (ToPtr1->isObjCClassType() &&
4383 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4384 return ImplicitConversionSequence::Worse;
4385 if (ToPtr2->isObjCClassType() &&
4386 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4387 return ImplicitConversionSequence::Better;
4388
4389 // A conversion to a non-Class object pointer type is better than a
4390 // conversion to a qualified 'Class' type.
4391 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4392 return ImplicitConversionSequence::Worse;
4393 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4394 return ImplicitConversionSequence::Better;
4395
4396 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4397 if (S.Context.hasSameType(FromType1, FromType2) &&
4398 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4399 (ToAssignLeft != ToAssignRight)) {
4400 if (FromPtr1->isSpecialized()) {
4401 // "conversion of B<A> * to B * is better than conversion of B * to
4402 // C *.
4403 bool IsFirstSame =
4404 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4405 bool IsSecondSame =
4406 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4407 if (IsFirstSame) {
4408 if (!IsSecondSame)
4409 return ImplicitConversionSequence::Better;
4410 } else if (IsSecondSame)
4411 return ImplicitConversionSequence::Worse;
4412 }
4413 return ToAssignLeft? ImplicitConversionSequence::Worse
4414 : ImplicitConversionSequence::Better;
4415 }
4416
4417 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4418 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4419 (FromAssignLeft != FromAssignRight))
4420 return FromAssignLeft? ImplicitConversionSequence::Better
4421 : ImplicitConversionSequence::Worse;
4422 }
4423 }
4424
4425 // Ranking of member-pointer types.
4426 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4427 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4428 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4429 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4430 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4431 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4432 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4433 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4434 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4435 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4436 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4437 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4438 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4439 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4440 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4441 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4442 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4443 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4444 return ImplicitConversionSequence::Worse;
4445 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4446 return ImplicitConversionSequence::Better;
4447 }
4448 // conversion of B::* to C::* is better than conversion of A::* to C::*
4449 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4450 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4451 return ImplicitConversionSequence::Better;
4452 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4453 return ImplicitConversionSequence::Worse;
4454 }
4455 }
4456
4457 if (SCS1.Second == ICK_Derived_To_Base) {
4458 // -- conversion of C to B is better than conversion of C to A,
4459 // -- binding of an expression of type C to a reference of type
4460 // B& is better than binding an expression of type C to a
4461 // reference of type A&,
4462 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4463 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4464 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4465 return ImplicitConversionSequence::Better;
4466 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4467 return ImplicitConversionSequence::Worse;
4468 }
4469
4470 // -- conversion of B to A is better than conversion of C to A.
4471 // -- binding of an expression of type B to a reference of type
4472 // A& is better than binding an expression of type C to a
4473 // reference of type A&,
4474 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4475 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4476 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4477 return ImplicitConversionSequence::Better;
4478 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4479 return ImplicitConversionSequence::Worse;
4480 }
4481 }
4482
4483 return ImplicitConversionSequence::Indistinguishable;
4484}
4485
4486/// Determine whether the given type is valid, e.g., it is not an invalid
4487/// C++ class.
4488static bool isTypeValid(QualType T) {
4489 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4490 return !Record->isInvalidDecl();
4491
4492 return true;
4493}
4494
4495static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4496 if (!T.getQualifiers().hasUnaligned())
4497 return T;
4498
4499 Qualifiers Q;
4500 T = Ctx.getUnqualifiedArrayType(T, Q);
4501 Q.removeUnaligned();
4502 return Ctx.getQualifiedType(T, Q);
4503}
4504
4505/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4506/// determine whether they are reference-compatible,
4507/// reference-related, or incompatible, for use in C++ initialization by
4508/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4509/// type, and the first type (T1) is the pointee type of the reference
4510/// type being initialized.
4511Sema::ReferenceCompareResult
4512Sema::CompareReferenceRelationship(SourceLocation Loc,
4513 QualType OrigT1, QualType OrigT2,
4514 ReferenceConversions *ConvOut) {
4515 assert(!OrigT1->isReferenceType() &&((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 4516, __PRETTY_FUNCTION__))
4516 "T1 must be the pointee type of the reference type")((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 4516, __PRETTY_FUNCTION__))
;
4517 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")((!OrigT2->isReferenceType() && "T2 cannot be a reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 4517, __PRETTY_FUNCTION__))
;
4518
4519 QualType T1 = Context.getCanonicalType(OrigT1);
4520 QualType T2 = Context.getCanonicalType(OrigT2);
4521 Qualifiers T1Quals, T2Quals;
4522 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4523 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4524
4525 ReferenceConversions ConvTmp;
4526 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4527 Conv = ReferenceConversions();
4528
4529 // C++2a [dcl.init.ref]p4:
4530 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4531 // reference-related to "cv2 T2" if T1 is similar to T2, or
4532 // T1 is a base class of T2.
4533 // "cv1 T1" is reference-compatible with "cv2 T2" if
4534 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4535 // "pointer to cv1 T1" via a standard conversion sequence.
4536
4537 // Check for standard conversions we can apply to pointers: derived-to-base
4538 // conversions, ObjC pointer conversions, and function pointer conversions.
4539 // (Qualification conversions are checked last.)
4540 QualType ConvertedT2;
4541 if (UnqualT1 == UnqualT2) {
4542 // Nothing to do.
4543 } else if (isCompleteType(Loc, OrigT2) &&
4544 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4545 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4546 Conv |= ReferenceConversions::DerivedToBase;
4547 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4548 UnqualT2->isObjCObjectOrInterfaceType() &&
4549 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4550 Conv |= ReferenceConversions::ObjC;
4551 else if (UnqualT2->isFunctionType() &&
4552 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4553 Conv |= ReferenceConversions::Function;
4554 // No need to check qualifiers; function types don't have them.
4555 return Ref_Compatible;
4556 }
4557 bool ConvertedReferent = Conv != 0;
4558
4559 // We can have a qualification conversion. Compute whether the types are
4560 // similar at the same time.
4561 bool PreviousToQualsIncludeConst = true;
4562 bool TopLevel = true;
4563 do {
4564 if (T1 == T2)
4565 break;
4566
4567 // We will need a qualification conversion.
4568 Conv |= ReferenceConversions::Qualification;
4569
4570 // Track whether we performed a qualification conversion anywhere other
4571 // than the top level. This matters for ranking reference bindings in
4572 // overload resolution.
4573 if (!TopLevel)
4574 Conv |= ReferenceConversions::NestedQualification;
4575
4576 // MS compiler ignores __unaligned qualifier for references; do the same.
4577 T1 = withoutUnaligned(Context, T1);
4578 T2 = withoutUnaligned(Context, T2);
4579
4580 // If we find a qualifier mismatch, the types are not reference-compatible,
4581 // but are still be reference-related if they're similar.
4582 bool ObjCLifetimeConversion = false;
4583 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4584 PreviousToQualsIncludeConst,
4585 ObjCLifetimeConversion))
4586 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4587 ? Ref_Related
4588 : Ref_Incompatible;
4589
4590 // FIXME: Should we track this for any level other than the first?
4591 if (ObjCLifetimeConversion)
4592 Conv |= ReferenceConversions::ObjCLifetime;
4593
4594 TopLevel = false;
4595 } while (Context.UnwrapSimilarTypes(T1, T2));
4596
4597 // At this point, if the types are reference-related, we must either have the
4598 // same inner type (ignoring qualifiers), or must have already worked out how
4599 // to convert the referent.
4600 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4601 ? Ref_Compatible
4602 : Ref_Incompatible;
4603}
4604
4605/// Look for a user-defined conversion to a value reference-compatible
4606/// with DeclType. Return true if something definite is found.
4607static bool
4608FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4609 QualType DeclType, SourceLocation DeclLoc,
4610 Expr *Init, QualType T2, bool AllowRvalues,
4611 bool AllowExplicit) {
4612 assert(T2->isRecordType() && "Can only find conversions of record types.")((T2->isRecordType() && "Can only find conversions of record types."
) ? static_cast<void> (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 4612, __PRETTY_FUNCTION__))
;
4613 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4614
4615 OverloadCandidateSet CandidateSet(
4616 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4617 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4618 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4619 NamedDecl *D = *I;
4620 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4621 if (isa<UsingShadowDecl>(D))
4622 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4623
4624 FunctionTemplateDecl *ConvTemplate
4625 = dyn_cast<FunctionTemplateDecl>(D);
4626 CXXConversionDecl *Conv;
4627 if (ConvTemplate)
4628 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4629 else
4630 Conv = cast<CXXConversionDecl>(D);
4631
4632 if (AllowRvalues) {
4633 // If we are initializing an rvalue reference, don't permit conversion
4634 // functions that return lvalues.
4635 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4636 const ReferenceType *RefType
4637 = Conv->getConversionType()->getAs<LValueReferenceType>();
4638 if (RefType && !RefType->getPointeeType()->isFunctionType())
4639 continue;
4640 }
4641
4642 if (!ConvTemplate &&
4643 S.CompareReferenceRelationship(
4644 DeclLoc,
4645 Conv->getConversionType()
4646 .getNonReferenceType()
4647 .getUnqualifiedType(),
4648 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4649 Sema::Ref_Incompatible)
4650 continue;
4651 } else {
4652 // If the conversion function doesn't return a reference type,
4653 // it can't be considered for this conversion. An rvalue reference
4654 // is only acceptable if its referencee is a function type.
4655
4656 const ReferenceType *RefType =
4657 Conv->getConversionType()->getAs<ReferenceType>();
4658 if (!RefType ||
4659 (!RefType->isLValueReferenceType() &&
4660 !RefType->getPointeeType()->isFunctionType()))
4661 continue;
4662 }
4663
4664 if (ConvTemplate)
4665 S.AddTemplateConversionCandidate(
4666 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4667 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4668 else
4669 S.AddConversionCandidate(
4670 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4671 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4672 }
4673
4674 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4675
4676 OverloadCandidateSet::iterator Best;
4677 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4678 case OR_Success:
4679 // C++ [over.ics.ref]p1:
4680 //
4681 // [...] If the parameter binds directly to the result of
4682 // applying a conversion function to the argument
4683 // expression, the implicit conversion sequence is a
4684 // user-defined conversion sequence (13.3.3.1.2), with the
4685 // second standard conversion sequence either an identity
4686 // conversion or, if the conversion function returns an
4687 // entity of a type that is a derived class of the parameter
4688 // type, a derived-to-base Conversion.
4689 if (!Best->FinalConversion.DirectBinding)
4690 return false;
4691
4692 ICS.setUserDefined();
4693 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4694 ICS.UserDefined.After = Best->FinalConversion;
4695 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4696 ICS.UserDefined.ConversionFunction = Best->Function;
4697 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4698 ICS.UserDefined.EllipsisConversion = false;
4699 assert(ICS.UserDefined.After.ReferenceBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 4701, __PRETTY_FUNCTION__))
4700 ICS.UserDefined.After.DirectBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 4701, __PRETTY_FUNCTION__))
4701 "Expected a direct reference binding!")((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 4701, __PRETTY_FUNCTION__))
;
4702 return true;
4703
4704 case OR_Ambiguous:
4705 ICS.setAmbiguous();
4706 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4707 Cand != CandidateSet.end(); ++Cand)
4708 if (Cand->Best)
4709 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4710 return true;
4711
4712 case OR_No_Viable_Function:
4713 case OR_Deleted:
4714 // There was no suitable conversion, or we found a deleted
4715 // conversion; continue with other checks.
4716 return false;
4717 }
4718
4719 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 4719)
;
4720}
4721
4722/// Compute an implicit conversion sequence for reference
4723/// initialization.
4724static ImplicitConversionSequence
4725TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4726 SourceLocation DeclLoc,
4727 bool SuppressUserConversions,
4728 bool AllowExplicit) {
4729 assert(DeclType->isReferenceType() && "Reference init needs a reference")((DeclType->isReferenceType() && "Reference init needs a reference"
) ? static_cast<void> (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 4729, __PRETTY_FUNCTION__))
;
4730
4731 // Most paths end in a failed conversion.
4732 ImplicitConversionSequence ICS;
4733 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4734
4735 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4736 QualType T2 = Init->getType();
4737
4738 // If the initializer is the address of an overloaded function, try
4739 // to resolve the overloaded function. If all goes well, T2 is the
4740 // type of the resulting function.
4741 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4742 DeclAccessPair Found;
4743 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4744 false, Found))
4745 T2 = Fn->getType();
4746 }
4747
4748 // Compute some basic properties of the types and the initializer.
4749 bool isRValRef = DeclType->isRValueReferenceType();
4750 Expr::Classification InitCategory = Init->Classify(S.Context);
4751
4752 Sema::ReferenceConversions RefConv;
4753 Sema::ReferenceCompareResult RefRelationship =
4754 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4755
4756 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4757 ICS.setStandard();
4758 ICS.Standard.First = ICK_Identity;
4759 // FIXME: A reference binding can be a function conversion too. We should
4760 // consider that when ordering reference-to-function bindings.
4761 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4762 ? ICK_Derived_To_Base
4763 : (RefConv & Sema::ReferenceConversions::ObjC)
4764 ? ICK_Compatible_Conversion
4765 : ICK_Identity;
4766 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4767 // a reference binding that performs a non-top-level qualification
4768 // conversion as a qualification conversion, not as an identity conversion.
4769 ICS.Standard.Third = (RefConv &
4770 Sema::ReferenceConversions::NestedQualification)
4771 ? ICK_Qualification
4772 : ICK_Identity;
4773 ICS.Standard.setFromType(T2);
4774 ICS.Standard.setToType(0, T2);
4775 ICS.Standard.setToType(1, T1);
4776 ICS.Standard.setToType(2, T1);
4777 ICS.Standard.ReferenceBinding = true;
4778 ICS.Standard.DirectBinding = BindsDirectly;
4779 ICS.Standard.IsLvalueReference = !isRValRef;
4780 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4781 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4782 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4783 ICS.Standard.ObjCLifetimeConversionBinding =
4784 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4785 ICS.Standard.CopyConstructor = nullptr;
4786 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4787 };
4788
4789 // C++0x [dcl.init.ref]p5:
4790 // A reference to type "cv1 T1" is initialized by an expression
4791 // of type "cv2 T2" as follows:
4792
4793 // -- If reference is an lvalue reference and the initializer expression
4794 if (!isRValRef) {
4795 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4796 // reference-compatible with "cv2 T2," or
4797 //
4798 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4799 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4800 // C++ [over.ics.ref]p1:
4801 // When a parameter of reference type binds directly (8.5.3)
4802 // to an argument expression, the implicit conversion sequence
4803 // is the identity conversion, unless the argument expression
4804 // has a type that is a derived class of the parameter type,
4805 // in which case the implicit conversion sequence is a
4806 // derived-to-base Conversion (13.3.3.1).
4807 SetAsReferenceBinding(/*BindsDirectly=*/true);
4808
4809 // Nothing more to do: the inaccessibility/ambiguity check for
4810 // derived-to-base conversions is suppressed when we're
4811 // computing the implicit conversion sequence (C++
4812 // [over.best.ics]p2).
4813 return ICS;
4814 }
4815
4816 // -- has a class type (i.e., T2 is a class type), where T1 is
4817 // not reference-related to T2, and can be implicitly
4818 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4819 // is reference-compatible with "cv3 T3" 92) (this
4820 // conversion is selected by enumerating the applicable
4821 // conversion functions (13.3.1.6) and choosing the best
4822 // one through overload resolution (13.3)),
4823 if (!SuppressUserConversions && T2->isRecordType() &&
4824 S.isCompleteType(DeclLoc, T2) &&
4825 RefRelationship == Sema::Ref_Incompatible) {
4826 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4827 Init, T2, /*AllowRvalues=*/false,
4828 AllowExplicit))
4829 return ICS;
4830 }
4831 }
4832
4833 // -- Otherwise, the reference shall be an lvalue reference to a
4834 // non-volatile const type (i.e., cv1 shall be const), or the reference
4835 // shall be an rvalue reference.
4836 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4837 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4838 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4839 return ICS;
4840 }
4841
4842 // -- If the initializer expression
4843 //
4844 // -- is an xvalue, class prvalue, array prvalue or function
4845 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4846 if (RefRelationship == Sema::Ref_Compatible &&
4847 (InitCategory.isXValue() ||
4848 (InitCategory.isPRValue() &&
4849 (T2->isRecordType() || T2->isArrayType())) ||
4850 (InitCategory.isLValue() && T2->isFunctionType()))) {
4851 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4852 // binding unless we're binding to a class prvalue.
4853 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4854 // allow the use of rvalue references in C++98/03 for the benefit of
4855 // standard library implementors; therefore, we need the xvalue check here.
4856 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4857 !(InitCategory.isPRValue() || T2->isRecordType()));
4858 return ICS;
4859 }
4860
4861 // -- has a class type (i.e., T2 is a class type), where T1 is not
4862 // reference-related to T2, and can be implicitly converted to
4863 // an xvalue, class prvalue, or function lvalue of type
4864 // "cv3 T3", where "cv1 T1" is reference-compatible with
4865 // "cv3 T3",
4866 //
4867 // then the reference is bound to the value of the initializer
4868 // expression in the first case and to the result of the conversion
4869 // in the second case (or, in either case, to an appropriate base
4870 // class subobject).
4871 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4872 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4873 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4874 Init, T2, /*AllowRvalues=*/true,
4875 AllowExplicit)) {
4876 // In the second case, if the reference is an rvalue reference
4877 // and the second standard conversion sequence of the
4878 // user-defined conversion sequence includes an lvalue-to-rvalue
4879 // conversion, the program is ill-formed.
4880 if (ICS.isUserDefined() && isRValRef &&
4881 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4882 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4883
4884 return ICS;
4885 }
4886
4887 // A temporary of function type cannot be created; don't even try.
4888 if (T1->isFunctionType())
4889 return ICS;
4890
4891 // -- Otherwise, a temporary of type "cv1 T1" is created and
4892 // initialized from the initializer expression using the
4893 // rules for a non-reference copy initialization (8.5). The
4894 // reference is then bound to the temporary. If T1 is
4895 // reference-related to T2, cv1 must be the same
4896 // cv-qualification as, or greater cv-qualification than,
4897 // cv2; otherwise, the program is ill-formed.
4898 if (RefRelationship == Sema::Ref_Related) {
4899 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4900 // we would be reference-compatible or reference-compatible with
4901 // added qualification. But that wasn't the case, so the reference
4902 // initialization fails.
4903 //
4904 // Note that we only want to check address spaces and cvr-qualifiers here.
4905 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4906 Qualifiers T1Quals = T1.getQualifiers();
4907 Qualifiers T2Quals = T2.getQualifiers();
4908 T1Quals.removeObjCGCAttr();
4909 T1Quals.removeObjCLifetime();
4910 T2Quals.removeObjCGCAttr();
4911 T2Quals.removeObjCLifetime();
4912 // MS compiler ignores __unaligned qualifier for references; do the same.
4913 T1Quals.removeUnaligned();
4914 T2Quals.removeUnaligned();
4915 if (!T1Quals.compatiblyIncludes(T2Quals))
4916 return ICS;
4917 }
4918
4919 // If at least one of the types is a class type, the types are not
4920 // related, and we aren't allowed any user conversions, the
4921 // reference binding fails. This case is important for breaking
4922 // recursion, since TryImplicitConversion below will attempt to
4923 // create a temporary through the use of a copy constructor.
4924 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4925 (T1->isRecordType() || T2->isRecordType()))
4926 return ICS;
4927
4928 // If T1 is reference-related to T2 and the reference is an rvalue
4929 // reference, the initializer expression shall not be an lvalue.
4930 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4931 Init->Classify(S.Context).isLValue()) {
4932 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4933 return ICS;
4934 }
4935
4936 // C++ [over.ics.ref]p2:
4937 // When a parameter of reference type is not bound directly to
4938 // an argument expression, the conversion sequence is the one
4939 // required to convert the argument expression to the
4940 // underlying type of the reference according to
4941 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4942 // to copy-initializing a temporary of the underlying type with
4943 // the argument expression. Any difference in top-level
4944 // cv-qualification is subsumed by the initialization itself
4945 // and does not constitute a conversion.
4946 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4947 AllowedExplicit::None,
4948 /*InOverloadResolution=*/false,
4949 /*CStyle=*/false,
4950 /*AllowObjCWritebackConversion=*/false,
4951 /*AllowObjCConversionOnExplicit=*/false);
4952
4953 // Of course, that's still a reference binding.
4954 if (ICS.isStandard()) {
4955 ICS.Standard.ReferenceBinding = true;
4956 ICS.Standard.IsLvalueReference = !isRValRef;
4957 ICS.Standard.BindsToFunctionLvalue = false;
4958 ICS.Standard.BindsToRvalue = true;
4959 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4960 ICS.Standard.ObjCLifetimeConversionBinding = false;
4961 } else if (ICS.isUserDefined()) {
4962 const ReferenceType *LValRefType =
4963 ICS.UserDefined.ConversionFunction->getReturnType()
4964 ->getAs<LValueReferenceType>();
4965
4966 // C++ [over.ics.ref]p3:
4967 // Except for an implicit object parameter, for which see 13.3.1, a
4968 // standard conversion sequence cannot be formed if it requires [...]
4969 // binding an rvalue reference to an lvalue other than a function
4970 // lvalue.
4971 // Note that the function case is not possible here.
4972 if (isRValRef && LValRefType) {
4973 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4974 return ICS;
4975 }
4976
4977 ICS.UserDefined.After.ReferenceBinding = true;
4978 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4979 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4980 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4981 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4982 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4983 }
4984
4985 return ICS;
4986}
4987
4988static ImplicitConversionSequence
4989TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4990 bool SuppressUserConversions,
4991 bool InOverloadResolution,
4992 bool AllowObjCWritebackConversion,
4993 bool AllowExplicit = false);
4994
4995/// TryListConversion - Try to copy-initialize a value of type ToType from the
4996/// initializer list From.
4997static ImplicitConversionSequence
4998TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4999 bool SuppressUserConversions,
5000 bool InOverloadResolution,
5001 bool AllowObjCWritebackConversion) {
5002 // C++11 [over.ics.list]p1:
5003 // When an argument is an initializer list, it is not an expression and
5004 // special rules apply for converting it to a parameter type.
5005
5006 ImplicitConversionSequence Result;
5007 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5008
5009 // We need a complete type for what follows. Incomplete types can never be
5010 // initialized from init lists.
5011 if (!S.isCompleteType(From->getBeginLoc(), ToType))
5012 return Result;
5013
5014 // Per DR1467:
5015 // If the parameter type is a class X and the initializer list has a single
5016 // element of type cv U, where U is X or a class derived from X, the
5017 // implicit conversion sequence is the one required to convert the element
5018 // to the parameter type.
5019 //
5020 // Otherwise, if the parameter type is a character array [... ]
5021 // and the initializer list has a single element that is an
5022 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5023 // implicit conversion sequence is the identity conversion.
5024 if (From->getNumInits() == 1) {
5025 if (ToType->isRecordType()) {
5026 QualType InitType = From->getInit(0)->getType();
5027 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5028 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5029 return TryCopyInitialization(S, From->getInit(0), ToType,
5030 SuppressUserConversions,
5031 InOverloadResolution,
5032 AllowObjCWritebackConversion);
5033 }
5034
5035 if (const auto *AT = S.Context.getAsArrayType(ToType)) {
5036 if (S.IsStringInit(From->getInit(0), AT)) {
5037 InitializedEntity Entity =
5038 InitializedEntity::InitializeParameter(S.Context, ToType,
5039 /*Consumed=*/false);
5040 if (S.CanPerformCopyInitialization(Entity, From)) {
5041 Result.setStandard();
5042 Result.Standard.setAsIdentityConversion();
5043 Result.Standard.setFromType(ToType);
5044 Result.Standard.setAllToTypes(ToType);
5045 return Result;
5046 }
5047 }
5048 }
5049 }
5050
5051 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5052 // C++11 [over.ics.list]p2:
5053 // If the parameter type is std::initializer_list<X> or "array of X" and
5054 // all the elements can be implicitly converted to X, the implicit
5055 // conversion sequence is the worst conversion necessary to convert an
5056 // element of the list to X.
5057 //
5058 // C++14 [over.ics.list]p3:
5059 // Otherwise, if the parameter type is "array of N X", if the initializer
5060 // list has exactly N elements or if it has fewer than N elements and X is
5061 // default-constructible, and if all the elements of the initializer list
5062 // can be implicitly converted to X, the implicit conversion sequence is
5063 // the worst conversion necessary to convert an element of the list to X.
5064 //
5065 // FIXME: We're missing a lot of these checks.
5066 bool toStdInitializerList = false;
5067 QualType X;
5068 if (ToType->isArrayType())
5069 X = S.Context.getAsArrayType(ToType)->getElementType();
5070 else
5071 toStdInitializerList = S.isStdInitializerList(ToType, &X);
5072 if (!X.isNull()) {
5073 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5074 Expr *Init = From->getInit(i);
5075 ImplicitConversionSequence ICS =
5076 TryCopyInitialization(S, Init, X, SuppressUserConversions,
5077 InOverloadResolution,
5078 AllowObjCWritebackConversion);
5079 // If a single element isn't convertible, fail.
5080 if (ICS.isBad()) {
5081 Result = ICS;
5082 break;
5083 }
5084 // Otherwise, look for the worst conversion.
5085 if (Result.isBad() || CompareImplicitConversionSequences(
5086 S, From->getBeginLoc(), ICS, Result) ==
5087 ImplicitConversionSequence::Worse)
5088 Result = ICS;
5089 }
5090
5091 // For an empty list, we won't have computed any conversion sequence.
5092 // Introduce the identity conversion sequence.
5093 if (From->getNumInits() == 0) {
5094 Result.setStandard();
5095 Result.Standard.setAsIdentityConversion();
5096 Result.Standard.setFromType(ToType);
5097 Result.Standard.setAllToTypes(ToType);
5098 }
5099
5100 Result.setStdInitializerListElement(toStdInitializerList);
5101 return Result;
5102 }
5103
5104 // C++14 [over.ics.list]p4:
5105 // C++11 [over.ics.list]p3:
5106 // Otherwise, if the parameter is a non-aggregate class X and overload
5107 // resolution chooses a single best constructor [...] the implicit
5108 // conversion sequence is a user-defined conversion sequence. If multiple
5109 // constructors are viable but none is better than the others, the
5110 // implicit conversion sequence is a user-defined conversion sequence.
5111 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5112 // This function can deal with initializer lists.
5113 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5114 AllowedExplicit::None,
5115 InOverloadResolution, /*CStyle=*/false,
5116 AllowObjCWritebackConversion,
5117 /*AllowObjCConversionOnExplicit=*/false);
5118 }
5119
5120 // C++14 [over.ics.list]p5:
5121 // C++11 [over.ics.list]p4:
5122 // Otherwise, if the parameter has an aggregate type which can be
5123 // initialized from the initializer list [...] the implicit conversion
5124 // sequence is a user-defined conversion sequence.
5125 if (ToType->isAggregateType()) {
5126 // Type is an aggregate, argument is an init list. At this point it comes
5127 // down to checking whether the initialization works.
5128 // FIXME: Find out whether this parameter is consumed or not.
5129 InitializedEntity Entity =
5130 InitializedEntity::InitializeParameter(S.Context, ToType,
5131 /*Consumed=*/false);
5132 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5133 From)) {
5134 Result.setUserDefined();
5135 Result.UserDefined.Before.setAsIdentityConversion();
5136 // Initializer lists don't have a type.
5137 Result.UserDefined.Before.setFromType(QualType());
5138 Result.UserDefined.Before.setAllToTypes(QualType());
5139
5140 Result.UserDefined.After.setAsIdentityConversion();
5141 Result.UserDefined.After.setFromType(ToType);
5142 Result.UserDefined.After.setAllToTypes(ToType);
5143 Result.UserDefined.ConversionFunction = nullptr;
5144 }
5145 return Result;
5146 }
5147
5148 // C++14 [over.ics.list]p6:
5149 // C++11 [over.ics.list]p5:
5150 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5151 if (ToType->isReferenceType()) {
5152 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5153 // mention initializer lists in any way. So we go by what list-
5154 // initialization would do and try to extrapolate from that.
5155
5156 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5157
5158 // If the initializer list has a single element that is reference-related
5159 // to the parameter type, we initialize the reference from that.
5160 if (From->getNumInits() == 1) {
5161 Expr *Init = From->getInit(0);
5162
5163 QualType T2 = Init->getType();
5164
5165 // If the initializer is the address of an overloaded function, try
5166 // to resolve the overloaded function. If all goes well, T2 is the
5167 // type of the resulting function.
5168 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5169 DeclAccessPair Found;
5170 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5171 Init, ToType, false, Found))
5172 T2 = Fn->getType();
5173 }
5174
5175 // Compute some basic properties of the types and the initializer.
5176 Sema::ReferenceCompareResult RefRelationship =
5177 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5178
5179 if (RefRelationship >= Sema::Ref_Related) {
5180 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5181 SuppressUserConversions,
5182 /*AllowExplicit=*/false);
5183 }
5184 }
5185
5186 // Otherwise, we bind the reference to a temporary created from the
5187 // initializer list.
5188 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5189 InOverloadResolution,
5190 AllowObjCWritebackConversion);
5191 if (Result.isFailure())
5192 return Result;
5193 assert(!Result.isEllipsis() &&((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5194, __PRETTY_FUNCTION__))
5194 "Sub-initialization cannot result in ellipsis conversion.")((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5194, __PRETTY_FUNCTION__))
;
5195
5196 // Can we even bind to a temporary?
5197 if (ToType->isRValueReferenceType() ||
5198 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5199 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5200 Result.UserDefined.After;
5201 SCS.ReferenceBinding = true;
5202 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5203 SCS.BindsToRvalue = true;
5204 SCS.BindsToFunctionLvalue = false;
5205 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5206 SCS.ObjCLifetimeConversionBinding = false;
5207 } else
5208 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5209 From, ToType);
5210 return Result;
5211 }
5212
5213 // C++14 [over.ics.list]p7:
5214 // C++11 [over.ics.list]p6:
5215 // Otherwise, if the parameter type is not a class:
5216 if (!ToType->isRecordType()) {
5217 // - if the initializer list has one element that is not itself an
5218 // initializer list, the implicit conversion sequence is the one
5219 // required to convert the element to the parameter type.
5220 unsigned NumInits = From->getNumInits();
5221 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5222 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5223 SuppressUserConversions,
5224 InOverloadResolution,
5225 AllowObjCWritebackConversion);
5226 // - if the initializer list has no elements, the implicit conversion
5227 // sequence is the identity conversion.
5228 else if (NumInits == 0) {
5229 Result.setStandard();
5230 Result.Standard.setAsIdentityConversion();
5231 Result.Standard.setFromType(ToType);
5232 Result.Standard.setAllToTypes(ToType);
5233 }
5234 return Result;
5235 }
5236
5237 // C++14 [over.ics.list]p8:
5238 // C++11 [over.ics.list]p7:
5239 // In all cases other than those enumerated above, no conversion is possible
5240 return Result;
5241}
5242
5243/// TryCopyInitialization - Try to copy-initialize a value of type
5244/// ToType from the expression From. Return the implicit conversion
5245/// sequence required to pass this argument, which may be a bad
5246/// conversion sequence (meaning that the argument cannot be passed to
5247/// a parameter of this type). If @p SuppressUserConversions, then we
5248/// do not permit any user-defined conversion sequences.
5249static ImplicitConversionSequence
5250TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5251 bool SuppressUserConversions,
5252 bool InOverloadResolution,
5253 bool AllowObjCWritebackConversion,
5254 bool AllowExplicit) {
5255 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5256 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5257 InOverloadResolution,AllowObjCWritebackConversion);
5258
5259 if (ToType->isReferenceType())
5260 return TryReferenceInit(S, From, ToType,
5261 /*FIXME:*/ From->getBeginLoc(),
5262 SuppressUserConversions, AllowExplicit);
5263
5264 return TryImplicitConversion(S, From, ToType,
5265 SuppressUserConversions,
5266 AllowedExplicit::None,
5267 InOverloadResolution,
5268 /*CStyle=*/false,
5269 AllowObjCWritebackConversion,
5270 /*AllowObjCConversionOnExplicit=*/false);
5271}
5272
5273static bool TryCopyInitialization(const CanQualType FromQTy,
5274 const CanQualType ToQTy,
5275 Sema &S,
5276 SourceLocation Loc,
5277 ExprValueKind FromVK) {
5278 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5279 ImplicitConversionSequence ICS =
5280 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5281
5282 return !ICS.isBad();
5283}
5284
5285/// TryObjectArgumentInitialization - Try to initialize the object
5286/// parameter of the given member function (@c Method) from the
5287/// expression @p From.
5288static ImplicitConversionSequence
5289TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5290 Expr::Classification FromClassification,
5291 CXXMethodDecl *Method,
5292 CXXRecordDecl *ActingContext) {
5293 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5294 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5295 // const volatile object.
5296 Qualifiers Quals = Method->getMethodQualifiers();
5297 if (isa<CXXDestructorDecl>(Method)) {
5298 Quals.addConst();
5299 Quals.addVolatile();
5300 }
5301
5302 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5303
5304 // Set up the conversion sequence as a "bad" conversion, to allow us
5305 // to exit early.
5306 ImplicitConversionSequence ICS;
5307
5308 // We need to have an object of class type.
5309 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5310 FromType = PT->getPointeeType();
5311
5312 // When we had a pointer, it's implicitly dereferenced, so we
5313 // better have an lvalue.
5314 assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0
) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5314, __PRETTY_FUNCTION__))
;
5315 }
5316
5317 assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) :
__assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5317, __PRETTY_FUNCTION__))
;
5318
5319 // C++0x [over.match.funcs]p4:
5320 // For non-static member functions, the type of the implicit object
5321 // parameter is
5322 //
5323 // - "lvalue reference to cv X" for functions declared without a
5324 // ref-qualifier or with the & ref-qualifier
5325 // - "rvalue reference to cv X" for functions declared with the &&
5326 // ref-qualifier
5327 //
5328 // where X is the class of which the function is a member and cv is the
5329 // cv-qualification on the member function declaration.
5330 //
5331 // However, when finding an implicit conversion sequence for the argument, we
5332 // are not allowed to perform user-defined conversions
5333 // (C++ [over.match.funcs]p5). We perform a simplified version of
5334 // reference binding here, that allows class rvalues to bind to
5335 // non-constant references.
5336
5337 // First check the qualifiers.
5338 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5339 if (ImplicitParamType.getCVRQualifiers()
5340 != FromTypeCanon.getLocalCVRQualifiers() &&
5341 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5342 ICS.setBad(BadConversionSequence::bad_qualifiers,
5343 FromType, ImplicitParamType);
5344 return ICS;
5345 }
5346
5347 if (FromTypeCanon.hasAddressSpace()) {
5348 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5349 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5350 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5351 ICS.setBad(BadConversionSequence::bad_qualifiers,
5352 FromType, ImplicitParamType);
5353 return ICS;
5354 }
5355 }
5356
5357 // Check that we have either the same type or a derived type. It
5358 // affects the conversion rank.
5359 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5360 ImplicitConversionKind SecondKind;
5361 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5362 SecondKind = ICK_Identity;
5363 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5364 SecondKind = ICK_Derived_To_Base;
5365 else {
5366 ICS.setBad(BadConversionSequence::unrelated_class,
5367 FromType, ImplicitParamType);
5368 return ICS;
5369 }
5370
5371 // Check the ref-qualifier.
5372 switch (Method->getRefQualifier()) {
5373 case RQ_None:
5374 // Do nothing; we don't care about lvalueness or rvalueness.
5375 break;
5376
5377 case RQ_LValue:
5378 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5379 // non-const lvalue reference cannot bind to an rvalue
5380 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5381 ImplicitParamType);
5382 return ICS;
5383 }
5384 break;
5385
5386 case RQ_RValue:
5387 if (!FromClassification.isRValue()) {
5388 // rvalue reference cannot bind to an lvalue
5389 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5390 ImplicitParamType);
5391 return ICS;
5392 }
5393 break;
5394 }
5395
5396 // Success. Mark this as a reference binding.
5397 ICS.setStandard();
5398 ICS.Standard.setAsIdentityConversion();
5399 ICS.Standard.Second = SecondKind;
5400 ICS.Standard.setFromType(FromType);
5401 ICS.Standard.setAllToTypes(ImplicitParamType);
5402 ICS.Standard.ReferenceBinding = true;
5403 ICS.Standard.DirectBinding = true;
5404 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5405 ICS.Standard.BindsToFunctionLvalue = false;
5406 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5407 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5408 = (Method->getRefQualifier() == RQ_None);
5409 return ICS;
5410}
5411
5412/// PerformObjectArgumentInitialization - Perform initialization of
5413/// the implicit object parameter for the given Method with the given
5414/// expression.
5415ExprResult
5416Sema::PerformObjectArgumentInitialization(Expr *From,
5417 NestedNameSpecifier *Qualifier,
5418 NamedDecl *FoundDecl,
5419 CXXMethodDecl *Method) {
5420 QualType FromRecordType, DestType;
5421 QualType ImplicitParamRecordType =
5422 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5423
5424 Expr::Classification FromClassification;
5425 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5426 FromRecordType = PT->getPointeeType();
5427 DestType = Method->getThisType();
5428 FromClassification = Expr::Classification::makeSimpleLValue();
5429 } else {
5430 FromRecordType = From->getType();
5431 DestType = ImplicitParamRecordType;
5432 FromClassification = From->Classify(Context);
5433
5434 // When performing member access on an rvalue, materialize a temporary.
5435 if (From->isRValue()) {
5436 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5437 Method->getRefQualifier() !=
5438 RefQualifierKind::RQ_RValue);
5439 }
5440 }
5441
5442 // Note that we always use the true parent context when performing
5443 // the actual argument initialization.
5444 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5445 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5446 Method->getParent());
5447 if (ICS.isBad()) {
5448 switch (ICS.Bad.Kind) {
5449 case BadConversionSequence::bad_qualifiers: {
5450 Qualifiers FromQs = FromRecordType.getQualifiers();
5451 Qualifiers ToQs = DestType.getQualifiers();
5452 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5453 if (CVR) {
5454 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5455 << Method->getDeclName() << FromRecordType << (CVR - 1)
5456 << From->getSourceRange();
5457 Diag(Method->getLocation(), diag::note_previous_decl)
5458 << Method->getDeclName();
5459 return ExprError();
5460 }
5461 break;
5462 }
5463
5464 case BadConversionSequence::lvalue_ref_to_rvalue:
5465 case BadConversionSequence::rvalue_ref_to_lvalue: {
5466 bool IsRValueQualified =
5467 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5468 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5469 << Method->getDeclName() << FromClassification.isRValue()
5470 << IsRValueQualified;
5471 Diag(Method->getLocation(), diag::note_previous_decl)
5472 << Method->getDeclName();
5473 return ExprError();
5474 }
5475
5476 case BadConversionSequence::no_conversion:
5477 case BadConversionSequence::unrelated_class:
5478 break;
5479 }
5480
5481 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5482 << ImplicitParamRecordType << FromRecordType
5483 << From->getSourceRange();
5484 }
5485
5486 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5487 ExprResult FromRes =
5488 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5489 if (FromRes.isInvalid())
5490 return ExprError();
5491 From = FromRes.get();
5492 }
5493
5494 if (!Context.hasSameType(From->getType(), DestType)) {
5495 CastKind CK;
5496 QualType PteeTy = DestType->getPointeeType();
5497 LangAS DestAS =
5498 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5499 if (FromRecordType.getAddressSpace() != DestAS)
5500 CK = CK_AddressSpaceConversion;
5501 else
5502 CK = CK_NoOp;
5503 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5504 }
5505 return From;
5506}
5507
5508/// TryContextuallyConvertToBool - Attempt to contextually convert the
5509/// expression From to bool (C++0x [conv]p3).
5510static ImplicitConversionSequence
5511TryContextuallyConvertToBool(Sema &S, Expr *From) {
5512 // C++ [dcl.init]/17.8:
5513 // - Otherwise, if the initialization is direct-initialization, the source
5514 // type is std::nullptr_t, and the destination type is bool, the initial
5515 // value of the object being initialized is false.
5516 if (From->getType()->isNullPtrType())
5517 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5518 S.Context.BoolTy,
5519 From->isGLValue());
5520
5521 // All other direct-initialization of bool is equivalent to an implicit
5522 // conversion to bool in which explicit conversions are permitted.
5523 return TryImplicitConversion(S, From, S.Context.BoolTy,
5524 /*SuppressUserConversions=*/false,
5525 AllowedExplicit::Conversions,
5526 /*InOverloadResolution=*/false,
5527 /*CStyle=*/false,
5528 /*AllowObjCWritebackConversion=*/false,
5529 /*AllowObjCConversionOnExplicit=*/false);
5530}
5531
5532/// PerformContextuallyConvertToBool - Perform a contextual conversion
5533/// of the expression From to bool (C++0x [conv]p3).
5534ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5535 if (checkPlaceholderForOverload(*this, From))
5536 return ExprError();
5537
5538 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5539 if (!ICS.isBad())
5540 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5541
5542 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5543 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5544 << From->getType() << From->getSourceRange();
5545 return ExprError();
5546}
5547
5548/// Check that the specified conversion is permitted in a converted constant
5549/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5550/// is acceptable.
5551static bool CheckConvertedConstantConversions(Sema &S,
5552 StandardConversionSequence &SCS) {
5553 // Since we know that the target type is an integral or unscoped enumeration
5554 // type, most conversion kinds are impossible. All possible First and Third
5555 // conversions are fine.
5556 switch (SCS.Second) {
5557 case ICK_Identity:
5558 case ICK_Integral_Promotion:
5559 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5560 case ICK_Zero_Queue_Conversion:
5561 return true;
5562
5563 case ICK_Boolean_Conversion:
5564 // Conversion from an integral or unscoped enumeration type to bool is
5565 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5566 // conversion, so we allow it in a converted constant expression.
5567 //
5568 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5569 // a lot of popular code. We should at least add a warning for this
5570 // (non-conforming) extension.
5571 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5572 SCS.getToType(2)->isBooleanType();
5573
5574 case ICK_Pointer_Conversion:
5575 case ICK_Pointer_Member:
5576 // C++1z: null pointer conversions and null member pointer conversions are
5577 // only permitted if the source type is std::nullptr_t.
5578 return SCS.getFromType()->isNullPtrType();
5579
5580 case ICK_Floating_Promotion:
5581 case ICK_Complex_Promotion:
5582 case ICK_Floating_Conversion:
5583 case ICK_Complex_Conversion:
5584 case ICK_Floating_Integral:
5585 case ICK_Compatible_Conversion:
5586 case ICK_Derived_To_Base:
5587 case ICK_Vector_Conversion:
5588 case ICK_SVE_Vector_Conversion:
5589 case ICK_Vector_Splat:
5590 case ICK_Complex_Real:
5591 case ICK_Block_Pointer_Conversion:
5592 case ICK_TransparentUnionConversion:
5593 case ICK_Writeback_Conversion:
5594 case ICK_Zero_Event_Conversion:
5595 case ICK_C_Only_Conversion:
5596 case ICK_Incompatible_Pointer_Conversion:
5597 return false;
5598
5599 case ICK_Lvalue_To_Rvalue:
5600 case ICK_Array_To_Pointer:
5601 case ICK_Function_To_Pointer:
5602 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5602)
;
5603
5604 case ICK_Function_Conversion:
5605 case ICK_Qualification:
5606 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5606)
;
5607
5608 case ICK_Num_Conversion_Kinds:
5609 break;
5610 }
5611
5612 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5612)
;
5613}
5614
5615/// CheckConvertedConstantExpression - Check that the expression From is a
5616/// converted constant expression of type T, perform the conversion and produce
5617/// the converted expression, per C++11 [expr.const]p3.
5618static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5619 QualType T, APValue &Value,
5620 Sema::CCEKind CCE,
5621 bool RequireInt,
5622 NamedDecl *Dest) {
5623 assert(S.getLangOpts().CPlusPlus11 &&((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5624, __PRETTY_FUNCTION__))
5624 "converted constant expression outside C++11")((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5624, __PRETTY_FUNCTION__))
;
5625
5626 if (checkPlaceholderForOverload(S, From))
5627 return ExprError();
5628
5629 // C++1z [expr.const]p3:
5630 // A converted constant expression of type T is an expression,
5631 // implicitly converted to type T, where the converted
5632 // expression is a constant expression and the implicit conversion
5633 // sequence contains only [... list of conversions ...].
5634 // C++1z [stmt.if]p2:
5635 // If the if statement is of the form if constexpr, the value of the
5636 // condition shall be a contextually converted constant expression of type
5637 // bool.
5638 ImplicitConversionSequence ICS =
5639 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5640 ? TryContextuallyConvertToBool(S, From)
5641 : TryCopyInitialization(S, From, T,
5642 /*SuppressUserConversions=*/false,
5643 /*InOverloadResolution=*/false,
5644 /*AllowObjCWritebackConversion=*/false,
5645 /*AllowExplicit=*/false);
5646 StandardConversionSequence *SCS = nullptr;
5647 switch (ICS.getKind()) {
5648 case ImplicitConversionSequence::StandardConversion:
5649 SCS = &ICS.Standard;
5650 break;
5651 case ImplicitConversionSequence::UserDefinedConversion:
5652 if (T->isRecordType())
5653 SCS = &ICS.UserDefined.Before;
5654 else
5655 SCS = &ICS.UserDefined.After;
5656 break;
5657 case ImplicitConversionSequence::AmbiguousConversion:
5658 case ImplicitConversionSequence::BadConversion:
5659 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5660 return S.Diag(From->getBeginLoc(),
5661 diag::err_typecheck_converted_constant_expression)
5662 << From->getType() << From->getSourceRange() << T;
5663 return ExprError();
5664
5665 case ImplicitConversionSequence::EllipsisConversion:
5666 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5666)
;
5667 }
5668
5669 // Check that we would only use permitted conversions.
5670 if (!CheckConvertedConstantConversions(S, *SCS)) {
5671 return S.Diag(From->getBeginLoc(),
5672 diag::err_typecheck_converted_constant_expression_disallowed)
5673 << From->getType() << From->getSourceRange() << T;
5674 }
5675 // [...] and where the reference binding (if any) binds directly.
5676 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5677 return S.Diag(From->getBeginLoc(),
5678 diag::err_typecheck_converted_constant_expression_indirect)
5679 << From->getType() << From->getSourceRange() << T;
5680 }
5681
5682 // Usually we can simply apply the ImplicitConversionSequence we formed
5683 // earlier, but that's not guaranteed to work when initializing an object of
5684 // class type.
5685 ExprResult Result;
5686 if (T->isRecordType()) {
5687 assert(CCE == Sema::CCEK_TemplateArg &&((CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr"
) ? static_cast<void> (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5688, __PRETTY_FUNCTION__))
5688 "unexpected class type converted constant expr")((CCE == Sema::CCEK_TemplateArg && "unexpected class type converted constant expr"
) ? static_cast<void> (0) : __assert_fail ("CCE == Sema::CCEK_TemplateArg && \"unexpected class type converted constant expr\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5688, __PRETTY_FUNCTION__))
;
5689 Result = S.PerformCopyInitialization(
5690 InitializedEntity::InitializeTemplateParameter(
5691 T, cast<NonTypeTemplateParmDecl>(Dest)),
5692 SourceLocation(), From);
5693 } else {
5694 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5695 }
5696 if (Result.isInvalid())
5697 return Result;
5698
5699 // C++2a [intro.execution]p5:
5700 // A full-expression is [...] a constant-expression [...]
5701 Result =
5702 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5703 /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5704 if (Result.isInvalid())
5705 return Result;
5706
5707 // Check for a narrowing implicit conversion.
5708 bool ReturnPreNarrowingValue = false;
5709 APValue PreNarrowingValue;
5710 QualType PreNarrowingType;
5711 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5712 PreNarrowingType)) {
5713 case NK_Dependent_Narrowing:
5714 // Implicit conversion to a narrower type, but the expression is
5715 // value-dependent so we can't tell whether it's actually narrowing.
5716 case NK_Variable_Narrowing:
5717 // Implicit conversion to a narrower type, and the value is not a constant
5718 // expression. We'll diagnose this in a moment.
5719 case NK_Not_Narrowing:
5720 break;
5721
5722 case NK_Constant_Narrowing:
5723 if (CCE == Sema::CCEK_ArrayBound &&
5724 PreNarrowingType->isIntegralOrEnumerationType() &&
5725 PreNarrowingValue.isInt()) {
5726 // Don't diagnose array bound narrowing here; we produce more precise
5727 // errors by allowing the un-narrowed value through.
5728 ReturnPreNarrowingValue = true;
5729 break;
5730 }
5731 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5732 << CCE << /*Constant*/ 1
5733 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5734 break;
5735
5736 case NK_Type_Narrowing:
5737 // FIXME: It would be better to diagnose that the expression is not a
5738 // constant expression.
5739 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5740 << CCE << /*Constant*/ 0 << From->getType() << T;
5741 break;
5742 }
5743
5744 if (Result.get()->isValueDependent()) {
5745 Value = APValue();
5746 return Result;
5747 }
5748
5749 // Check the expression is a constant expression.
5750 SmallVector<PartialDiagnosticAt, 8> Notes;
5751 Expr::EvalResult Eval;
5752 Eval.Diag = &Notes;
5753
5754 ConstantExprKind Kind;
5755 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5756 Kind = ConstantExprKind::ClassTemplateArgument;
5757 else if (CCE == Sema::CCEK_TemplateArg)
5758 Kind = ConstantExprKind::NonClassTemplateArgument;
5759 else
5760 Kind = ConstantExprKind::Normal;
5761
5762 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5763 (RequireInt && !Eval.Val.isInt())) {
5764 // The expression can't be folded, so we can't keep it at this position in
5765 // the AST.
5766 Result = ExprError();
5767 } else {
5768 Value = Eval.Val;
5769
5770 if (Notes.empty()) {
5771 // It's a constant expression.
5772 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5773 if (ReturnPreNarrowingValue)
5774 Value = std::move(PreNarrowingValue);
5775 return E;
5776 }
5777 }
5778
5779 // It's not a constant expression. Produce an appropriate diagnostic.
5780 if (Notes.size() == 1 &&
5781 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5782 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5783 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5784 diag::note_constexpr_invalid_template_arg) {
5785 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5786 for (unsigned I = 0; I < Notes.size(); ++I)
5787 S.Diag(Notes[I].first, Notes[I].second);
5788 } else {
5789 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5790 << CCE << From->getSourceRange();
5791 for (unsigned I = 0; I < Notes.size(); ++I)
5792 S.Diag(Notes[I].first, Notes[I].second);
5793 }
5794 return ExprError();
5795}
5796
5797ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5798 APValue &Value, CCEKind CCE,
5799 NamedDecl *Dest) {
5800 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5801 Dest);
5802}
5803
5804ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5805 llvm::APSInt &Value,
5806 CCEKind CCE) {
5807 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")((T->isIntegralOrEnumerationType() && "unexpected converted const type"
) ? static_cast<void> (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 5807, __PRETTY_FUNCTION__))
;
5808
5809 APValue V;
5810 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5811 /*Dest=*/nullptr);
5812 if (!R.isInvalid() && !R.get()->isValueDependent())
5813 Value = V.getInt();
5814 return R;
5815}
5816
5817
5818/// dropPointerConversions - If the given standard conversion sequence
5819/// involves any pointer conversions, remove them. This may change
5820/// the result type of the conversion sequence.
5821static void dropPointerConversion(StandardConversionSequence &SCS) {
5822 if (SCS.Second == ICK_Pointer_Conversion) {
5823 SCS.Second = ICK_Identity;
5824 SCS.Third = ICK_Identity;
5825 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5826 }
5827}
5828
5829/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5830/// convert the expression From to an Objective-C pointer type.
5831static ImplicitConversionSequence
5832TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5833 // Do an implicit conversion to 'id'.
5834 QualType Ty = S.Context.getObjCIdType();
5835 ImplicitConversionSequence ICS
5836 = TryImplicitConversion(S, From, Ty,
5837 // FIXME: Are these flags correct?
5838 /*SuppressUserConversions=*/false,
5839 AllowedExplicit::Conversions,
5840 /*InOverloadResolution=*/false,
5841 /*CStyle=*/false,
5842 /*AllowObjCWritebackConversion=*/false,
5843 /*AllowObjCConversionOnExplicit=*/true);
5844
5845 // Strip off any final conversions to 'id'.
5846 switch (ICS.getKind()) {
5847 case ImplicitConversionSequence::BadConversion:
5848 case ImplicitConversionSequence::AmbiguousConversion:
5849 case ImplicitConversionSequence::EllipsisConversion:
5850 break;
5851
5852 case ImplicitConversionSequence::UserDefinedConversion:
5853 dropPointerConversion(ICS.UserDefined.After);
5854 break;
5855
5856 case ImplicitConversionSequence::StandardConversion:
5857 dropPointerConversion(ICS.Standard);
5858 break;
5859 }
5860
5861 return ICS;
5862}
5863
5864/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5865/// conversion of the expression From to an Objective-C pointer type.
5866/// Returns a valid but null ExprResult if no conversion sequence exists.
5867ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5868 if (checkPlaceholderForOverload(*this, From))
5869 return ExprError();
5870
5871 QualType Ty = Context.getObjCIdType();
5872 ImplicitConversionSequence ICS =
5873 TryContextuallyConvertToObjCPointer(*this, From);
5874 if (!ICS.isBad())
5875 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5876 return ExprResult();
5877}
5878
5879/// Determine whether the provided type is an integral type, or an enumeration
5880/// type of a permitted flavor.
5881bool Sema::ICEConvertDiagnoser::match(QualType T) {
5882 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5883 : T->isIntegralOrUnscopedEnumerationType();
5884}
5885
5886static ExprResult
5887diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5888 Sema::ContextualImplicitConverter &Converter,
5889 QualType T, UnresolvedSetImpl &ViableConversions) {
5890
5891 if (Converter.Suppress)
5892 return ExprError();
5893
5894 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5895 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5896 CXXConversionDecl *Conv =
5897 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5898 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5899 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5900 }
5901 return From;
5902}
5903
5904static bool
5905diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5906 Sema::ContextualImplicitConverter &Converter,
5907 QualType T, bool HadMultipleCandidates,
5908 UnresolvedSetImpl &ExplicitConversions) {
5909 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5910 DeclAccessPair Found = ExplicitConversions[0];
5911 CXXConversionDecl *Conversion =
5912 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5913
5914 // The user probably meant to invoke the given explicit
5915 // conversion; use it.
5916 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5917 std::string TypeStr;
5918 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5919
5920 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5921 << FixItHint::CreateInsertion(From->getBeginLoc(),
5922 "static_cast<" + TypeStr + ">(")
5923 << FixItHint::CreateInsertion(
5924 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5925 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5926
5927 // If we aren't in a SFINAE context, build a call to the
5928 // explicit conversion function.
5929 if (SemaRef.isSFINAEContext())
5930 return true;
5931
5932 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5933 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5934 HadMultipleCandidates);
5935 if (Result.isInvalid())
5936 return true;
5937 // Record usage of conversion in an implicit cast.
5938 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5939 CK_UserDefinedConversion, Result.get(),
5940 nullptr, Result.get()->getValueKind(),
5941 SemaRef.CurFPFeatureOverrides());
5942 }
5943 return false;
5944}
5945
5946static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5947 Sema::ContextualImplicitConverter &Converter,
5948 QualType T, bool HadMultipleCandidates,
5949 DeclAccessPair &Found) {
5950 CXXConversionDecl *Conversion =
5951 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5952 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5953
5954 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5955 if (!Converter.SuppressConversion) {
5956 if (SemaRef.isSFINAEContext())
5957 return true;
5958
5959 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5960 << From->getSourceRange();
5961 }
5962
5963 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5964 HadMultipleCandidates);
5965 if (Result.isInvalid())
5966 return true;
5967 // Record usage of conversion in an implicit cast.
5968 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5969 CK_UserDefinedConversion, Result.get(),
5970 nullptr, Result.get()->getValueKind(),
5971 SemaRef.CurFPFeatureOverrides());
5972 return false;
5973}
5974
5975static ExprResult finishContextualImplicitConversion(
5976 Sema &SemaRef, SourceLocation Loc, Expr *From,
5977 Sema::ContextualImplicitConverter &Converter) {
5978 if (!Converter.match(From->getType()) && !Converter.Suppress)
5979 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5980 << From->getSourceRange();
5981
5982 return SemaRef.DefaultLvalueConversion(From);
5983}
5984
5985static void
5986collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5987 UnresolvedSetImpl &ViableConversions,
5988 OverloadCandidateSet &CandidateSet) {
5989 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5990 DeclAccessPair FoundDecl = ViableConversions[I];
5991 NamedDecl *D = FoundDecl.getDecl();
5992 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5993 if (isa<UsingShadowDecl>(D))
5994 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5995
5996 CXXConversionDecl *Conv;
5997 FunctionTemplateDecl *ConvTemplate;
5998 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5999 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6000 else
6001 Conv = cast<CXXConversionDecl>(D);
6002
6003 if (ConvTemplate)
6004 SemaRef.AddTemplateConversionCandidate(
6005 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6006 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6007 else
6008 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6009 ToType, CandidateSet,
6010 /*AllowObjCConversionOnExplicit=*/false,
6011 /*AllowExplicit*/ true);
6012 }
6013}
6014
6015/// Attempt to convert the given expression to a type which is accepted
6016/// by the given converter.
6017///
6018/// This routine will attempt to convert an expression of class type to a
6019/// type accepted by the specified converter. In C++11 and before, the class
6020/// must have a single non-explicit conversion function converting to a matching
6021/// type. In C++1y, there can be multiple such conversion functions, but only
6022/// one target type.
6023///
6024/// \param Loc The source location of the construct that requires the
6025/// conversion.
6026///
6027/// \param From The expression we're converting from.
6028///
6029/// \param Converter Used to control and diagnose the conversion process.
6030///
6031/// \returns The expression, converted to an integral or enumeration type if
6032/// successful.
6033ExprResult Sema::PerformContextualImplicitConversion(
6034 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6035 // We can't perform any more checking for type-dependent expressions.
6036 if (From->isTypeDependent())
6037 return From;
6038
6039 // Process placeholders immediately.
6040 if (From->hasPlaceholderType()) {
6041 ExprResult result = CheckPlaceholderExpr(From);
6042 if (result.isInvalid())
6043 return result;
6044 From = result.get();
6045 }
6046
6047 // If the expression already has a matching type, we're golden.
6048 QualType T = From->getType();
6049 if (Converter.match(T))
6050 return DefaultLvalueConversion(From);
6051
6052 // FIXME: Check for missing '()' if T is a function type?
6053
6054 // We can only perform contextual implicit conversions on objects of class
6055 // type.
6056 const RecordType *RecordTy = T->getAs<RecordType>();
6057 if (!RecordTy || !getLangOpts().CPlusPlus) {
6058 if (!Converter.Suppress)
6059 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6060 return From;
6061 }
6062
6063 // We must have a complete class type.
6064 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6065 ContextualImplicitConverter &Converter;
6066 Expr *From;
6067
6068 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6069 : Converter(Converter), From(From) {}
6070
6071 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6072 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6073 }
6074 } IncompleteDiagnoser(Converter, From);
6075
6076 if (Converter.Suppress ? !isCompleteType(Loc, T)
6077 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6078 return From;
6079
6080 // Look for a conversion to an integral or enumeration type.
6081 UnresolvedSet<4>
6082 ViableConversions; // These are *potentially* viable in C++1y.
6083 UnresolvedSet<4> ExplicitConversions;
6084 const auto &Conversions =
6085 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6086
6087 bool HadMultipleCandidates =
6088 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6089
6090 // To check that there is only one target type, in C++1y:
6091 QualType ToType;
6092 bool HasUniqueTargetType = true;
6093
6094 // Collect explicit or viable (potentially in C++1y) conversions.
6095 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6096 NamedDecl *D = (*I)->getUnderlyingDecl();
6097 CXXConversionDecl *Conversion;
6098 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6099 if (ConvTemplate) {
6100 if (getLangOpts().CPlusPlus14)
6101 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6102 else
6103 continue; // C++11 does not consider conversion operator templates(?).
6104 } else
6105 Conversion = cast<CXXConversionDecl>(D);
6106
6107 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6109, __PRETTY_FUNCTION__))
6108 "Conversion operator templates are considered potentially "(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6109, __PRETTY_FUNCTION__))
6109 "viable in C++1y")(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6109, __PRETTY_FUNCTION__))
;
6110
6111 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6112 if (Converter.match(CurToType) || ConvTemplate) {
6113
6114 if (Conversion->isExplicit()) {
6115 // FIXME: For C++1y, do we need this restriction?
6116 // cf. diagnoseNoViableConversion()
6117 if (!ConvTemplate)
6118 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6119 } else {
6120 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6121 if (ToType.isNull())
6122 ToType = CurToType.getUnqualifiedType();
6123 else if (HasUniqueTargetType &&
6124 (CurToType.getUnqualifiedType() != ToType))
6125 HasUniqueTargetType = false;
6126 }
6127 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6128 }
6129 }
6130 }
6131
6132 if (getLangOpts().CPlusPlus14) {
6133 // C++1y [conv]p6:
6134 // ... An expression e of class type E appearing in such a context
6135 // is said to be contextually implicitly converted to a specified
6136 // type T and is well-formed if and only if e can be implicitly
6137 // converted to a type T that is determined as follows: E is searched
6138 // for conversion functions whose return type is cv T or reference to
6139 // cv T such that T is allowed by the context. There shall be
6140 // exactly one such T.
6141
6142 // If no unique T is found:
6143 if (ToType.isNull()) {
6144 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6145 HadMultipleCandidates,
6146 ExplicitConversions))
6147 return ExprError();
6148 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6149 }
6150
6151 // If more than one unique Ts are found:
6152 if (!HasUniqueTargetType)
6153 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6154 ViableConversions);
6155
6156 // If one unique T is found:
6157 // First, build a candidate set from the previously recorded
6158 // potentially viable conversions.
6159 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6160 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6161 CandidateSet);
6162
6163 // Then, perform overload resolution over the candidate set.
6164 OverloadCandidateSet::iterator Best;
6165 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6166 case OR_Success: {
6167 // Apply this conversion.
6168 DeclAccessPair Found =
6169 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6170 if (recordConversion(*this, Loc, From, Converter, T,
6171 HadMultipleCandidates, Found))
6172 return ExprError();
6173 break;
6174 }
6175 case OR_Ambiguous:
6176 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6177 ViableConversions);
6178 case OR_No_Viable_Function:
6179 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6180 HadMultipleCandidates,
6181 ExplicitConversions))
6182 return ExprError();
6183 LLVM_FALLTHROUGH[[gnu::fallthrough]];
6184 case OR_Deleted:
6185 // We'll complain below about a non-integral condition type.
6186 break;
6187 }
6188 } else {
6189 switch (ViableConversions.size()) {
6190 case 0: {
6191 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6192 HadMultipleCandidates,
6193 ExplicitConversions))
6194 return ExprError();
6195
6196 // We'll complain below about a non-integral condition type.
6197 break;
6198 }
6199 case 1: {
6200 // Apply this conversion.
6201 DeclAccessPair Found = ViableConversions[0];
6202 if (recordConversion(*this, Loc, From, Converter, T,
6203 HadMultipleCandidates, Found))
6204 return ExprError();
6205 break;
6206 }
6207 default:
6208 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6209 ViableConversions);
6210 }
6211 }
6212
6213 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6214}
6215
6216/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6217/// an acceptable non-member overloaded operator for a call whose
6218/// arguments have types T1 (and, if non-empty, T2). This routine
6219/// implements the check in C++ [over.match.oper]p3b2 concerning
6220/// enumeration types.
6221static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6222 FunctionDecl *Fn,
6223 ArrayRef<Expr *> Args) {
6224 QualType T1 = Args[0]->getType();
6225 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6226
6227 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6228 return true;
6229
6230 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6231 return true;
6232
6233 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6234 if (Proto->getNumParams() < 1)
6235 return false;
6236
6237 if (T1->isEnumeralType()) {
6238 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6239 if (Context.hasSameUnqualifiedType(T1, ArgType))
6240 return true;
6241 }
6242
6243 if (Proto->getNumParams() < 2)
6244 return false;
6245
6246 if (!T2.isNull() && T2->isEnumeralType()) {
6247 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6248 if (Context.hasSameUnqualifiedType(T2, ArgType))
6249 return true;
6250 }
6251
6252 return false;
6253}
6254
6255/// AddOverloadCandidate - Adds the given function to the set of
6256/// candidate functions, using the given function call arguments. If
6257/// @p SuppressUserConversions, then don't allow user-defined
6258/// conversions via constructors or conversion operators.
6259///
6260/// \param PartialOverloading true if we are performing "partial" overloading
6261/// based on an incomplete set of function arguments. This feature is used by
6262/// code completion.
6263void Sema::AddOverloadCandidate(
6264 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6265 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6266 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6267 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6268 OverloadCandidateParamOrder PO) {
6269 const FunctionProtoType *Proto
6270 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6271 assert(Proto && "Functions without a prototype cannot be overloaded")((Proto && "Functions without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6271, __PRETTY_FUNCTION__))
;
6272 assert(!Function->getDescribedFunctionTemplate() &&((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6273, __PRETTY_FUNCTION__))
6273 "Use AddTemplateOverloadCandidate for function templates")((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6273, __PRETTY_FUNCTION__))
;
6274
6275 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6276 if (!isa<CXXConstructorDecl>(Method)) {
6277 // If we get here, it's because we're calling a member function
6278 // that is named without a member access expression (e.g.,
6279 // "this->f") that was either written explicitly or created
6280 // implicitly. This can happen with a qualified call to a member
6281 // function, e.g., X::f(). We use an empty type for the implied
6282 // object argument (C++ [over.call.func]p3), and the acting context
6283 // is irrelevant.
6284 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6285 Expr::Classification::makeSimpleLValue(), Args,
6286 CandidateSet, SuppressUserConversions,
6287 PartialOverloading, EarlyConversions, PO);
6288 return;
6289 }
6290 // We treat a constructor like a non-member function, since its object
6291 // argument doesn't participate in overload resolution.
6292 }
6293
6294 if (!CandidateSet.isNewCandidate(Function, PO))
6295 return;
6296
6297 // C++11 [class.copy]p11: [DR1402]
6298 // A defaulted move constructor that is defined as deleted is ignored by
6299 // overload resolution.
6300 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6301 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6302 Constructor->isMoveConstructor())
6303 return;
6304
6305 // Overload resolution is always an unevaluated context.
6306 EnterExpressionEvaluationContext Unevaluated(
6307 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6308
6309 // C++ [over.match.oper]p3:
6310 // if no operand has a class type, only those non-member functions in the
6311 // lookup set that have a first parameter of type T1 or "reference to
6312 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6313 // is a right operand) a second parameter of type T2 or "reference to
6314 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6315 // candidate functions.
6316 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6317 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6318 return;
6319
6320 // Add this candidate
6321 OverloadCandidate &Candidate =
6322 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6323 Candidate.FoundDecl = FoundDecl;
6324 Candidate.Function = Function;
6325 Candidate.Viable = true;
6326 Candidate.RewriteKind =
6327 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6328 Candidate.IsSurrogate = false;
6329 Candidate.IsADLCandidate = IsADLCandidate;
6330 Candidate.IgnoreObjectArgument = false;
6331 Candidate.ExplicitCallArguments = Args.size();
6332
6333 // Explicit functions are not actually candidates at all if we're not
6334 // allowing them in this context, but keep them around so we can point
6335 // to them in diagnostics.
6336 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6337 Candidate.Viable = false;
6338 Candidate.FailureKind = ovl_fail_explicit;
6339 return;
6340 }
6341
6342 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6343 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6344 Candidate.Viable = false;
6345 Candidate.FailureKind = ovl_non_default_multiversion_function;
6346 return;
6347 }
6348
6349 if (Constructor) {
6350 // C++ [class.copy]p3:
6351 // A member function template is never instantiated to perform the copy
6352 // of a class object to an object of its class type.
6353 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6354 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6355 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6356 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6357 ClassType))) {
6358 Candidate.Viable = false;
6359 Candidate.FailureKind = ovl_fail_illegal_constructor;
6360 return;
6361 }
6362
6363 // C++ [over.match.funcs]p8: (proposed DR resolution)
6364 // A constructor inherited from class type C that has a first parameter
6365 // of type "reference to P" (including such a constructor instantiated
6366 // from a template) is excluded from the set of candidate functions when
6367 // constructing an object of type cv D if the argument list has exactly
6368 // one argument and D is reference-related to P and P is reference-related
6369 // to C.
6370 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6371 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6372 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6373 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6374 QualType C = Context.getRecordType(Constructor->getParent());
6375 QualType D = Context.getRecordType(Shadow->getParent());
6376 SourceLocation Loc = Args.front()->getExprLoc();
6377 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6378 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6379 Candidate.Viable = false;
6380 Candidate.FailureKind = ovl_fail_inhctor_slice;
6381 return;
6382 }
6383 }
6384
6385 // Check that the constructor is capable of constructing an object in the
6386 // destination address space.
6387 if (!Qualifiers::isAddressSpaceSupersetOf(
6388 Constructor->getMethodQualifiers().getAddressSpace(),
6389 CandidateSet.getDestAS())) {
6390 Candidate.Viable = false;
6391 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6392 }
6393 }
6394
6395 unsigned NumParams = Proto->getNumParams();
6396
6397 // (C++ 13.3.2p2): A candidate function having fewer than m
6398 // parameters is viable only if it has an ellipsis in its parameter
6399 // list (8.3.5).
6400 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6401 !Proto->isVariadic()) {
6402 Candidate.Viable = false;
6403 Candidate.FailureKind = ovl_fail_too_many_arguments;
6404 return;
6405 }
6406
6407 // (C++ 13.3.2p2): A candidate function having more than m parameters
6408 // is viable only if the (m+1)st parameter has a default argument
6409 // (8.3.6). For the purposes of overload resolution, the
6410 // parameter list is truncated on the right, so that there are
6411 // exactly m parameters.
6412 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6413 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6414 // Not enough arguments.
6415 Candidate.Viable = false;
6416 Candidate.FailureKind = ovl_fail_too_few_arguments;
6417 return;
6418 }
6419
6420 // (CUDA B.1): Check for invalid calls between targets.
6421 if (getLangOpts().CUDA)
6422 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6423 // Skip the check for callers that are implicit members, because in this
6424 // case we may not yet know what the member's target is; the target is
6425 // inferred for the member automatically, based on the bases and fields of
6426 // the class.
6427 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6428 Candidate.Viable = false;
6429 Candidate.FailureKind = ovl_fail_bad_target;
6430 return;
6431 }
6432
6433 if (Function->getTrailingRequiresClause()) {
6434 ConstraintSatisfaction Satisfaction;
6435 if (CheckFunctionConstraints(Function, Satisfaction) ||
6436 !Satisfaction.IsSatisfied) {
6437 Candidate.Viable = false;
6438 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6439 return;
6440 }
6441 }
6442
6443 // Determine the implicit conversion sequences for each of the
6444 // arguments.
6445 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6446 unsigned ConvIdx =
6447 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6448 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6449 // We already formed a conversion sequence for this parameter during
6450 // template argument deduction.
6451 } else if (ArgIdx < NumParams) {
6452 // (C++ 13.3.2p3): for F to be a viable function, there shall
6453 // exist for each argument an implicit conversion sequence
6454 // (13.3.3.1) that converts that argument to the corresponding
6455 // parameter of F.
6456 QualType ParamType = Proto->getParamType(ArgIdx);
6457 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6458 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6459 /*InOverloadResolution=*/true,
6460 /*AllowObjCWritebackConversion=*/
6461 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6462 if (Candidate.Conversions[ConvIdx].isBad()) {
6463 Candidate.Viable = false;
6464 Candidate.FailureKind = ovl_fail_bad_conversion;
6465 return;
6466 }
6467 } else {
6468 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6469 // argument for which there is no corresponding parameter is
6470 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6471 Candidate.Conversions[ConvIdx].setEllipsis();
6472 }
6473 }
6474
6475 if (EnableIfAttr *FailedAttr =
6476 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6477 Candidate.Viable = false;
6478 Candidate.FailureKind = ovl_fail_enable_if;
6479 Candidate.DeductionFailure.Data = FailedAttr;
6480 return;
6481 }
6482
6483 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6484 Candidate.Viable = false;
6485 Candidate.FailureKind = ovl_fail_ext_disabled;
6486 return;
6487 }
6488}
6489
6490ObjCMethodDecl *
6491Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6492 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6493 if (Methods.size() <= 1)
6494 return nullptr;
6495
6496 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6497 bool Match = true;
6498 ObjCMethodDecl *Method = Methods[b];
6499 unsigned NumNamedArgs = Sel.getNumArgs();
6500 // Method might have more arguments than selector indicates. This is due
6501 // to addition of c-style arguments in method.
6502 if (Method->param_size() > NumNamedArgs)
6503 NumNamedArgs = Method->param_size();
6504 if (Args.size() < NumNamedArgs)
6505 continue;
6506
6507 for (unsigned i = 0; i < NumNamedArgs; i++) {
6508 // We can't do any type-checking on a type-dependent argument.
6509 if (Args[i]->isTypeDependent()) {
6510 Match = false;
6511 break;
6512 }
6513
6514 ParmVarDecl *param = Method->parameters()[i];
6515 Expr *argExpr = Args[i];
6516 assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6516, __PRETTY_FUNCTION__))
;
6517
6518 // Strip the unbridged-cast placeholder expression off unless it's
6519 // a consumed argument.
6520 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6521 !param->hasAttr<CFConsumedAttr>())
6522 argExpr = stripARCUnbridgedCast(argExpr);
6523
6524 // If the parameter is __unknown_anytype, move on to the next method.
6525 if (param->getType() == Context.UnknownAnyTy) {
6526 Match = false;
6527 break;
6528 }
6529
6530 ImplicitConversionSequence ConversionState
6531 = TryCopyInitialization(*this, argExpr, param->getType(),
6532 /*SuppressUserConversions*/false,
6533 /*InOverloadResolution=*/true,
6534 /*AllowObjCWritebackConversion=*/
6535 getLangOpts().ObjCAutoRefCount,
6536 /*AllowExplicit*/false);
6537 // This function looks for a reasonably-exact match, so we consider
6538 // incompatible pointer conversions to be a failure here.
6539 if (ConversionState.isBad() ||
6540 (ConversionState.isStandard() &&
6541 ConversionState.Standard.Second ==
6542 ICK_Incompatible_Pointer_Conversion)) {
6543 Match = false;
6544 break;
6545 }
6546 }
6547 // Promote additional arguments to variadic methods.
6548 if (Match && Method->isVariadic()) {
6549 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6550 if (Args[i]->isTypeDependent()) {
6551 Match = false;
6552 break;
6553 }
6554 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6555 nullptr);
6556 if (Arg.isInvalid()) {
6557 Match = false;
6558 break;
6559 }
6560 }
6561 } else {
6562 // Check for extra arguments to non-variadic methods.
6563 if (Args.size() != NumNamedArgs)
6564 Match = false;
6565 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6566 // Special case when selectors have no argument. In this case, select
6567 // one with the most general result type of 'id'.
6568 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6569 QualType ReturnT = Methods[b]->getReturnType();
6570 if (ReturnT->isObjCIdType())
6571 return Methods[b];
6572 }
6573 }
6574 }
6575
6576 if (Match)
6577 return Method;
6578 }
6579 return nullptr;
6580}
6581
6582static bool convertArgsForAvailabilityChecks(
6583 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6584 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6585 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6586 if (ThisArg) {
6587 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6588 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6589, __PRETTY_FUNCTION__))
6589 "Shouldn't have `this` for ctors!")((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6589, __PRETTY_FUNCTION__))
;
6590 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")((!Method->isStatic() && "Shouldn't have `this` for static methods!"
) ? static_cast<void> (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6590, __PRETTY_FUNCTION__))
;
6591 ExprResult R = S.PerformObjectArgumentInitialization(
6592 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6593 if (R.isInvalid())
6594 return false;
6595 ConvertedThis = R.get();
6596 } else {
6597 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6598 (void)MD;
6599 assert((MissingImplicitThis || MD->isStatic() ||(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6601, __PRETTY_FUNCTION__))
6600 isa<CXXConstructorDecl>(MD)) &&(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6601, __PRETTY_FUNCTION__))
6601 "Expected `this` for non-ctor instance methods")(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6601, __PRETTY_FUNCTION__))
;
6602 }
6603 ConvertedThis = nullptr;
6604 }
6605
6606 // Ignore any variadic arguments. Converting them is pointless, since the
6607 // user can't refer to them in the function condition.
6608 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6609
6610 // Convert the arguments.
6611 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6612 ExprResult R;
6613 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6614 S.Context, Function->getParamDecl(I)),
6615 SourceLocation(), Args[I]);
6616
6617 if (R.isInvalid())
6618 return false;
6619
6620 ConvertedArgs.push_back(R.get());
6621 }
6622
6623 if (Trap.hasErrorOccurred())
6624 return false;
6625
6626 // Push default arguments if needed.
6627 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6628 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6629 ParmVarDecl *P = Function->getParamDecl(i);
6630 if (!P->hasDefaultArg())
6631 return false;
6632 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6633 if (R.isInvalid())
6634 return false;
6635 ConvertedArgs.push_back(R.get());
6636 }
6637
6638 if (Trap.hasErrorOccurred())
6639 return false;
6640 }
6641 return true;
6642}
6643
6644EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6645 SourceLocation CallLoc,
6646 ArrayRef<Expr *> Args,
6647 bool MissingImplicitThis) {
6648 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6649 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6650 return nullptr;
6651
6652 SFINAETrap Trap(*this);
6653 SmallVector<Expr *, 16> ConvertedArgs;
6654 // FIXME: We should look into making enable_if late-parsed.
6655 Expr *DiscardedThis;
6656 if (!convertArgsForAvailabilityChecks(
6657 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6658 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6659 return *EnableIfAttrs.begin();
6660
6661 for (auto *EIA : EnableIfAttrs) {
6662 APValue Result;
6663 // FIXME: This doesn't consider value-dependent cases, because doing so is
6664 // very difficult. Ideally, we should handle them more gracefully.
6665 if (EIA->getCond()->isValueDependent() ||
6666 !EIA->getCond()->EvaluateWithSubstitution(
6667 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6668 return EIA;
6669
6670 if (!Result.isInt() || !Result.getInt().getBoolValue())
6671 return EIA;
6672 }
6673 return nullptr;
6674}
6675
6676template <typename CheckFn>
6677static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6678 bool ArgDependent, SourceLocation Loc,
6679 CheckFn &&IsSuccessful) {
6680 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6681 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6682 if (ArgDependent == DIA->getArgDependent())
6683 Attrs.push_back(DIA);
6684 }
6685
6686 // Common case: No diagnose_if attributes, so we can quit early.
6687 if (Attrs.empty())
6688 return false;
6689
6690 auto WarningBegin = std::stable_partition(
6691 Attrs.begin(), Attrs.end(),
6692 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6693
6694 // Note that diagnose_if attributes are late-parsed, so they appear in the
6695 // correct order (unlike enable_if attributes).
6696 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6697 IsSuccessful);
6698 if (ErrAttr != WarningBegin) {
6699 const DiagnoseIfAttr *DIA = *ErrAttr;
6700 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6701 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6702 << DIA->getParent() << DIA->getCond()->getSourceRange();
6703 return true;
6704 }
6705
6706 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6707 if (IsSuccessful(DIA)) {
6708 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6709 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6710 << DIA->getParent() << DIA->getCond()->getSourceRange();
6711 }
6712
6713 return false;
6714}
6715
6716bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6717 const Expr *ThisArg,
6718 ArrayRef<const Expr *> Args,
6719 SourceLocation Loc) {
6720 return diagnoseDiagnoseIfAttrsWith(
6721 *this, Function, /*ArgDependent=*/true, Loc,
6722 [&](const DiagnoseIfAttr *DIA) {
6723 APValue Result;
6724 // It's sane to use the same Args for any redecl of this function, since
6725 // EvaluateWithSubstitution only cares about the position of each
6726 // argument in the arg list, not the ParmVarDecl* it maps to.
6727 if (!DIA->getCond()->EvaluateWithSubstitution(
6728 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6729 return false;
6730 return Result.isInt() && Result.getInt().getBoolValue();
6731 });
6732}
6733
6734bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6735 SourceLocation Loc) {
6736 return diagnoseDiagnoseIfAttrsWith(
6737 *this, ND, /*ArgDependent=*/false, Loc,
6738 [&](const DiagnoseIfAttr *DIA) {
6739 bool Result;
6740 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6741 Result;
6742 });
6743}
6744
6745/// Add all of the function declarations in the given function set to
6746/// the overload candidate set.
6747void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6748 ArrayRef<Expr *> Args,
6749 OverloadCandidateSet &CandidateSet,
6750 TemplateArgumentListInfo *ExplicitTemplateArgs,
6751 bool SuppressUserConversions,
6752 bool PartialOverloading,
6753 bool FirstArgumentIsBase) {
6754 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6755 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6756 ArrayRef<Expr *> FunctionArgs = Args;
6757
6758 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6759 FunctionDecl *FD =
6760 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6761
6762 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6763 QualType ObjectType;
6764 Expr::Classification ObjectClassification;
6765 if (Args.size() > 0) {
6766 if (Expr *E = Args[0]) {
6767 // Use the explicit base to restrict the lookup:
6768 ObjectType = E->getType();
6769 // Pointers in the object arguments are implicitly dereferenced, so we
6770 // always classify them as l-values.
6771 if (!ObjectType.isNull() && ObjectType->isPointerType())
6772 ObjectClassification = Expr::Classification::makeSimpleLValue();
6773 else
6774 ObjectClassification = E->Classify(Context);
6775 } // .. else there is an implicit base.
6776 FunctionArgs = Args.slice(1);
6777 }
6778 if (FunTmpl) {
6779 AddMethodTemplateCandidate(
6780 FunTmpl, F.getPair(),
6781 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6782 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6783 FunctionArgs, CandidateSet, SuppressUserConversions,
6784 PartialOverloading);
6785 } else {
6786 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6787 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6788 ObjectClassification, FunctionArgs, CandidateSet,
6789 SuppressUserConversions, PartialOverloading);
6790 }
6791 } else {
6792 // This branch handles both standalone functions and static methods.
6793
6794 // Slice the first argument (which is the base) when we access
6795 // static method as non-static.
6796 if (Args.size() > 0 &&
6797 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6798 !isa<CXXConstructorDecl>(FD)))) {
6799 assert(cast<CXXMethodDecl>(FD)->isStatic())((cast<CXXMethodDecl>(FD)->isStatic()) ? static_cast
<void> (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6799, __PRETTY_FUNCTION__))
;
6800 FunctionArgs = Args.slice(1);
6801 }
6802 if (FunTmpl) {
6803 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6804 ExplicitTemplateArgs, FunctionArgs,
6805 CandidateSet, SuppressUserConversions,
6806 PartialOverloading);
6807 } else {
6808 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6809 SuppressUserConversions, PartialOverloading);
6810 }
6811 }
6812 }
6813}
6814
6815/// AddMethodCandidate - Adds a named decl (which is some kind of
6816/// method) as a method candidate to the given overload set.
6817void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6818 Expr::Classification ObjectClassification,
6819 ArrayRef<Expr *> Args,
6820 OverloadCandidateSet &CandidateSet,
6821 bool SuppressUserConversions,
6822 OverloadCandidateParamOrder PO) {
6823 NamedDecl *Decl = FoundDecl.getDecl();
6824 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6825
6826 if (isa<UsingShadowDecl>(Decl))
6827 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6828
6829 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6830 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6831, __PRETTY_FUNCTION__))
6831 "Expected a member function template")((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6831, __PRETTY_FUNCTION__))
;
6832 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6833 /*ExplicitArgs*/ nullptr, ObjectType,
6834 ObjectClassification, Args, CandidateSet,
6835 SuppressUserConversions, false, PO);
6836 } else {
6837 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6838 ObjectType, ObjectClassification, Args, CandidateSet,
6839 SuppressUserConversions, false, None, PO);
6840 }
6841}
6842
6843/// AddMethodCandidate - Adds the given C++ member function to the set
6844/// of candidate functions, using the given function call arguments
6845/// and the object argument (@c Object). For example, in a call
6846/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6847/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6848/// allow user-defined conversions via constructors or conversion
6849/// operators.
6850void
6851Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6852 CXXRecordDecl *ActingContext, QualType ObjectType,
6853 Expr::Classification ObjectClassification,
6854 ArrayRef<Expr *> Args,
6855 OverloadCandidateSet &CandidateSet,
6856 bool SuppressUserConversions,
6857 bool PartialOverloading,
6858 ConversionSequenceList EarlyConversions,
6859 OverloadCandidateParamOrder PO) {
6860 const FunctionProtoType *Proto
6861 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6862 assert(Proto && "Methods without a prototype cannot be overloaded")((Proto && "Methods without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6862, __PRETTY_FUNCTION__))
;
6863 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6864, __PRETTY_FUNCTION__))
6864 "Use AddOverloadCandidate for constructors")((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 6864, __PRETTY_FUNCTION__))
;
6865
6866 if (!CandidateSet.isNewCandidate(Method, PO))
6867 return;
6868
6869 // C++11 [class.copy]p23: [DR1402]
6870 // A defaulted move assignment operator that is defined as deleted is
6871 // ignored by overload resolution.
6872 if (Method->isDefaulted() && Method->isDeleted() &&
6873 Method->isMoveAssignmentOperator())
6874 return;
6875
6876 // Overload resolution is always an unevaluated context.
6877 EnterExpressionEvaluationContext Unevaluated(
6878 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6879
6880 // Add this candidate
6881 OverloadCandidate &Candidate =
6882 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6883 Candidate.FoundDecl = FoundDecl;
6884 Candidate.Function = Method;
6885 Candidate.RewriteKind =
6886 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6887 Candidate.IsSurrogate = false;
6888 Candidate.IgnoreObjectArgument = false;
6889 Candidate.ExplicitCallArguments = Args.size();
6890
6891 unsigned NumParams = Proto->getNumParams();
6892
6893 // (C++ 13.3.2p2): A candidate function having fewer than m
6894 // parameters is viable only if it has an ellipsis in its parameter
6895 // list (8.3.5).
6896 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6897 !Proto->isVariadic()) {
6898 Candidate.Viable = false;
6899 Candidate.FailureKind = ovl_fail_too_many_arguments;
6900 return;
6901 }
6902
6903 // (C++ 13.3.2p2): A candidate function having more than m parameters
6904 // is viable only if the (m+1)st parameter has a default argument
6905 // (8.3.6). For the purposes of overload resolution, the
6906 // parameter list is truncated on the right, so that there are
6907 // exactly m parameters.
6908 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6909 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6910 // Not enough arguments.
6911 Candidate.Viable = false;
6912 Candidate.FailureKind = ovl_fail_too_few_arguments;
6913 return;
6914 }
6915
6916 Candidate.Viable = true;
6917
6918 if (Method->isStatic() || ObjectType.isNull())
6919 // The implicit object argument is ignored.
6920 Candidate.IgnoreObjectArgument = true;
6921 else {
6922 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6923 // Determine the implicit conversion sequence for the object
6924 // parameter.
6925 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6926 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6927 Method, ActingContext);
6928 if (Candidate.Conversions[ConvIdx].isBad()) {
6929 Candidate.Viable = false;
6930 Candidate.FailureKind = ovl_fail_bad_conversion;
6931 return;
6932 }
6933 }
6934
6935 // (CUDA B.1): Check for invalid calls between targets.
6936 if (getLangOpts().CUDA)
6937 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6938 if (!IsAllowedCUDACall(Caller, Method)) {
6939 Candidate.Viable = false;
6940 Candidate.FailureKind = ovl_fail_bad_target;
6941 return;
6942 }
6943
6944 if (Method->getTrailingRequiresClause()) {
6945 ConstraintSatisfaction Satisfaction;
6946 if (CheckFunctionConstraints(Method, Satisfaction) ||
6947 !Satisfaction.IsSatisfied) {
6948 Candidate.Viable = false;
6949 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6950 return;
6951 }
6952 }
6953
6954 // Determine the implicit conversion sequences for each of the
6955 // arguments.
6956 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6957 unsigned ConvIdx =
6958 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6959 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6960 // We already formed a conversion sequence for this parameter during
6961 // template argument deduction.
6962 } else if (ArgIdx < NumParams) {
6963 // (C++ 13.3.2p3): for F to be a viable function, there shall
6964 // exist for each argument an implicit conversion sequence
6965 // (13.3.3.1) that converts that argument to the corresponding
6966 // parameter of F.
6967 QualType ParamType = Proto->getParamType(ArgIdx);
6968 Candidate.Conversions[ConvIdx]
6969 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6970 SuppressUserConversions,
6971 /*InOverloadResolution=*/true,
6972 /*AllowObjCWritebackConversion=*/
6973 getLangOpts().ObjCAutoRefCount);
6974 if (Candidate.Conversions[ConvIdx].isBad()) {
6975 Candidate.Viable = false;
6976 Candidate.FailureKind = ovl_fail_bad_conversion;
6977 return;
6978 }
6979 } else {
6980 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6981 // argument for which there is no corresponding parameter is
6982 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6983 Candidate.Conversions[ConvIdx].setEllipsis();
6984 }
6985 }
6986
6987 if (EnableIfAttr *FailedAttr =
6988 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
6989 Candidate.Viable = false;
6990 Candidate.FailureKind = ovl_fail_enable_if;
6991 Candidate.DeductionFailure.Data = FailedAttr;
6992 return;
6993 }
6994
6995 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6996 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6997 Candidate.Viable = false;
6998 Candidate.FailureKind = ovl_non_default_multiversion_function;
6999 }
7000}
7001
7002/// Add a C++ member function template as a candidate to the candidate
7003/// set, using template argument deduction to produce an appropriate member
7004/// function template specialization.
7005void Sema::AddMethodTemplateCandidate(
7006 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7007 CXXRecordDecl *ActingContext,
7008 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7009 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7010 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7011 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7012 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7013 return;
7014
7015 // C++ [over.match.funcs]p7:
7016 // In each case where a candidate is a function template, candidate
7017 // function template specializations are generated using template argument
7018 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7019 // candidate functions in the usual way.113) A given name can refer to one
7020 // or more function templates and also to a set of overloaded non-template
7021 // functions. In such a case, the candidate functions generated from each
7022 // function template are combined with the set of non-template candidate
7023 // functions.
7024 TemplateDeductionInfo Info(CandidateSet.getLocation());
7025 FunctionDecl *Specialization = nullptr;
7026 ConversionSequenceList Conversions;
7027 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7028 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7029 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7030 return CheckNonDependentConversions(
7031 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7032 SuppressUserConversions, ActingContext, ObjectType,
7033 ObjectClassification, PO);
7034 })) {
7035 OverloadCandidate &Candidate =
7036 CandidateSet.addCandidate(Conversions.size(), Conversions);
7037 Candidate.FoundDecl = FoundDecl;
7038 Candidate.Function = MethodTmpl->getTemplatedDecl();
7039 Candidate.Viable = false;
7040 Candidate.RewriteKind =
7041 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7042 Candidate.IsSurrogate = false;
7043 Candidate.IgnoreObjectArgument =
7044 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7045 ObjectType.isNull();
7046 Candidate.ExplicitCallArguments = Args.size();
7047 if (Result == TDK_NonDependentConversionFailure)
7048 Candidate.FailureKind = ovl_fail_bad_conversion;
7049 else {
7050 Candidate.FailureKind = ovl_fail_bad_deduction;
7051 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7052 Info);
7053 }
7054 return;
7055 }
7056
7057 // Add the function template specialization produced by template argument
7058 // deduction as a candidate.
7059 assert(Specialization && "Missing member function template specialization?")((Specialization && "Missing member function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7059, __PRETTY_FUNCTION__))
;
7060 assert(isa<CXXMethodDecl>(Specialization) &&((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7061, __PRETTY_FUNCTION__))
7061 "Specialization is not a member function?")((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7061, __PRETTY_FUNCTION__))
;
7062 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7063 ActingContext, ObjectType, ObjectClassification, Args,
7064 CandidateSet, SuppressUserConversions, PartialOverloading,
7065 Conversions, PO);
7066}
7067
7068/// Determine whether a given function template has a simple explicit specifier
7069/// or a non-value-dependent explicit-specification that evaluates to true.
7070static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7071 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7072}
7073
7074/// Add a C++ function template specialization as a candidate
7075/// in the candidate set, using template argument deduction to produce
7076/// an appropriate function template specialization.
7077void Sema::AddTemplateOverloadCandidate(
7078 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7079 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7080 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7081 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7082 OverloadCandidateParamOrder PO) {
7083 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7084 return;
7085
7086 // If the function template has a non-dependent explicit specification,
7087 // exclude it now if appropriate; we are not permitted to perform deduction
7088 // and substitution in this case.
7089 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7090 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7091 Candidate.FoundDecl = FoundDecl;
7092 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7093 Candidate.Viable = false;
7094 Candidate.FailureKind = ovl_fail_explicit;
7095 return;
7096 }
7097
7098 // C++ [over.match.funcs]p7:
7099 // In each case where a candidate is a function template, candidate
7100 // function template specializations are generated using template argument
7101 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7102 // candidate functions in the usual way.113) A given name can refer to one
7103 // or more function templates and also to a set of overloaded non-template
7104 // functions. In such a case, the candidate functions generated from each
7105 // function template are combined with the set of non-template candidate
7106 // functions.
7107 TemplateDeductionInfo Info(CandidateSet.getLocation());
7108 FunctionDecl *Specialization = nullptr;
7109 ConversionSequenceList Conversions;
7110 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7111 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7112 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7113 return CheckNonDependentConversions(
7114 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7115 SuppressUserConversions, nullptr, QualType(), {}, PO);
7116 })) {
7117 OverloadCandidate &Candidate =
7118 CandidateSet.addCandidate(Conversions.size(), Conversions);
7119 Candidate.FoundDecl = FoundDecl;
7120 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7121 Candidate.Viable = false;
7122 Candidate.RewriteKind =
7123 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7124 Candidate.IsSurrogate = false;
7125 Candidate.IsADLCandidate = IsADLCandidate;
7126 // Ignore the object argument if there is one, since we don't have an object
7127 // type.
7128 Candidate.IgnoreObjectArgument =
7129 isa<CXXMethodDecl>(Candidate.Function) &&
7130 !isa<CXXConstructorDecl>(Candidate.Function);
7131 Candidate.ExplicitCallArguments = Args.size();
7132 if (Result == TDK_NonDependentConversionFailure)
7133 Candidate.FailureKind = ovl_fail_bad_conversion;
7134 else {
7135 Candidate.FailureKind = ovl_fail_bad_deduction;
7136 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7137 Info);
7138 }
7139 return;
7140 }
7141
7142 // Add the function template specialization produced by template argument
7143 // deduction as a candidate.
7144 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7144, __PRETTY_FUNCTION__))
;
7145 AddOverloadCandidate(
7146 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7147 PartialOverloading, AllowExplicit,
7148 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7149}
7150
7151/// Check that implicit conversion sequences can be formed for each argument
7152/// whose corresponding parameter has a non-dependent type, per DR1391's
7153/// [temp.deduct.call]p10.
7154bool Sema::CheckNonDependentConversions(
7155 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7156 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7157 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7158 CXXRecordDecl *ActingContext, QualType ObjectType,
7159 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7160 // FIXME: The cases in which we allow explicit conversions for constructor
7161 // arguments never consider calling a constructor template. It's not clear
7162 // that is correct.
7163 const bool AllowExplicit = false;
7164
7165 auto *FD = FunctionTemplate->getTemplatedDecl();
7166 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7167 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7168 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7169
7170 Conversions =
7171 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7172
7173 // Overload resolution is always an unevaluated context.
7174 EnterExpressionEvaluationContext Unevaluated(
7175 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7176
7177 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7178 // require that, but this check should never result in a hard error, and
7179 // overload resolution is permitted to sidestep instantiations.
7180 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7181 !ObjectType.isNull()) {
7182 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7183 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7184 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7185 Method, ActingContext);
7186 if (Conversions[ConvIdx].isBad())
7187 return true;
7188 }
7189
7190 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7191 ++I) {
7192 QualType ParamType = ParamTypes[I];
7193 if (!ParamType->isDependentType()) {
7194 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7195 ? 0
7196 : (ThisConversions + I);
7197 Conversions[ConvIdx]
7198 = TryCopyInitialization(*this, Args[I], ParamType,
7199 SuppressUserConversions,
7200 /*InOverloadResolution=*/true,
7201 /*AllowObjCWritebackConversion=*/
7202 getLangOpts().ObjCAutoRefCount,
7203 AllowExplicit);
7204 if (Conversions[ConvIdx].isBad())
7205 return true;
7206 }
7207 }
7208
7209 return false;
7210}
7211
7212/// Determine whether this is an allowable conversion from the result
7213/// of an explicit conversion operator to the expected type, per C++
7214/// [over.match.conv]p1 and [over.match.ref]p1.
7215///
7216/// \param ConvType The return type of the conversion function.
7217///
7218/// \param ToType The type we are converting to.
7219///
7220/// \param AllowObjCPointerConversion Allow a conversion from one
7221/// Objective-C pointer to another.
7222///
7223/// \returns true if the conversion is allowable, false otherwise.
7224static bool isAllowableExplicitConversion(Sema &S,
7225 QualType ConvType, QualType ToType,
7226 bool AllowObjCPointerConversion) {
7227 QualType ToNonRefType = ToType.getNonReferenceType();
7228
7229 // Easy case: the types are the same.
7230 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7231 return true;
7232
7233 // Allow qualification conversions.
7234 bool ObjCLifetimeConversion;
7235 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7236 ObjCLifetimeConversion))
7237 return true;
7238
7239 // If we're not allowed to consider Objective-C pointer conversions,
7240 // we're done.
7241 if (!AllowObjCPointerConversion)
7242 return false;
7243
7244 // Is this an Objective-C pointer conversion?
7245 bool IncompatibleObjC = false;
7246 QualType ConvertedType;
7247 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7248 IncompatibleObjC);
7249}
7250
7251/// AddConversionCandidate - Add a C++ conversion function as a
7252/// candidate in the candidate set (C++ [over.match.conv],
7253/// C++ [over.match.copy]). From is the expression we're converting from,
7254/// and ToType is the type that we're eventually trying to convert to
7255/// (which may or may not be the same type as the type that the
7256/// conversion function produces).
7257void Sema::AddConversionCandidate(
7258 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7259 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7260 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7261 bool AllowExplicit, bool AllowResultConversion) {
7262 assert(!Conversion->getDescribedFunctionTemplate() &&((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7263, __PRETTY_FUNCTION__))
7263 "Conversion function templates use AddTemplateConversionCandidate")((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7263, __PRETTY_FUNCTION__))
;
7264 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7265 if (!CandidateSet.isNewCandidate(Conversion))
7266 return;
7267
7268 // If the conversion function has an undeduced return type, trigger its
7269 // deduction now.
7270 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7271 if (DeduceReturnType(Conversion, From->getExprLoc()))
7272 return;
7273 ConvType = Conversion->getConversionType().getNonReferenceType();
7274 }
7275
7276 // If we don't allow any conversion of the result type, ignore conversion
7277 // functions that don't convert to exactly (possibly cv-qualified) T.
7278 if (!AllowResultConversion &&
7279 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7280 return;
7281
7282 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7283 // operator is only a candidate if its return type is the target type or
7284 // can be converted to the target type with a qualification conversion.
7285 //
7286 // FIXME: Include such functions in the candidate list and explain why we
7287 // can't select them.
7288 if (Conversion->isExplicit() &&
7289 !isAllowableExplicitConversion(*this, ConvType, ToType,
7290 AllowObjCConversionOnExplicit))
7291 return;
7292
7293 // Overload resolution is always an unevaluated context.
7294 EnterExpressionEvaluationContext Unevaluated(
7295 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7296
7297 // Add this candidate
7298 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7299 Candidate.FoundDecl = FoundDecl;
7300 Candidate.Function = Conversion;
7301 Candidate.IsSurrogate = false;
7302 Candidate.IgnoreObjectArgument = false;
7303 Candidate.FinalConversion.setAsIdentityConversion();
7304 Candidate.FinalConversion.setFromType(ConvType);
7305 Candidate.FinalConversion.setAllToTypes(ToType);
7306 Candidate.Viable = true;
7307 Candidate.ExplicitCallArguments = 1;
7308
7309 // Explicit functions are not actually candidates at all if we're not
7310 // allowing them in this context, but keep them around so we can point
7311 // to them in diagnostics.
7312 if (!AllowExplicit && Conversion->isExplicit()) {
7313 Candidate.Viable = false;
7314 Candidate.FailureKind = ovl_fail_explicit;
7315 return;
7316 }
7317
7318 // C++ [over.match.funcs]p4:
7319 // For conversion functions, the function is considered to be a member of
7320 // the class of the implicit implied object argument for the purpose of
7321 // defining the type of the implicit object parameter.
7322 //
7323 // Determine the implicit conversion sequence for the implicit
7324 // object parameter.
7325 QualType ImplicitParamType = From->getType();
7326 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7327 ImplicitParamType = FromPtrType->getPointeeType();
7328 CXXRecordDecl *ConversionContext
7329 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7330
7331 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7332 *this, CandidateSet.getLocation(), From->getType(),
7333 From->Classify(Context), Conversion, ConversionContext);
7334
7335 if (Candidate.Conversions[0].isBad()) {
7336 Candidate.Viable = false;
7337 Candidate.FailureKind = ovl_fail_bad_conversion;
7338 return;
7339 }
7340
7341 if (Conversion->getTrailingRequiresClause()) {
7342 ConstraintSatisfaction Satisfaction;
7343 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7344 !Satisfaction.IsSatisfied) {
7345 Candidate.Viable = false;
7346 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7347 return;
7348 }
7349 }
7350
7351 // We won't go through a user-defined type conversion function to convert a
7352 // derived to base as such conversions are given Conversion Rank. They only
7353 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7354 QualType FromCanon
7355 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7356 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7357 if (FromCanon == ToCanon ||
7358 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7359 Candidate.Viable = false;
7360 Candidate.FailureKind = ovl_fail_trivial_conversion;
7361 return;
7362 }
7363
7364 // To determine what the conversion from the result of calling the
7365 // conversion function to the type we're eventually trying to
7366 // convert to (ToType), we need to synthesize a call to the
7367 // conversion function and attempt copy initialization from it. This
7368 // makes sure that we get the right semantics with respect to
7369 // lvalues/rvalues and the type. Fortunately, we can allocate this
7370 // call on the stack and we don't need its arguments to be
7371 // well-formed.
7372 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7373 VK_LValue, From->getBeginLoc());
7374 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7375 Context.getPointerType(Conversion->getType()),
7376 CK_FunctionToPointerDecay, &ConversionRef,
7377 VK_RValue, FPOptionsOverride());
7378
7379 QualType ConversionType = Conversion->getConversionType();
7380 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7381 Candidate.Viable = false;
7382 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7383 return;
7384 }
7385
7386 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7387
7388 // Note that it is safe to allocate CallExpr on the stack here because
7389 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7390 // allocator).
7391 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7392
7393 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7394 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7395 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7396
7397 ImplicitConversionSequence ICS =
7398 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7399 /*SuppressUserConversions=*/true,
7400 /*InOverloadResolution=*/false,
7401 /*AllowObjCWritebackConversion=*/false);
7402
7403 switch (ICS.getKind()) {
7404 case ImplicitConversionSequence::StandardConversion:
7405 Candidate.FinalConversion = ICS.Standard;
7406
7407 // C++ [over.ics.user]p3:
7408 // If the user-defined conversion is specified by a specialization of a
7409 // conversion function template, the second standard conversion sequence
7410 // shall have exact match rank.
7411 if (Conversion->getPrimaryTemplate() &&
7412 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7413 Candidate.Viable = false;
7414 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7415 return;
7416 }
7417
7418 // C++0x [dcl.init.ref]p5:
7419 // In the second case, if the reference is an rvalue reference and
7420 // the second standard conversion sequence of the user-defined
7421 // conversion sequence includes an lvalue-to-rvalue conversion, the
7422 // program is ill-formed.
7423 if (ToType->isRValueReferenceType() &&
7424 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7425 Candidate.Viable = false;
7426 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7427 return;
7428 }
7429 break;
7430
7431 case ImplicitConversionSequence::BadConversion:
7432 Candidate.Viable = false;
7433 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7434 return;
7435
7436 default:
7437 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7438)
7438 "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7438)
;
7439 }
7440
7441 if (EnableIfAttr *FailedAttr =
7442 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7443 Candidate.Viable = false;
7444 Candidate.FailureKind = ovl_fail_enable_if;
7445 Candidate.DeductionFailure.Data = FailedAttr;
7446 return;
7447 }
7448
7449 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7450 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7451 Candidate.Viable = false;
7452 Candidate.FailureKind = ovl_non_default_multiversion_function;
7453 }
7454}
7455
7456/// Adds a conversion function template specialization
7457/// candidate to the overload set, using template argument deduction
7458/// to deduce the template arguments of the conversion function
7459/// template from the type that we are converting to (C++
7460/// [temp.deduct.conv]).
7461void Sema::AddTemplateConversionCandidate(
7462 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7463 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7464 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7465 bool AllowExplicit, bool AllowResultConversion) {
7466 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7467, __PRETTY_FUNCTION__))
7467 "Only conversion function templates permitted here")((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7467, __PRETTY_FUNCTION__))
;
7468
7469 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7470 return;
7471
7472 // If the function template has a non-dependent explicit specification,
7473 // exclude it now if appropriate; we are not permitted to perform deduction
7474 // and substitution in this case.
7475 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7476 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7477 Candidate.FoundDecl = FoundDecl;
7478 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7479 Candidate.Viable = false;
7480 Candidate.FailureKind = ovl_fail_explicit;
7481 return;
7482 }
7483
7484 TemplateDeductionInfo Info(CandidateSet.getLocation());
7485 CXXConversionDecl *Specialization = nullptr;
7486 if (TemplateDeductionResult Result
7487 = DeduceTemplateArguments(FunctionTemplate, ToType,
7488 Specialization, Info)) {
7489 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7490 Candidate.FoundDecl = FoundDecl;
7491 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7492 Candidate.Viable = false;
7493 Candidate.FailureKind = ovl_fail_bad_deduction;
7494 Candidate.IsSurrogate = false;
7495 Candidate.IgnoreObjectArgument = false;
7496 Candidate.ExplicitCallArguments = 1;
7497 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7498 Info);
7499 return;
7500 }
7501
7502 // Add the conversion function template specialization produced by
7503 // template argument deduction as a candidate.
7504 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7504, __PRETTY_FUNCTION__))
;
7505 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7506 CandidateSet, AllowObjCConversionOnExplicit,
7507 AllowExplicit, AllowResultConversion);
7508}
7509
7510/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7511/// converts the given @c Object to a function pointer via the
7512/// conversion function @c Conversion, and then attempts to call it
7513/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7514/// the type of function that we'll eventually be calling.
7515void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7516 DeclAccessPair FoundDecl,
7517 CXXRecordDecl *ActingContext,
7518 const FunctionProtoType *Proto,
7519 Expr *Object,
7520 ArrayRef<Expr *> Args,
7521 OverloadCandidateSet& CandidateSet) {
7522 if (!CandidateSet.isNewCandidate(Conversion))
7523 return;
7524
7525 // Overload resolution is always an unevaluated context.
7526 EnterExpressionEvaluationContext Unevaluated(
7527 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7528
7529 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7530 Candidate.FoundDecl = FoundDecl;
7531 Candidate.Function = nullptr;
7532 Candidate.Surrogate = Conversion;
7533 Candidate.Viable = true;
7534 Candidate.IsSurrogate = true;
7535 Candidate.IgnoreObjectArgument = false;
7536 Candidate.ExplicitCallArguments = Args.size();
7537
7538 // Determine the implicit conversion sequence for the implicit
7539 // object parameter.
7540 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7541 *this, CandidateSet.getLocation(), Object->getType(),
7542 Object->Classify(Context), Conversion, ActingContext);
7543 if (ObjectInit.isBad()) {
7544 Candidate.Viable = false;
7545 Candidate.FailureKind = ovl_fail_bad_conversion;
7546 Candidate.Conversions[0] = ObjectInit;
7547 return;
7548 }
7549
7550 // The first conversion is actually a user-defined conversion whose
7551 // first conversion is ObjectInit's standard conversion (which is
7552 // effectively a reference binding). Record it as such.
7553 Candidate.Conversions[0].setUserDefined();
7554 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7555 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7556 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7557 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7558 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7559 Candidate.Conversions[0].UserDefined.After
7560 = Candidate.Conversions[0].UserDefined.Before;
7561 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7562
7563 // Find the
7564 unsigned NumParams = Proto->getNumParams();
7565
7566 // (C++ 13.3.2p2): A candidate function having fewer than m
7567 // parameters is viable only if it has an ellipsis in its parameter
7568 // list (8.3.5).
7569 if (Args.size() > NumParams && !Proto->isVariadic()) {
7570 Candidate.Viable = false;
7571 Candidate.FailureKind = ovl_fail_too_many_arguments;
7572 return;
7573 }
7574
7575 // Function types don't have any default arguments, so just check if
7576 // we have enough arguments.
7577 if (Args.size() < NumParams) {
7578 // Not enough arguments.
7579 Candidate.Viable = false;
7580 Candidate.FailureKind = ovl_fail_too_few_arguments;
7581 return;
7582 }
7583
7584 // Determine the implicit conversion sequences for each of the
7585 // arguments.
7586 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7587 if (ArgIdx < NumParams) {
7588 // (C++ 13.3.2p3): for F to be a viable function, there shall
7589 // exist for each argument an implicit conversion sequence
7590 // (13.3.3.1) that converts that argument to the corresponding
7591 // parameter of F.
7592 QualType ParamType = Proto->getParamType(ArgIdx);
7593 Candidate.Conversions[ArgIdx + 1]
7594 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7595 /*SuppressUserConversions=*/false,
7596 /*InOverloadResolution=*/false,
7597 /*AllowObjCWritebackConversion=*/
7598 getLangOpts().ObjCAutoRefCount);
7599 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7600 Candidate.Viable = false;
7601 Candidate.FailureKind = ovl_fail_bad_conversion;
7602 return;
7603 }
7604 } else {
7605 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7606 // argument for which there is no corresponding parameter is
7607 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7608 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7609 }
7610 }
7611
7612 if (EnableIfAttr *FailedAttr =
7613 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7614 Candidate.Viable = false;
7615 Candidate.FailureKind = ovl_fail_enable_if;
7616 Candidate.DeductionFailure.Data = FailedAttr;
7617 return;
7618 }
7619}
7620
7621/// Add all of the non-member operator function declarations in the given
7622/// function set to the overload candidate set.
7623void Sema::AddNonMemberOperatorCandidates(
7624 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7625 OverloadCandidateSet &CandidateSet,
7626 TemplateArgumentListInfo *ExplicitTemplateArgs) {
7627 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7628 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7629 ArrayRef<Expr *> FunctionArgs = Args;
7630
7631 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7632 FunctionDecl *FD =
7633 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7634
7635 // Don't consider rewritten functions if we're not rewriting.
7636 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7637 continue;
7638
7639 assert(!isa<CXXMethodDecl>(FD) &&((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7640, __PRETTY_FUNCTION__))
7640 "unqualified operator lookup found a member function")((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7640, __PRETTY_FUNCTION__))
;
7641
7642 if (FunTmpl) {
7643 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7644 FunctionArgs, CandidateSet);
7645 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7646 AddTemplateOverloadCandidate(
7647 FunTmpl, F.getPair(), ExplicitTemplateArgs,
7648 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7649 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7650 } else {
7651 if (ExplicitTemplateArgs)
7652 continue;
7653 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7654 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7655 AddOverloadCandidate(FD, F.getPair(),
7656 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7657 false, false, true, false, ADLCallKind::NotADL,
7658 None, OverloadCandidateParamOrder::Reversed);
7659 }
7660 }
7661}
7662
7663/// Add overload candidates for overloaded operators that are
7664/// member functions.
7665///
7666/// Add the overloaded operator candidates that are member functions
7667/// for the operator Op that was used in an operator expression such
7668/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7669/// CandidateSet will store the added overload candidates. (C++
7670/// [over.match.oper]).
7671void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7672 SourceLocation OpLoc,
7673 ArrayRef<Expr *> Args,
7674 OverloadCandidateSet &CandidateSet,
7675 OverloadCandidateParamOrder PO) {
7676 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7677
7678 // C++ [over.match.oper]p3:
7679 // For a unary operator @ with an operand of a type whose
7680 // cv-unqualified version is T1, and for a binary operator @ with
7681 // a left operand of a type whose cv-unqualified version is T1 and
7682 // a right operand of a type whose cv-unqualified version is T2,
7683 // three sets of candidate functions, designated member
7684 // candidates, non-member candidates and built-in candidates, are
7685 // constructed as follows:
7686 QualType T1 = Args[0]->getType();
7687
7688 // -- If T1 is a complete class type or a class currently being
7689 // defined, the set of member candidates is the result of the
7690 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7691 // the set of member candidates is empty.
7692 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7693 // Complete the type if it can be completed.
7694 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7695 return;
7696 // If the type is neither complete nor being defined, bail out now.
7697 if (!T1Rec->getDecl()->getDefinition())
7698 return;
7699
7700 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7701 LookupQualifiedName(Operators, T1Rec->getDecl());
7702 Operators.suppressDiagnostics();
7703
7704 for (LookupResult::iterator Oper = Operators.begin(),
7705 OperEnd = Operators.end();
7706 Oper != OperEnd;
7707 ++Oper)
7708 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7709 Args[0]->Classify(Context), Args.slice(1),
7710 CandidateSet, /*SuppressUserConversion=*/false, PO);
7711 }
7712}
7713
7714/// AddBuiltinCandidate - Add a candidate for a built-in
7715/// operator. ResultTy and ParamTys are the result and parameter types
7716/// of the built-in candidate, respectively. Args and NumArgs are the
7717/// arguments being passed to the candidate. IsAssignmentOperator
7718/// should be true when this built-in candidate is an assignment
7719/// operator. NumContextualBoolArguments is the number of arguments
7720/// (at the beginning of the argument list) that will be contextually
7721/// converted to bool.
7722void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7723 OverloadCandidateSet& CandidateSet,
7724 bool IsAssignmentOperator,
7725 unsigned NumContextualBoolArguments) {
7726 // Overload resolution is always an unevaluated context.
7727 EnterExpressionEvaluationContext Unevaluated(
7728 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7729
7730 // Add this candidate
7731 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7732 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7733 Candidate.Function = nullptr;
7734 Candidate.IsSurrogate = false;
7735 Candidate.IgnoreObjectArgument = false;
7736 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7737
7738 // Determine the implicit conversion sequences for each of the
7739 // arguments.
7740 Candidate.Viable = true;
7741 Candidate.ExplicitCallArguments = Args.size();
7742 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7743 // C++ [over.match.oper]p4:
7744 // For the built-in assignment operators, conversions of the
7745 // left operand are restricted as follows:
7746 // -- no temporaries are introduced to hold the left operand, and
7747 // -- no user-defined conversions are applied to the left
7748 // operand to achieve a type match with the left-most
7749 // parameter of a built-in candidate.
7750 //
7751 // We block these conversions by turning off user-defined
7752 // conversions, since that is the only way that initialization of
7753 // a reference to a non-class type can occur from something that
7754 // is not of the same type.
7755 if (ArgIdx < NumContextualBoolArguments) {
7756 assert(ParamTys[ArgIdx] == Context.BoolTy &&((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7757, __PRETTY_FUNCTION__))
7757 "Contextual conversion to bool requires bool type")((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7757, __PRETTY_FUNCTION__))
;
7758 Candidate.Conversions[ArgIdx]
7759 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7760 } else {
7761 Candidate.Conversions[ArgIdx]
7762 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7763 ArgIdx == 0 && IsAssignmentOperator,
7764 /*InOverloadResolution=*/false,
7765 /*AllowObjCWritebackConversion=*/
7766 getLangOpts().ObjCAutoRefCount);
7767 }
7768 if (Candidate.Conversions[ArgIdx].isBad()) {
7769 Candidate.Viable = false;
7770 Candidate.FailureKind = ovl_fail_bad_conversion;
7771 break;
7772 }
7773 }
7774}
7775
7776namespace {
7777
7778/// BuiltinCandidateTypeSet - A set of types that will be used for the
7779/// candidate operator functions for built-in operators (C++
7780/// [over.built]). The types are separated into pointer types and
7781/// enumeration types.
7782class BuiltinCandidateTypeSet {
7783 /// TypeSet - A set of types.
7784 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7785 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7786
7787 /// PointerTypes - The set of pointer types that will be used in the
7788 /// built-in candidates.
7789 TypeSet PointerTypes;
7790
7791 /// MemberPointerTypes - The set of member pointer types that will be
7792 /// used in the built-in candidates.
7793 TypeSet MemberPointerTypes;
7794
7795 /// EnumerationTypes - The set of enumeration types that will be
7796 /// used in the built-in candidates.
7797 TypeSet EnumerationTypes;
7798
7799 /// The set of vector types that will be used in the built-in
7800 /// candidates.
7801 TypeSet VectorTypes;
7802
7803 /// The set of matrix types that will be used in the built-in
7804 /// candidates.
7805 TypeSet MatrixTypes;
7806
7807 /// A flag indicating non-record types are viable candidates
7808 bool HasNonRecordTypes;
7809
7810 /// A flag indicating whether either arithmetic or enumeration types
7811 /// were present in the candidate set.
7812 bool HasArithmeticOrEnumeralTypes;
7813
7814 /// A flag indicating whether the nullptr type was present in the
7815 /// candidate set.
7816 bool HasNullPtrType;
7817
7818 /// Sema - The semantic analysis instance where we are building the
7819 /// candidate type set.
7820 Sema &SemaRef;
7821
7822 /// Context - The AST context in which we will build the type sets.
7823 ASTContext &Context;
7824
7825 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7826 const Qualifiers &VisibleQuals);
7827 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7828
7829public:
7830 /// iterator - Iterates through the types that are part of the set.
7831 typedef TypeSet::iterator iterator;
7832
7833 BuiltinCandidateTypeSet(Sema &SemaRef)
7834 : HasNonRecordTypes(false),
7835 HasArithmeticOrEnumeralTypes(false),
7836 HasNullPtrType(false),
7837 SemaRef(SemaRef),
7838 Context(SemaRef.Context) { }
7839
7840 void AddTypesConvertedFrom(QualType Ty,
7841 SourceLocation Loc,
7842 bool AllowUserConversions,
7843 bool AllowExplicitConversions,
7844 const Qualifiers &VisibleTypeConversionsQuals);
7845
7846 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7847 llvm::iterator_range<iterator> member_pointer_types() {
7848 return MemberPointerTypes;
7849 }
7850 llvm::iterator_range<iterator> enumeration_types() {
7851 return EnumerationTypes;
7852 }
7853 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7854 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7855
7856 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7857 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7858 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7859 bool hasNullPtrType() const { return HasNullPtrType; }
7860};
7861
7862} // end anonymous namespace
7863
7864/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7865/// the set of pointer types along with any more-qualified variants of
7866/// that type. For example, if @p Ty is "int const *", this routine
7867/// will add "int const *", "int const volatile *", "int const
7868/// restrict *", and "int const volatile restrict *" to the set of
7869/// pointer types. Returns true if the add of @p Ty itself succeeded,
7870/// false otherwise.
7871///
7872/// FIXME: what to do about extended qualifiers?
7873bool
7874BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7875 const Qualifiers &VisibleQuals) {
7876
7877 // Insert this type.
7878 if (!PointerTypes.insert(Ty))
7879 return false;
7880
7881 QualType PointeeTy;
7882 const PointerType *PointerTy = Ty->getAs<PointerType>();
7883 bool buildObjCPtr = false;
7884 if (!PointerTy) {
7885 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7886 PointeeTy = PTy->getPointeeType();
7887 buildObjCPtr = true;
7888 } else {
7889 PointeeTy = PointerTy->getPointeeType();
7890 }
7891
7892 // Don't add qualified variants of arrays. For one, they're not allowed
7893 // (the qualifier would sink to the element type), and for another, the
7894 // only overload situation where it matters is subscript or pointer +- int,
7895 // and those shouldn't have qualifier variants anyway.
7896 if (PointeeTy->isArrayType())
7897 return true;
7898
7899 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7900 bool hasVolatile = VisibleQuals.hasVolatile();
7901 bool hasRestrict = VisibleQuals.hasRestrict();
7902
7903 // Iterate through all strict supersets of BaseCVR.
7904 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7905 if ((CVR | BaseCVR) != CVR) continue;
7906 // Skip over volatile if no volatile found anywhere in the types.
7907 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7908
7909 // Skip over restrict if no restrict found anywhere in the types, or if
7910 // the type cannot be restrict-qualified.
7911 if ((CVR & Qualifiers::Restrict) &&
7912 (!hasRestrict ||
7913 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7914 continue;
7915
7916 // Build qualified pointee type.
7917 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7918
7919 // Build qualified pointer type.
7920 QualType QPointerTy;
7921 if (!buildObjCPtr)
7922 QPointerTy = Context.getPointerType(QPointeeTy);
7923 else
7924 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7925
7926 // Insert qualified pointer type.
7927 PointerTypes.insert(QPointerTy);
7928 }
7929
7930 return true;
7931}
7932
7933/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7934/// to the set of pointer types along with any more-qualified variants of
7935/// that type. For example, if @p Ty is "int const *", this routine
7936/// will add "int const *", "int const volatile *", "int const
7937/// restrict *", and "int const volatile restrict *" to the set of
7938/// pointer types. Returns true if the add of @p Ty itself succeeded,
7939/// false otherwise.
7940///
7941/// FIXME: what to do about extended qualifiers?
7942bool
7943BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7944 QualType Ty) {
7945 // Insert this type.
7946 if (!MemberPointerTypes.insert(Ty))
7947 return false;
7948
7949 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7950 assert(PointerTy && "type was not a member pointer type!")((PointerTy && "type was not a member pointer type!")
? static_cast<void> (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 7950, __PRETTY_FUNCTION__))
;
7951
7952 QualType PointeeTy = PointerTy->getPointeeType();
7953 // Don't add qualified variants of arrays. For one, they're not allowed
7954 // (the qualifier would sink to the element type), and for another, the
7955 // only overload situation where it matters is subscript or pointer +- int,
7956 // and those shouldn't have qualifier variants anyway.
7957 if (PointeeTy->isArrayType())
7958 return true;
7959 const Type *ClassTy = PointerTy->getClass();
7960
7961 // Iterate through all strict supersets of the pointee type's CVR
7962 // qualifiers.
7963 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7964 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7965 if ((CVR | BaseCVR) != CVR) continue;
7966
7967 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7968 MemberPointerTypes.insert(
7969 Context.getMemberPointerType(QPointeeTy, ClassTy));
7970 }
7971
7972 return true;
7973}
7974
7975/// AddTypesConvertedFrom - Add each of the types to which the type @p
7976/// Ty can be implicit converted to the given set of @p Types. We're
7977/// primarily interested in pointer types and enumeration types. We also
7978/// take member pointer types, for the conditional operator.
7979/// AllowUserConversions is true if we should look at the conversion
7980/// functions of a class type, and AllowExplicitConversions if we
7981/// should also include the explicit conversion functions of a class
7982/// type.
7983void
7984BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7985 SourceLocation Loc,
7986 bool AllowUserConversions,
7987 bool AllowExplicitConversions,
7988 const Qualifiers &VisibleQuals) {
7989 // Only deal with canonical types.
7990 Ty = Context.getCanonicalType(Ty);
7991
7992 // Look through reference types; they aren't part of the type of an
7993 // expression for the purposes of conversions.
7994 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7995 Ty = RefTy->getPointeeType();
7996
7997 // If we're dealing with an array type, decay to the pointer.
7998 if (Ty->isArrayType())
7999 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8000
8001 // Otherwise, we don't care about qualifiers on the type.
8002 Ty = Ty.getLocalUnqualifiedType();
8003
8004 // Flag if we ever add a non-record type.
8005 const RecordType *TyRec = Ty->getAs<RecordType>();
8006 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8007
8008 // Flag if we encounter an arithmetic type.
8009 HasArithmeticOrEnumeralTypes =
8010 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8011
8012 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8013 PointerTypes.insert(Ty);
8014 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8015 // Insert our type, and its more-qualified variants, into the set
8016 // of types.
8017 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8018 return;
8019 } else if (Ty->isMemberPointerType()) {
8020 // Member pointers are far easier, since the pointee can't be converted.
8021 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8022 return;
8023 } else if (Ty->isEnumeralType()) {
8024 HasArithmeticOrEnumeralTypes = true;
8025 EnumerationTypes.insert(Ty);
8026 } else if (Ty->isVectorType()) {
8027 // We treat vector types as arithmetic types in many contexts as an
8028 // extension.
8029 HasArithmeticOrEnumeralTypes = true;
8030 VectorTypes.insert(Ty);
8031 } else if (Ty->isMatrixType()) {
8032 // Similar to vector types, we treat vector types as arithmetic types in
8033 // many contexts as an extension.
8034 HasArithmeticOrEnumeralTypes = true;
8035 MatrixTypes.insert(Ty);
8036 } else if (Ty->isNullPtrType()) {
8037 HasNullPtrType = true;
8038 } else if (AllowUserConversions && TyRec) {
8039 // No conversion functions in incomplete types.
8040 if (!SemaRef.isCompleteType(Loc, Ty))
8041 return;
8042
8043 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8044 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8045 if (isa<UsingShadowDecl>(D))
8046 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8047
8048 // Skip conversion function templates; they don't tell us anything
8049 // about which builtin types we can convert to.
8050 if (isa<FunctionTemplateDecl>(D))
8051 continue;
8052
8053 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8054 if (AllowExplicitConversions || !Conv->isExplicit()) {
8055 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8056 VisibleQuals);
8057 }
8058 }
8059 }
8060}
8061/// Helper function for adjusting address spaces for the pointer or reference
8062/// operands of builtin operators depending on the argument.
8063static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8064 Expr *Arg) {
8065 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8066}
8067
8068/// Helper function for AddBuiltinOperatorCandidates() that adds
8069/// the volatile- and non-volatile-qualified assignment operators for the
8070/// given type to the candidate set.
8071static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8072 QualType T,
8073 ArrayRef<Expr *> Args,
8074 OverloadCandidateSet &CandidateSet) {
8075 QualType ParamTypes[2];
8076
8077 // T& operator=(T&, T)
8078 ParamTypes[0] = S.Context.getLValueReferenceType(
8079 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8080 ParamTypes[1] = T;
8081 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8082 /*IsAssignmentOperator=*/true);
8083
8084 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8085 // volatile T& operator=(volatile T&, T)
8086 ParamTypes[0] = S.Context.getLValueReferenceType(
8087 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8088 Args[0]));
8089 ParamTypes[1] = T;
8090 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8091 /*IsAssignmentOperator=*/true);
8092 }
8093}
8094
8095/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8096/// if any, found in visible type conversion functions found in ArgExpr's type.
8097static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8098 Qualifiers VRQuals;
8099 const RecordType *TyRec;
8100 if (const MemberPointerType *RHSMPType =
8101 ArgExpr->getType()->getAs<MemberPointerType>())
8102 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8103 else
8104 TyRec = ArgExpr->getType()->getAs<RecordType>();
8105 if (!TyRec) {
8106 // Just to be safe, assume the worst case.
8107 VRQuals.addVolatile();
8108 VRQuals.addRestrict();
8109 return VRQuals;
8110 }
8111
8112 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8113 if (!ClassDecl->hasDefinition())
8114 return VRQuals;
8115
8116 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8117 if (isa<UsingShadowDecl>(D))
8118 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8119 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8120 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8121 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8122 CanTy = ResTypeRef->getPointeeType();
8123 // Need to go down the pointer/mempointer chain and add qualifiers
8124 // as see them.
8125 bool done = false;
8126 while (!done) {
8127 if (CanTy.isRestrictQualified())
8128 VRQuals.addRestrict();
8129 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8130 CanTy = ResTypePtr->getPointeeType();
8131 else if (const MemberPointerType *ResTypeMPtr =
8132 CanTy->getAs<MemberPointerType>())
8133 CanTy = ResTypeMPtr->getPointeeType();
8134 else
8135 done = true;
8136 if (CanTy.isVolatileQualified())
8137 VRQuals.addVolatile();
8138 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8139 return VRQuals;
8140 }
8141 }
8142 }
8143 return VRQuals;
8144}
8145
8146namespace {
8147
8148/// Helper class to manage the addition of builtin operator overload
8149/// candidates. It provides shared state and utility methods used throughout
8150/// the process, as well as a helper method to add each group of builtin
8151/// operator overloads from the standard to a candidate set.
8152class BuiltinOperatorOverloadBuilder {
8153 // Common instance state available to all overload candidate addition methods.
8154 Sema &S;
8155 ArrayRef<Expr *> Args;
8156 Qualifiers VisibleTypeConversionsQuals;
8157 bool HasArithmeticOrEnumeralCandidateType;
8158 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8159 OverloadCandidateSet &CandidateSet;
8160
8161 static constexpr int ArithmeticTypesCap = 24;
8162 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8163
8164 // Define some indices used to iterate over the arithmetic types in
8165 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8166 // types are that preserved by promotion (C++ [over.built]p2).
8167 unsigned FirstIntegralType,
8168 LastIntegralType;
8169 unsigned FirstPromotedIntegralType,
8170 LastPromotedIntegralType;
8171 unsigned FirstPromotedArithmeticType,
8172 LastPromotedArithmeticType;
8173 unsigned NumArithmeticTypes;
8174
8175 void InitArithmeticTypes() {
8176 // Start of promoted types.
8177 FirstPromotedArithmeticType = 0;
8178 ArithmeticTypes.push_back(S.Context.FloatTy);
8179 ArithmeticTypes.push_back(S.Context.DoubleTy);
8180 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8181 if (S.Context.getTargetInfo().hasFloat128Type())
8182 ArithmeticTypes.push_back(S.Context.Float128Ty);
8183
8184 // Start of integral types.
8185 FirstIntegralType = ArithmeticTypes.size();
8186 FirstPromotedIntegralType = ArithmeticTypes.size();
8187 ArithmeticTypes.push_back(S.Context.IntTy);
8188 ArithmeticTypes.push_back(S.Context.LongTy);
8189 ArithmeticTypes.push_back(S.Context.LongLongTy);
8190 if (S.Context.getTargetInfo().hasInt128Type() ||
8191 (S.Context.getAuxTargetInfo() &&
8192 S.Context.getAuxTargetInfo()->hasInt128Type()))
8193 ArithmeticTypes.push_back(S.Context.Int128Ty);
8194 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8195 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8196 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8197 if (S.Context.getTargetInfo().hasInt128Type() ||
8198 (S.Context.getAuxTargetInfo() &&
8199 S.Context.getAuxTargetInfo()->hasInt128Type()))
8200 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8201 LastPromotedIntegralType = ArithmeticTypes.size();
8202 LastPromotedArithmeticType = ArithmeticTypes.size();
8203 // End of promoted types.
8204
8205 ArithmeticTypes.push_back(S.Context.BoolTy);
8206 ArithmeticTypes.push_back(S.Context.CharTy);
8207 ArithmeticTypes.push_back(S.Context.WCharTy);
8208 if (S.Context.getLangOpts().Char8)
8209 ArithmeticTypes.push_back(S.Context.Char8Ty);
8210 ArithmeticTypes.push_back(S.Context.Char16Ty);
8211 ArithmeticTypes.push_back(S.Context.Char32Ty);
8212 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8213 ArithmeticTypes.push_back(S.Context.ShortTy);
8214 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8215 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8216 LastIntegralType = ArithmeticTypes.size();
8217 NumArithmeticTypes = ArithmeticTypes.size();
8218 // End of integral types.
8219 // FIXME: What about complex? What about half?
8220
8221 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types."
) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 8222, __PRETTY_FUNCTION__))
8222 "Enough inline storage for all arithmetic types.")((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types."
) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 8222, __PRETTY_FUNCTION__))
;
8223 }
8224
8225 /// Helper method to factor out the common pattern of adding overloads
8226 /// for '++' and '--' builtin operators.
8227 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8228 bool HasVolatile,
8229 bool HasRestrict) {
8230 QualType ParamTypes[2] = {
8231 S.Context.getLValueReferenceType(CandidateTy),
8232 S.Context.IntTy
8233 };
8234
8235 // Non-volatile version.
8236 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8237
8238 // Use a heuristic to reduce number of builtin candidates in the set:
8239 // add volatile version only if there are conversions to a volatile type.
8240 if (HasVolatile) {
8241 ParamTypes[0] =
8242 S.Context.getLValueReferenceType(
8243 S.Context.getVolatileType(CandidateTy));
8244 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8245 }
8246
8247 // Add restrict version only if there are conversions to a restrict type
8248 // and our candidate type is a non-restrict-qualified pointer.
8249 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8250 !CandidateTy.isRestrictQualified()) {
8251 ParamTypes[0]
8252 = S.Context.getLValueReferenceType(
8253 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8254 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8255
8256 if (HasVolatile) {
8257 ParamTypes[0]
8258 = S.Context.getLValueReferenceType(
8259 S.Context.getCVRQualifiedType(CandidateTy,
8260 (Qualifiers::Volatile |
8261 Qualifiers::Restrict)));
8262 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8263 }
8264 }
8265
8266 }
8267
8268 /// Helper to add an overload candidate for a binary builtin with types \p L
8269 /// and \p R.
8270 void AddCandidate(QualType L, QualType R) {
8271 QualType LandR[2] = {L, R};
8272 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8273 }
8274
8275public:
8276 BuiltinOperatorOverloadBuilder(
8277 Sema &S, ArrayRef<Expr *> Args,
8278 Qualifiers VisibleTypeConversionsQuals,
8279 bool HasArithmeticOrEnumeralCandidateType,
8280 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8281 OverloadCandidateSet &CandidateSet)
8282 : S(S), Args(Args),
8283 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8284 HasArithmeticOrEnumeralCandidateType(
8285 HasArithmeticOrEnumeralCandidateType),
8286 CandidateTypes(CandidateTypes),
8287 CandidateSet(CandidateSet) {
8288
8289 InitArithmeticTypes();
8290 }
8291
8292 // Increment is deprecated for bool since C++17.
8293 //
8294 // C++ [over.built]p3:
8295 //
8296 // For every pair (T, VQ), where T is an arithmetic type other
8297 // than bool, and VQ is either volatile or empty, there exist
8298 // candidate operator functions of the form
8299 //
8300 // VQ T& operator++(VQ T&);
8301 // T operator++(VQ T&, int);
8302 //
8303 // C++ [over.built]p4:
8304 //
8305 // For every pair (T, VQ), where T is an arithmetic type other
8306 // than bool, and VQ is either volatile or empty, there exist
8307 // candidate operator functions of the form
8308 //
8309 // VQ T& operator--(VQ T&);
8310 // T operator--(VQ T&, int);
8311 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8312 if (!HasArithmeticOrEnumeralCandidateType)
8313 return;
8314
8315 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8316 const auto TypeOfT = ArithmeticTypes[Arith];
8317 if (TypeOfT == S.Context.BoolTy) {
8318 if (Op == OO_MinusMinus)
8319 continue;
8320 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8321 continue;
8322 }
8323 addPlusPlusMinusMinusStyleOverloads(
8324 TypeOfT,
8325 VisibleTypeConversionsQuals.hasVolatile(),
8326 VisibleTypeConversionsQuals.hasRestrict());
8327 }
8328 }
8329
8330 // C++ [over.built]p5:
8331 //
8332 // For every pair (T, VQ), where T is a cv-qualified or
8333 // cv-unqualified object type, and VQ is either volatile or
8334 // empty, there exist candidate operator functions of the form
8335 //
8336 // T*VQ& operator++(T*VQ&);
8337 // T*VQ& operator--(T*VQ&);
8338 // T* operator++(T*VQ&, int);
8339 // T* operator--(T*VQ&, int);
8340 void addPlusPlusMinusMinusPointerOverloads() {
8341 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8342 // Skip pointer types that aren't pointers to object types.
8343 if (!PtrTy->getPointeeType()->isObjectType())
8344 continue;
8345
8346 addPlusPlusMinusMinusStyleOverloads(
8347 PtrTy,
8348 (!PtrTy.isVolatileQualified() &&
8349 VisibleTypeConversionsQuals.hasVolatile()),
8350 (!PtrTy.isRestrictQualified() &&
8351 VisibleTypeConversionsQuals.hasRestrict()));
8352 }
8353 }
8354
8355 // C++ [over.built]p6:
8356 // For every cv-qualified or cv-unqualified object type T, there
8357 // exist candidate operator functions of the form
8358 //
8359 // T& operator*(T*);
8360 //
8361 // C++ [over.built]p7:
8362 // For every function type T that does not have cv-qualifiers or a
8363 // ref-qualifier, there exist candidate operator functions of the form
8364 // T& operator*(T*);
8365 void addUnaryStarPointerOverloads() {
8366 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8367 QualType PointeeTy = ParamTy->getPointeeType();
8368 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8369 continue;
8370
8371 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8372 if (Proto->getMethodQuals() || Proto->getRefQualifier())
8373 continue;
8374
8375 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8376 }
8377 }
8378
8379 // C++ [over.built]p9:
8380 // For every promoted arithmetic type T, there exist candidate
8381 // operator functions of the form
8382 //
8383 // T operator+(T);
8384 // T operator-(T);
8385 void addUnaryPlusOrMinusArithmeticOverloads() {
8386 if (!HasArithmeticOrEnumeralCandidateType)
8387 return;
8388
8389 for (unsigned Arith = FirstPromotedArithmeticType;
8390 Arith < LastPromotedArithmeticType; ++Arith) {
8391 QualType ArithTy = ArithmeticTypes[Arith];
8392 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8393 }
8394
8395 // Extension: We also add these operators for vector types.
8396 for (QualType VecTy : CandidateTypes[0].vector_types())
8397 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8398 }
8399
8400 // C++ [over.built]p8:
8401 // For every type T, there exist candidate operator functions of
8402 // the form
8403 //
8404 // T* operator+(T*);
8405 void addUnaryPlusPointerOverloads() {
8406 for (QualType ParamTy : CandidateTypes[0].pointer_types())
8407 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8408 }
8409
8410 // C++ [over.built]p10:
8411 // For every promoted integral type T, there exist candidate
8412 // operator functions of the form
8413 //
8414 // T operator~(T);
8415 void addUnaryTildePromotedIntegralOverloads() {
8416 if (!HasArithmeticOrEnumeralCandidateType)
8417 return;
8418
8419 for (unsigned Int = FirstPromotedIntegralType;
8420 Int < LastPromotedIntegralType; ++Int) {
8421 QualType IntTy = ArithmeticTypes[Int];
8422 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8423 }
8424
8425 // Extension: We also add this operator for vector types.
8426 for (QualType VecTy : CandidateTypes[0].vector_types())
8427 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8428 }
8429
8430 // C++ [over.match.oper]p16:
8431 // For every pointer to member type T or type std::nullptr_t, there
8432 // exist candidate operator functions of the form
8433 //
8434 // bool operator==(T,T);
8435 // bool operator!=(T,T);
8436 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8437 /// Set of (canonical) types that we've already handled.
8438 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8439
8440 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8441 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8442 // Don't add the same builtin candidate twice.
8443 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8444 continue;
8445
8446 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8447 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8448 }
8449
8450 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8451 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8452 if (AddedTypes.insert(NullPtrTy).second) {
8453 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8454 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8455 }
8456 }
8457 }
8458 }
8459
8460 // C++ [over.built]p15:
8461 //
8462 // For every T, where T is an enumeration type or a pointer type,
8463 // there exist candidate operator functions of the form
8464 //
8465 // bool operator<(T, T);
8466 // bool operator>(T, T);
8467 // bool operator<=(T, T);
8468 // bool operator>=(T, T);
8469 // bool operator==(T, T);
8470 // bool operator!=(T, T);
8471 // R operator<=>(T, T)
8472 void addGenericBinaryPointerOrEnumeralOverloads() {
8473 // C++ [over.match.oper]p3:
8474 // [...]the built-in candidates include all of the candidate operator
8475 // functions defined in 13.6 that, compared to the given operator, [...]
8476 // do not have the same parameter-type-list as any non-template non-member
8477 // candidate.
8478 //
8479 // Note that in practice, this only affects enumeration types because there
8480 // aren't any built-in candidates of record type, and a user-defined operator
8481 // must have an operand of record or enumeration type. Also, the only other
8482 // overloaded operator with enumeration arguments, operator=,
8483 // cannot be overloaded for enumeration types, so this is the only place
8484 // where we must suppress candidates like this.
8485 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8486 UserDefinedBinaryOperators;
8487
8488 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8489 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8490 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8491 CEnd = CandidateSet.end();
8492 C != CEnd; ++C) {
8493 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8494 continue;
8495
8496 if (C->Function->isFunctionTemplateSpecialization())
8497 continue;
8498
8499 // We interpret "same parameter-type-list" as applying to the
8500 // "synthesized candidate, with the order of the two parameters
8501 // reversed", not to the original function.
8502 bool Reversed = C->isReversed();
8503 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8504 ->getType()
8505 .getUnqualifiedType();
8506 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8507 ->getType()
8508 .getUnqualifiedType();
8509
8510 // Skip if either parameter isn't of enumeral type.
8511 if (!FirstParamType->isEnumeralType() ||
8512 !SecondParamType->isEnumeralType())
8513 continue;
8514
8515 // Add this operator to the set of known user-defined operators.
8516 UserDefinedBinaryOperators.insert(
8517 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8518 S.Context.getCanonicalType(SecondParamType)));
8519 }
8520 }
8521 }
8522
8523 /// Set of (canonical) types that we've already handled.
8524 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8525
8526 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8527 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8528 // Don't add the same builtin candidate twice.
8529 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8530 continue;
8531
8532 QualType ParamTypes[2] = {PtrTy, PtrTy};
8533 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8534 }
8535 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8536 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8537
8538 // Don't add the same builtin candidate twice, or if a user defined
8539 // candidate exists.
8540 if (!AddedTypes.insert(CanonType).second ||
8541 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8542 CanonType)))
8543 continue;
8544 QualType ParamTypes[2] = {EnumTy, EnumTy};
8545 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8546 }
8547 }
8548 }
8549
8550 // C++ [over.built]p13:
8551 //
8552 // For every cv-qualified or cv-unqualified object type T
8553 // there exist candidate operator functions of the form
8554 //
8555 // T* operator+(T*, ptrdiff_t);
8556 // T& operator[](T*, ptrdiff_t); [BELOW]
8557 // T* operator-(T*, ptrdiff_t);
8558 // T* operator+(ptrdiff_t, T*);
8559 // T& operator[](ptrdiff_t, T*); [BELOW]
8560 //
8561 // C++ [over.built]p14:
8562 //
8563 // For every T, where T is a pointer to object type, there
8564 // exist candidate operator functions of the form
8565 //
8566 // ptrdiff_t operator-(T, T);
8567 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8568 /// Set of (canonical) types that we've already handled.
8569 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8570
8571 for (int Arg = 0; Arg < 2; ++Arg) {
8572 QualType AsymmetricParamTypes[2] = {
8573 S.Context.getPointerDiffType(),
8574 S.Context.getPointerDiffType(),
8575 };
8576 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8577 QualType PointeeTy = PtrTy->getPointeeType();
8578 if (!PointeeTy->isObjectType())
8579 continue;
8580
8581 AsymmetricParamTypes[Arg] = PtrTy;
8582 if (Arg == 0 || Op == OO_Plus) {
8583 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8584 // T* operator+(ptrdiff_t, T*);
8585 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8586 }
8587 if (Op == OO_Minus) {
8588 // ptrdiff_t operator-(T, T);
8589 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8590 continue;
8591
8592 QualType ParamTypes[2] = {PtrTy, PtrTy};
8593 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8594 }
8595 }
8596 }
8597 }
8598
8599 // C++ [over.built]p12:
8600 //
8601 // For every pair of promoted arithmetic types L and R, there
8602 // exist candidate operator functions of the form
8603 //
8604 // LR operator*(L, R);
8605 // LR operator/(L, R);
8606 // LR operator+(L, R);
8607 // LR operator-(L, R);
8608 // bool operator<(L, R);
8609 // bool operator>(L, R);
8610 // bool operator<=(L, R);
8611 // bool operator>=(L, R);
8612 // bool operator==(L, R);
8613 // bool operator!=(L, R);
8614 //
8615 // where LR is the result of the usual arithmetic conversions
8616 // between types L and R.
8617 //
8618 // C++ [over.built]p24:
8619 //
8620 // For every pair of promoted arithmetic types L and R, there exist
8621 // candidate operator functions of the form
8622 //
8623 // LR operator?(bool, L, R);
8624 //
8625 // where LR is the result of the usual arithmetic conversions
8626 // between types L and R.
8627 // Our candidates ignore the first parameter.
8628 void addGenericBinaryArithmeticOverloads() {
8629 if (!HasArithmeticOrEnumeralCandidateType)
8630 return;
8631
8632 for (unsigned Left = FirstPromotedArithmeticType;
8633 Left < LastPromotedArithmeticType; ++Left) {
8634 for (unsigned Right = FirstPromotedArithmeticType;
8635 Right < LastPromotedArithmeticType; ++Right) {
8636 QualType LandR[2] = { ArithmeticTypes[Left],
8637 ArithmeticTypes[Right] };
8638 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8639 }
8640 }
8641
8642 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8643 // conditional operator for vector types.
8644 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8645 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8646 QualType LandR[2] = {Vec1Ty, Vec2Ty};
8647 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8648 }
8649 }
8650
8651 /// Add binary operator overloads for each candidate matrix type M1, M2:
8652 /// * (M1, M1) -> M1
8653 /// * (M1, M1.getElementType()) -> M1
8654 /// * (M2.getElementType(), M2) -> M2
8655 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8656 void addMatrixBinaryArithmeticOverloads() {
8657 if (!HasArithmeticOrEnumeralCandidateType)
8658 return;
8659
8660 for (QualType M1 : CandidateTypes[0].matrix_types()) {
8661 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8662 AddCandidate(M1, M1);
8663 }
8664
8665 for (QualType M2 : CandidateTypes[1].matrix_types()) {
8666 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8667 if (!CandidateTypes[0].containsMatrixType(M2))
8668 AddCandidate(M2, M2);
8669 }
8670 }
8671
8672 // C++2a [over.built]p14:
8673 //
8674 // For every integral type T there exists a candidate operator function
8675 // of the form
8676 //
8677 // std::strong_ordering operator<=>(T, T)
8678 //
8679 // C++2a [over.built]p15:
8680 //
8681 // For every pair of floating-point types L and R, there exists a candidate
8682 // operator function of the form
8683 //
8684 // std::partial_ordering operator<=>(L, R);
8685 //
8686 // FIXME: The current specification for integral types doesn't play nice with
8687 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8688 // comparisons. Under the current spec this can lead to ambiguity during
8689 // overload resolution. For example:
8690 //
8691 // enum A : int {a};
8692 // auto x = (a <=> (long)42);
8693 //
8694 // error: call is ambiguous for arguments 'A' and 'long'.
8695 // note: candidate operator<=>(int, int)
8696 // note: candidate operator<=>(long, long)
8697 //
8698 // To avoid this error, this function deviates from the specification and adds
8699 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8700 // arithmetic types (the same as the generic relational overloads).
8701 //
8702 // For now this function acts as a placeholder.
8703 void addThreeWayArithmeticOverloads() {
8704 addGenericBinaryArithmeticOverloads();
8705 }
8706
8707 // C++ [over.built]p17:
8708 //
8709 // For every pair of promoted integral types L and R, there
8710 // exist candidate operator functions of the form
8711 //
8712 // LR operator%(L, R);
8713 // LR operator&(L, R);
8714 // LR operator^(L, R);
8715 // LR operator|(L, R);
8716 // L operator<<(L, R);
8717 // L operator>>(L, R);
8718 //
8719 // where LR is the result of the usual arithmetic conversions
8720 // between types L and R.
8721 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8722 if (!HasArithmeticOrEnumeralCandidateType)
8723 return;
8724
8725 for (unsigned Left = FirstPromotedIntegralType;
8726 Left < LastPromotedIntegralType; ++Left) {
8727 for (unsigned Right = FirstPromotedIntegralType;
8728 Right < LastPromotedIntegralType; ++Right) {
8729 QualType LandR[2] = { ArithmeticTypes[Left],
8730 ArithmeticTypes[Right] };
8731 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8732 }
8733 }
8734 }
8735
8736 // C++ [over.built]p20:
8737 //
8738 // For every pair (T, VQ), where T is an enumeration or
8739 // pointer to member type and VQ is either volatile or
8740 // empty, there exist candidate operator functions of the form
8741 //
8742 // VQ T& operator=(VQ T&, T);
8743 void addAssignmentMemberPointerOrEnumeralOverloads() {
8744 /// Set of (canonical) types that we've already handled.
8745 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8746
8747 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8748 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8749 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8750 continue;
8751
8752 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8753 }
8754
8755 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8756 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8757 continue;
8758
8759 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8760 }
8761 }
8762 }
8763
8764 // C++ [over.built]p19:
8765 //
8766 // For every pair (T, VQ), where T is any type and VQ is either
8767 // volatile or empty, there exist candidate operator functions
8768 // of the form
8769 //
8770 // T*VQ& operator=(T*VQ&, T*);
8771 //
8772 // C++ [over.built]p21:
8773 //
8774 // For every pair (T, VQ), where T is a cv-qualified or
8775 // cv-unqualified object type and VQ is either volatile or
8776 // empty, there exist candidate operator functions of the form
8777 //
8778 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8779 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8780 void addAssignmentPointerOverloads(bool isEqualOp) {
8781 /// Set of (canonical) types that we've already handled.
8782 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8783
8784 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8785 // If this is operator=, keep track of the builtin candidates we added.
8786 if (isEqualOp)
8787 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8788 else if (!PtrTy->getPointeeType()->isObjectType())
8789 continue;
8790
8791 // non-volatile version
8792 QualType ParamTypes[2] = {
8793 S.Context.getLValueReferenceType(PtrTy),
8794 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8795 };
8796 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8797 /*IsAssignmentOperator=*/ isEqualOp);
8798
8799 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8800 VisibleTypeConversionsQuals.hasVolatile();
8801 if (NeedVolatile) {
8802 // volatile version
8803 ParamTypes[0] =
8804 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8805 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8806 /*IsAssignmentOperator=*/isEqualOp);
8807 }
8808
8809 if (!PtrTy.isRestrictQualified() &&
8810 VisibleTypeConversionsQuals.hasRestrict()) {
8811 // restrict version
8812 ParamTypes[0] =
8813 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8814 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8815 /*IsAssignmentOperator=*/isEqualOp);
8816
8817 if (NeedVolatile) {
8818 // volatile restrict version
8819 ParamTypes[0] =
8820 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8821 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8822 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8823 /*IsAssignmentOperator=*/isEqualOp);
8824 }
8825 }
8826 }
8827
8828 if (isEqualOp) {
8829 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8830 // Make sure we don't add the same candidate twice.
8831 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8832 continue;
8833
8834 QualType ParamTypes[2] = {
8835 S.Context.getLValueReferenceType(PtrTy),
8836 PtrTy,
8837 };
8838
8839 // non-volatile version
8840 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8841 /*IsAssignmentOperator=*/true);
8842
8843 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8844 VisibleTypeConversionsQuals.hasVolatile();
8845 if (NeedVolatile) {
8846 // volatile version
8847 ParamTypes[0] = S.Context.getLValueReferenceType(
8848 S.Context.getVolatileType(PtrTy));
8849 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8850 /*IsAssignmentOperator=*/true);
8851 }
8852
8853 if (!PtrTy.isRestrictQualified() &&
8854 VisibleTypeConversionsQuals.hasRestrict()) {
8855 // restrict version
8856 ParamTypes[0] = S.Context.getLValueReferenceType(
8857 S.Context.getRestrictType(PtrTy));
8858 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8859 /*IsAssignmentOperator=*/true);
8860
8861 if (NeedVolatile) {
8862 // volatile restrict version
8863 ParamTypes[0] =
8864 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8865 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8866 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8867 /*IsAssignmentOperator=*/true);
8868 }
8869 }
8870 }
8871 }
8872 }
8873
8874 // C++ [over.built]p18:
8875 //
8876 // For every triple (L, VQ, R), where L is an arithmetic type,
8877 // VQ is either volatile or empty, and R is a promoted
8878 // arithmetic type, there exist candidate operator functions of
8879 // the form
8880 //
8881 // VQ L& operator=(VQ L&, R);
8882 // VQ L& operator*=(VQ L&, R);
8883 // VQ L& operator/=(VQ L&, R);
8884 // VQ L& operator+=(VQ L&, R);
8885 // VQ L& operator-=(VQ L&, R);
8886 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8887 if (!HasArithmeticOrEnumeralCandidateType)
8888 return;
8889
8890 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8891 for (unsigned Right = FirstPromotedArithmeticType;
8892 Right < LastPromotedArithmeticType; ++Right) {
8893 QualType ParamTypes[2];
8894 ParamTypes[1] = ArithmeticTypes[Right];
8895 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8896 S, ArithmeticTypes[Left], Args[0]);
8897 // Add this built-in operator as a candidate (VQ is empty).
8898 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8899 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8900 /*IsAssignmentOperator=*/isEqualOp);
8901
8902 // Add this built-in operator as a candidate (VQ is 'volatile').
8903 if (VisibleTypeConversionsQuals.hasVolatile()) {
8904 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8905 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8906 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8907 /*IsAssignmentOperator=*/isEqualOp);
8908 }
8909 }
8910 }
8911
8912 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8913 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8914 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8915 QualType ParamTypes[2];
8916 ParamTypes[1] = Vec2Ty;
8917 // Add this built-in operator as a candidate (VQ is empty).
8918 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8919 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8920 /*IsAssignmentOperator=*/isEqualOp);
8921
8922 // Add this built-in operator as a candidate (VQ is 'volatile').
8923 if (VisibleTypeConversionsQuals.hasVolatile()) {
8924 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8925 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8926 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8927 /*IsAssignmentOperator=*/isEqualOp);
8928 }
8929 }
8930 }
8931
8932 // C++ [over.built]p22:
8933 //
8934 // For every triple (L, VQ, R), where L is an integral type, VQ
8935 // is either volatile or empty, and R is a promoted integral
8936 // type, there exist candidate operator functions of the form
8937 //
8938 // VQ L& operator%=(VQ L&, R);
8939 // VQ L& operator<<=(VQ L&, R);
8940 // VQ L& operator>>=(VQ L&, R);
8941 // VQ L& operator&=(VQ L&, R);
8942 // VQ L& operator^=(VQ L&, R);
8943 // VQ L& operator|=(VQ L&, R);
8944 void addAssignmentIntegralOverloads() {
8945 if (!HasArithmeticOrEnumeralCandidateType)
8946 return;
8947
8948 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8949 for (unsigned Right = FirstPromotedIntegralType;
8950 Right < LastPromotedIntegralType; ++Right) {
8951 QualType ParamTypes[2];
8952 ParamTypes[1] = ArithmeticTypes[Right];
8953 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8954 S, ArithmeticTypes[Left], Args[0]);
8955 // Add this built-in operator as a candidate (VQ is empty).
8956 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8957 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8958 if (VisibleTypeConversionsQuals.hasVolatile()) {
8959 // Add this built-in operator as a candidate (VQ is 'volatile').
8960 ParamTypes[0] = LeftBaseTy;
8961 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8962 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8963 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8964 }
8965 }
8966 }
8967 }
8968
8969 // C++ [over.operator]p23:
8970 //
8971 // There also exist candidate operator functions of the form
8972 //
8973 // bool operator!(bool);
8974 // bool operator&&(bool, bool);
8975 // bool operator||(bool, bool);
8976 void addExclaimOverload() {
8977 QualType ParamTy = S.Context.BoolTy;
8978 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8979 /*IsAssignmentOperator=*/false,
8980 /*NumContextualBoolArguments=*/1);
8981 }
8982 void addAmpAmpOrPipePipeOverload() {
8983 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8984 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8985 /*IsAssignmentOperator=*/false,
8986 /*NumContextualBoolArguments=*/2);
8987 }
8988
8989 // C++ [over.built]p13:
8990 //
8991 // For every cv-qualified or cv-unqualified object type T there
8992 // exist candidate operator functions of the form
8993 //
8994 // T* operator+(T*, ptrdiff_t); [ABOVE]
8995 // T& operator[](T*, ptrdiff_t);
8996 // T* operator-(T*, ptrdiff_t); [ABOVE]
8997 // T* operator+(ptrdiff_t, T*); [ABOVE]
8998 // T& operator[](ptrdiff_t, T*);
8999 void addSubscriptOverloads() {
9000 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9001 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9002 QualType PointeeType = PtrTy->getPointeeType();
9003 if (!PointeeType->isObjectType())
9004 continue;
9005
9006 // T& operator[](T*, ptrdiff_t)
9007 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9008 }
9009
9010 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9011 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9012 QualType PointeeType = PtrTy->getPointeeType();
9013 if (!PointeeType->isObjectType())
9014 continue;
9015
9016 // T& operator[](ptrdiff_t, T*)
9017 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9018 }
9019 }
9020
9021 // C++ [over.built]p11:
9022 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9023 // C1 is the same type as C2 or is a derived class of C2, T is an object
9024 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9025 // there exist candidate operator functions of the form
9026 //
9027 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9028 //
9029 // where CV12 is the union of CV1 and CV2.
9030 void addArrowStarOverloads() {
9031 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9032 QualType C1Ty = PtrTy;
9033 QualType C1;
9034 QualifierCollector Q1;
9035 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9036 if (!isa<RecordType>(C1))
9037 continue;
9038 // heuristic to reduce number of builtin candidates in the set.
9039 // Add volatile/restrict version only if there are conversions to a
9040 // volatile/restrict type.
9041 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9042 continue;
9043 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9044 continue;
9045 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9046 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9047 QualType C2 = QualType(mptr->getClass(), 0);
9048 C2 = C2.getUnqualifiedType();
9049 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9050 break;
9051 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9052 // build CV12 T&
9053 QualType T = mptr->getPointeeType();
9054 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9055 T.isVolatileQualified())
9056 continue;
9057 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9058 T.isRestrictQualified())
9059 continue;
9060 T = Q1.apply(S.Context, T);
9061 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9062 }
9063 }
9064 }
9065
9066 // Note that we don't consider the first argument, since it has been
9067 // contextually converted to bool long ago. The candidates below are
9068 // therefore added as binary.
9069 //
9070 // C++ [over.built]p25:
9071 // For every type T, where T is a pointer, pointer-to-member, or scoped
9072 // enumeration type, there exist candidate operator functions of the form
9073 //
9074 // T operator?(bool, T, T);
9075 //
9076 void addConditionalOperatorOverloads() {
9077 /// Set of (canonical) types that we've already handled.
9078 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9079
9080 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9081 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9082 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9083 continue;
9084
9085 QualType ParamTypes[2] = {PtrTy, PtrTy};
9086 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9087 }
9088
9089 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9090 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9091 continue;
9092
9093 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9094 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9095 }
9096
9097 if (S.getLangOpts().CPlusPlus11) {
9098 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9099 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9100 continue;
9101
9102 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9103 continue;
9104
9105 QualType ParamTypes[2] = {EnumTy, EnumTy};
9106 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9107 }
9108 }
9109 }
9110 }
9111};
9112
9113} // end anonymous namespace
9114
9115/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9116/// operator overloads to the candidate set (C++ [over.built]), based
9117/// on the operator @p Op and the arguments given. For example, if the
9118/// operator is a binary '+', this routine might add "int
9119/// operator+(int, int)" to cover integer addition.
9120void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9121 SourceLocation OpLoc,
9122 ArrayRef<Expr *> Args,
9123 OverloadCandidateSet &CandidateSet) {
9124 // Find all of the types that the arguments can convert to, but only
9125 // if the operator we're looking at has built-in operator candidates
9126 // that make use of these types. Also record whether we encounter non-record
9127 // candidate types or either arithmetic or enumeral candidate types.
9128 Qualifiers VisibleTypeConversionsQuals;
9129 VisibleTypeConversionsQuals.addConst();
9130 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9131 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9132
9133 bool HasNonRecordCandidateType = false;
9134 bool HasArithmeticOrEnumeralCandidateType = false;
9135 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9136 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9137 CandidateTypes.emplace_back(*this);
9138 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9139 OpLoc,
9140 true,
9141 (Op == OO_Exclaim ||
9142 Op == OO_AmpAmp ||
9143 Op == OO_PipePipe),
9144 VisibleTypeConversionsQuals);
9145 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9146 CandidateTypes[ArgIdx].hasNonRecordTypes();
9147 HasArithmeticOrEnumeralCandidateType =
9148 HasArithmeticOrEnumeralCandidateType ||
9149 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9150 }
9151
9152 // Exit early when no non-record types have been added to the candidate set
9153 // for any of the arguments to the operator.
9154 //
9155 // We can't exit early for !, ||, or &&, since there we have always have
9156 // 'bool' overloads.
9157 if (!HasNonRecordCandidateType &&
9158 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9159 return;
9160
9161 // Setup an object to manage the common state for building overloads.
9162 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9163 VisibleTypeConversionsQuals,
9164 HasArithmeticOrEnumeralCandidateType,
9165 CandidateTypes, CandidateSet);
9166
9167 // Dispatch over the operation to add in only those overloads which apply.
9168 switch (Op) {
9169 case OO_None:
9170 case NUM_OVERLOADED_OPERATORS:
9171 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9171)
;
9172
9173 case OO_New:
9174 case OO_Delete:
9175 case OO_Array_New:
9176 case OO_Array_Delete:
9177 case OO_Call:
9178 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9179)
9179 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9179)
;
9180
9181 case OO_Comma:
9182 case OO_Arrow:
9183 case OO_Coawait:
9184 // C++ [over.match.oper]p3:
9185 // -- For the operator ',', the unary operator '&', the
9186 // operator '->', or the operator 'co_await', the
9187 // built-in candidates set is empty.
9188 break;
9189
9190 case OO_Plus: // '+' is either unary or binary
9191 if (Args.size() == 1)
9192 OpBuilder.addUnaryPlusPointerOverloads();
9193 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9194
9195 case OO_Minus: // '-' is either unary or binary
9196 if (Args.size() == 1) {
9197 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9198 } else {
9199 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9200 OpBuilder.addGenericBinaryArithmeticOverloads();
9201 OpBuilder.addMatrixBinaryArithmeticOverloads();
9202 }
9203 break;
9204
9205 case OO_Star: // '*' is either unary or binary
9206 if (Args.size() == 1)
9207 OpBuilder.addUnaryStarPointerOverloads();
9208 else {
9209 OpBuilder.addGenericBinaryArithmeticOverloads();
9210 OpBuilder.addMatrixBinaryArithmeticOverloads();
9211 }
9212 break;
9213
9214 case OO_Slash:
9215 OpBuilder.addGenericBinaryArithmeticOverloads();
9216 break;
9217
9218 case OO_PlusPlus:
9219 case OO_MinusMinus:
9220 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9221 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9222 break;
9223
9224 case OO_EqualEqual:
9225 case OO_ExclaimEqual:
9226 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9227 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9228
9229 case OO_Less:
9230 case OO_Greater:
9231 case OO_LessEqual:
9232 case OO_GreaterEqual:
9233 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9234 OpBuilder.addGenericBinaryArithmeticOverloads();
9235 break;
9236
9237 case OO_Spaceship:
9238 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9239 OpBuilder.addThreeWayArithmeticOverloads();
9240 break;
9241
9242 case OO_Percent:
9243 case OO_Caret:
9244 case OO_Pipe:
9245 case OO_LessLess:
9246 case OO_GreaterGreater:
9247 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9248 break;
9249
9250 case OO_Amp: // '&' is either unary or binary
9251 if (Args.size() == 1)
9252 // C++ [over.match.oper]p3:
9253 // -- For the operator ',', the unary operator '&', or the
9254 // operator '->', the built-in candidates set is empty.
9255 break;
9256
9257 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9258 break;
9259
9260 case OO_Tilde:
9261 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9262 break;
9263
9264 case OO_Equal:
9265 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9266 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9267
9268 case OO_PlusEqual:
9269 case OO_MinusEqual:
9270 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9271 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9272
9273 case OO_StarEqual:
9274 case OO_SlashEqual:
9275 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9276 break;
9277
9278 case OO_PercentEqual:
9279 case OO_LessLessEqual:
9280 case OO_GreaterGreaterEqual:
9281 case OO_AmpEqual:
9282 case OO_CaretEqual:
9283 case OO_PipeEqual:
9284 OpBuilder.addAssignmentIntegralOverloads();
9285 break;
9286
9287 case OO_Exclaim:
9288 OpBuilder.addExclaimOverload();
9289 break;
9290
9291 case OO_AmpAmp:
9292 case OO_PipePipe:
9293 OpBuilder.addAmpAmpOrPipePipeOverload();
9294 break;
9295
9296 case OO_Subscript:
9297 OpBuilder.addSubscriptOverloads();
9298 break;
9299
9300 case OO_ArrowStar:
9301 OpBuilder.addArrowStarOverloads();
9302 break;
9303
9304 case OO_Conditional:
9305 OpBuilder.addConditionalOperatorOverloads();
9306 OpBuilder.addGenericBinaryArithmeticOverloads();
9307 break;
9308 }
9309}
9310
9311/// Add function candidates found via argument-dependent lookup
9312/// to the set of overloading candidates.
9313///
9314/// This routine performs argument-dependent name lookup based on the
9315/// given function name (which may also be an operator name) and adds
9316/// all of the overload candidates found by ADL to the overload
9317/// candidate set (C++ [basic.lookup.argdep]).
9318void
9319Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9320 SourceLocation Loc,
9321 ArrayRef<Expr *> Args,
9322 TemplateArgumentListInfo *ExplicitTemplateArgs,
9323 OverloadCandidateSet& CandidateSet,
9324 bool PartialOverloading) {
9325 ADLResult Fns;
9326
9327 // FIXME: This approach for uniquing ADL results (and removing
9328 // redundant candidates from the set) relies on pointer-equality,
9329 // which means we need to key off the canonical decl. However,
9330 // always going back to the canonical decl might not get us the
9331 // right set of default arguments. What default arguments are
9332 // we supposed to consider on ADL candidates, anyway?
9333
9334 // FIXME: Pass in the explicit template arguments?
9335 ArgumentDependentLookup(Name, Loc, Args, Fns);
9336
9337 // Erase all of the candidates we already knew about.
9338 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9339 CandEnd = CandidateSet.end();
9340 Cand != CandEnd; ++Cand)
9341 if (Cand->Function) {
9342 Fns.erase(Cand->Function);
9343 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9344 Fns.erase(FunTmpl);
9345 }
9346
9347 // For each of the ADL candidates we found, add it to the overload
9348 // set.
9349 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9350 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9351
9352 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9353 if (ExplicitTemplateArgs)
9354 continue;
9355
9356 AddOverloadCandidate(
9357 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9358 PartialOverloading, /*AllowExplicit=*/true,
9359 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9360 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9361 AddOverloadCandidate(
9362 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9363 /*SuppressUserConversions=*/false, PartialOverloading,
9364 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9365 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9366 }
9367 } else {
9368 auto *FTD = cast<FunctionTemplateDecl>(*I);
9369 AddTemplateOverloadCandidate(
9370 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9371 /*SuppressUserConversions=*/false, PartialOverloading,
9372 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9373 if (CandidateSet.getRewriteInfo().shouldAddReversed(
9374 Context, FTD->getTemplatedDecl())) {
9375 AddTemplateOverloadCandidate(
9376 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9377 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9378 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9379 OverloadCandidateParamOrder::Reversed);
9380 }
9381 }
9382 }
9383}
9384
9385namespace {
9386enum class Comparison { Equal, Better, Worse };
9387}
9388
9389/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9390/// overload resolution.
9391///
9392/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9393/// Cand1's first N enable_if attributes have precisely the same conditions as
9394/// Cand2's first N enable_if attributes (where N = the number of enable_if
9395/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9396///
9397/// Note that you can have a pair of candidates such that Cand1's enable_if
9398/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9399/// worse than Cand1's.
9400static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9401 const FunctionDecl *Cand2) {
9402 // Common case: One (or both) decls don't have enable_if attrs.
9403 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9404 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9405 if (!Cand1Attr || !Cand2Attr) {
9406 if (Cand1Attr == Cand2Attr)
9407 return Comparison::Equal;
9408 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9409 }
9410
9411 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9412 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9413
9414 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9415 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9416 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9417 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9418
9419 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9420 // has fewer enable_if attributes than Cand2, and vice versa.
9421 if (!Cand1A)
9422 return Comparison::Worse;
9423 if (!Cand2A)
9424 return Comparison::Better;
9425
9426 Cand1ID.clear();
9427 Cand2ID.clear();
9428
9429 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9430 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9431 if (Cand1ID != Cand2ID)
9432 return Comparison::Worse;
9433 }
9434
9435 return Comparison::Equal;
9436}
9437
9438static Comparison
9439isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9440 const OverloadCandidate &Cand2) {
9441 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9442 !Cand2.Function->isMultiVersion())
9443 return Comparison::Equal;
9444
9445 // If both are invalid, they are equal. If one of them is invalid, the other
9446 // is better.
9447 if (Cand1.Function->isInvalidDecl()) {
9448 if (Cand2.Function->isInvalidDecl())
9449 return Comparison::Equal;
9450 return Comparison::Worse;
9451 }
9452 if (Cand2.Function->isInvalidDecl())
9453 return Comparison::Better;
9454
9455 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9456 // cpu_dispatch, else arbitrarily based on the identifiers.
9457 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9458 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9459 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9460 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9461
9462 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9463 return Comparison::Equal;
9464
9465 if (Cand1CPUDisp && !Cand2CPUDisp)
9466 return Comparison::Better;
9467 if (Cand2CPUDisp && !Cand1CPUDisp)
9468 return Comparison::Worse;
9469
9470 if (Cand1CPUSpec && Cand2CPUSpec) {
9471 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9472 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9473 ? Comparison::Better
9474 : Comparison::Worse;
9475
9476 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9477 FirstDiff = std::mismatch(
9478 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9479 Cand2CPUSpec->cpus_begin(),
9480 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9481 return LHS->getName() == RHS->getName();
9482 });
9483
9484 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9486, __PRETTY_FUNCTION__))
9485 "Two different cpu-specific versions should not have the same "((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9486, __PRETTY_FUNCTION__))
9486 "identifier list, otherwise they'd be the same decl!")((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9486, __PRETTY_FUNCTION__))
;
9487 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9488 ? Comparison::Better
9489 : Comparison::Worse;
9490 }
9491 llvm_unreachable("No way to get here unless both had cpu_dispatch")::llvm::llvm_unreachable_internal("No way to get here unless both had cpu_dispatch"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9491)
;
9492}
9493
9494/// Compute the type of the implicit object parameter for the given function,
9495/// if any. Returns None if there is no implicit object parameter, and a null
9496/// QualType if there is a 'matches anything' implicit object parameter.
9497static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9498 const FunctionDecl *F) {
9499 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9500 return llvm::None;
9501
9502 auto *M = cast<CXXMethodDecl>(F);
9503 // Static member functions' object parameters match all types.
9504 if (M->isStatic())
9505 return QualType();
9506
9507 QualType T = M->getThisObjectType();
9508 if (M->getRefQualifier() == RQ_RValue)
9509 return Context.getRValueReferenceType(T);
9510 return Context.getLValueReferenceType(T);
9511}
9512
9513static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9514 const FunctionDecl *F2, unsigned NumParams) {
9515 if (declaresSameEntity(F1, F2))
9516 return true;
9517
9518 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9519 if (First) {
9520 if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9521 return *T;
9522 }
9523 assert(I < F->getNumParams())((I < F->getNumParams()) ? static_cast<void> (0) :
__assert_fail ("I < F->getNumParams()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9523, __PRETTY_FUNCTION__))
;
9524 return F->getParamDecl(I++)->getType();
9525 };
9526
9527 unsigned I1 = 0, I2 = 0;
9528 for (unsigned I = 0; I != NumParams; ++I) {
9529 QualType T1 = NextParam(F1, I1, I == 0);
9530 QualType T2 = NextParam(F2, I2, I == 0);
9531 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9532 return false;
9533 }
9534 return true;
9535}
9536
9537/// isBetterOverloadCandidate - Determines whether the first overload
9538/// candidate is a better candidate than the second (C++ 13.3.3p1).
9539bool clang::isBetterOverloadCandidate(
9540 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9541 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9542 // Define viable functions to be better candidates than non-viable
9543 // functions.
9544 if (!Cand2.Viable)
9545 return Cand1.Viable;
9546 else if (!Cand1.Viable)
9547 return false;
9548
9549 // [CUDA] A function with 'never' preference is marked not viable, therefore
9550 // is never shown up here. The worst preference shown up here is 'wrong side',
9551 // e.g. an H function called by a HD function in device compilation. This is
9552 // valid AST as long as the HD function is not emitted, e.g. it is an inline
9553 // function which is called only by an H function. A deferred diagnostic will
9554 // be triggered if it is emitted. However a wrong-sided function is still
9555 // a viable candidate here.
9556 //
9557 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9558 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9559 // can be emitted, Cand1 is not better than Cand2. This rule should have
9560 // precedence over other rules.
9561 //
9562 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9563 // other rules should be used to determine which is better. This is because
9564 // host/device based overloading resolution is mostly for determining
9565 // viability of a function. If two functions are both viable, other factors
9566 // should take precedence in preference, e.g. the standard-defined preferences
9567 // like argument conversion ranks or enable_if partial-ordering. The
9568 // preference for pass-object-size parameters is probably most similar to a
9569 // type-based-overloading decision and so should take priority.
9570 //
9571 // If other rules cannot determine which is better, CUDA preference will be
9572 // used again to determine which is better.
9573 //
9574 // TODO: Currently IdentifyCUDAPreference does not return correct values
9575 // for functions called in global variable initializers due to missing
9576 // correct context about device/host. Therefore we can only enforce this
9577 // rule when there is a caller. We should enforce this rule for functions
9578 // in global variable initializers once proper context is added.
9579 //
9580 // TODO: We can only enable the hostness based overloading resolution when
9581 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9582 // overloading resolution diagnostics.
9583 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9584 S.getLangOpts().GPUExcludeWrongSideOverloads) {
9585 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) {
9586 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9587 bool IsCand1ImplicitHD =
9588 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9589 bool IsCand2ImplicitHD =
9590 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9591 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9592 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9593 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never)((P1 != Sema::CFP_Never && P2 != Sema::CFP_Never) ? static_cast
<void> (0) : __assert_fail ("P1 != Sema::CFP_Never && P2 != Sema::CFP_Never"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9593, __PRETTY_FUNCTION__))
;
9594 // The implicit HD function may be a function in a system header which
9595 // is forced by pragma. In device compilation, if we prefer HD candidates
9596 // over wrong-sided candidates, overloading resolution may change, which
9597 // may result in non-deferrable diagnostics. As a workaround, we let
9598 // implicit HD candidates take equal preference as wrong-sided candidates.
9599 // This will preserve the overloading resolution.
9600 // TODO: We still need special handling of implicit HD functions since
9601 // they may incur other diagnostics to be deferred. We should make all
9602 // host/device related diagnostics deferrable and remove special handling
9603 // of implicit HD functions.
9604 auto EmitThreshold =
9605 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9606 (IsCand1ImplicitHD || IsCand2ImplicitHD))
9607 ? Sema::CFP_Never
9608 : Sema::CFP_WrongSide;
9609 auto Cand1Emittable = P1 > EmitThreshold;
9610 auto Cand2Emittable = P2 > EmitThreshold;
9611 if (Cand1Emittable && !Cand2Emittable)
9612 return true;
9613 if (!Cand1Emittable && Cand2Emittable)
9614 return false;
9615 }
9616 }
9617
9618 // C++ [over.match.best]p1:
9619 //
9620 // -- if F is a static member function, ICS1(F) is defined such
9621 // that ICS1(F) is neither better nor worse than ICS1(G) for
9622 // any function G, and, symmetrically, ICS1(G) is neither
9623 // better nor worse than ICS1(F).
9624 unsigned StartArg = 0;
9625 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9626 StartArg = 1;
9627
9628 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9629 // We don't allow incompatible pointer conversions in C++.
9630 if (!S.getLangOpts().CPlusPlus)
9631 return ICS.isStandard() &&
9632 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9633
9634 // The only ill-formed conversion we allow in C++ is the string literal to
9635 // char* conversion, which is only considered ill-formed after C++11.
9636 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9637 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9638 };
9639
9640 // Define functions that don't require ill-formed conversions for a given
9641 // argument to be better candidates than functions that do.
9642 unsigned NumArgs = Cand1.Conversions.size();
9643 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")((Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"
) ? static_cast<void> (0) : __assert_fail ("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9643, __PRETTY_FUNCTION__))
;
9644 bool HasBetterConversion = false;
9645 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9646 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9647 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9648 if (Cand1Bad != Cand2Bad) {
9649 if (Cand1Bad)
9650 return false;
9651 HasBetterConversion = true;
9652 }
9653 }
9654
9655 if (HasBetterConversion)
9656 return true;
9657
9658 // C++ [over.match.best]p1:
9659 // A viable function F1 is defined to be a better function than another
9660 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9661 // conversion sequence than ICSi(F2), and then...
9662 bool HasWorseConversion = false;
9663 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9664 switch (CompareImplicitConversionSequences(S, Loc,
9665 Cand1.Conversions[ArgIdx],
9666 Cand2.Conversions[ArgIdx])) {
9667 case ImplicitConversionSequence::Better:
9668 // Cand1 has a better conversion sequence.
9669 HasBetterConversion = true;
9670 break;
9671
9672 case ImplicitConversionSequence::Worse:
9673 if (Cand1.Function && Cand2.Function &&
9674 Cand1.isReversed() != Cand2.isReversed() &&
9675 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9676 NumArgs)) {
9677 // Work around large-scale breakage caused by considering reversed
9678 // forms of operator== in C++20:
9679 //
9680 // When comparing a function against a reversed function with the same
9681 // parameter types, if we have a better conversion for one argument and
9682 // a worse conversion for the other, the implicit conversion sequences
9683 // are treated as being equally good.
9684 //
9685 // This prevents a comparison function from being considered ambiguous
9686 // with a reversed form that is written in the same way.
9687 //
9688 // We diagnose this as an extension from CreateOverloadedBinOp.
9689 HasWorseConversion = true;
9690 break;
9691 }
9692
9693 // Cand1 can't be better than Cand2.
9694 return false;
9695
9696 case ImplicitConversionSequence::Indistinguishable:
9697 // Do nothing.
9698 break;
9699 }
9700 }
9701
9702 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9703 // ICSj(F2), or, if not that,
9704 if (HasBetterConversion && !HasWorseConversion)
9705 return true;
9706
9707 // -- the context is an initialization by user-defined conversion
9708 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9709 // from the return type of F1 to the destination type (i.e.,
9710 // the type of the entity being initialized) is a better
9711 // conversion sequence than the standard conversion sequence
9712 // from the return type of F2 to the destination type.
9713 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9714 Cand1.Function && Cand2.Function &&
9715 isa<CXXConversionDecl>(Cand1.Function) &&
9716 isa<CXXConversionDecl>(Cand2.Function)) {
9717 // First check whether we prefer one of the conversion functions over the
9718 // other. This only distinguishes the results in non-standard, extension
9719 // cases such as the conversion from a lambda closure type to a function
9720 // pointer or block.
9721 ImplicitConversionSequence::CompareKind Result =
9722 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9723 if (Result == ImplicitConversionSequence::Indistinguishable)
9724 Result = CompareStandardConversionSequences(S, Loc,
9725 Cand1.FinalConversion,
9726 Cand2.FinalConversion);
9727
9728 if (Result != ImplicitConversionSequence::Indistinguishable)
9729 return Result == ImplicitConversionSequence::Better;
9730
9731 // FIXME: Compare kind of reference binding if conversion functions
9732 // convert to a reference type used in direct reference binding, per
9733 // C++14 [over.match.best]p1 section 2 bullet 3.
9734 }
9735
9736 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9737 // as combined with the resolution to CWG issue 243.
9738 //
9739 // When the context is initialization by constructor ([over.match.ctor] or
9740 // either phase of [over.match.list]), a constructor is preferred over
9741 // a conversion function.
9742 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9743 Cand1.Function && Cand2.Function &&
9744 isa<CXXConstructorDecl>(Cand1.Function) !=
9745 isa<CXXConstructorDecl>(Cand2.Function))
9746 return isa<CXXConstructorDecl>(Cand1.Function);
9747
9748 // -- F1 is a non-template function and F2 is a function template
9749 // specialization, or, if not that,
9750 bool Cand1IsSpecialization = Cand1.Function &&
9751 Cand1.Function->getPrimaryTemplate();
9752 bool Cand2IsSpecialization = Cand2.Function &&
9753 Cand2.Function->getPrimaryTemplate();
9754 if (Cand1IsSpecialization != Cand2IsSpecialization)
9755 return Cand2IsSpecialization;
9756
9757 // -- F1 and F2 are function template specializations, and the function
9758 // template for F1 is more specialized than the template for F2
9759 // according to the partial ordering rules described in 14.5.5.2, or,
9760 // if not that,
9761 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9762 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9763 Cand1.Function->getPrimaryTemplate(),
9764 Cand2.Function->getPrimaryTemplate(), Loc,
9765 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9766 : TPOC_Call,
9767 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9768 Cand1.isReversed() ^ Cand2.isReversed()))
9769 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9770 }
9771
9772 // -— F1 and F2 are non-template functions with the same
9773 // parameter-type-lists, and F1 is more constrained than F2 [...],
9774 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9775 !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9776 Cand2.Function->hasPrototype()) {
9777 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9778 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9779 if (PT1->getNumParams() == PT2->getNumParams() &&
9780 PT1->isVariadic() == PT2->isVariadic() &&
9781 S.FunctionParamTypesAreEqual(PT1, PT2)) {
9782 Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9783 Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9784 if (RC1 && RC2) {
9785 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9786 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9787 {RC2}, AtLeastAsConstrained1) ||
9788 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9789 {RC1}, AtLeastAsConstrained2))
9790 return false;
9791 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9792 return AtLeastAsConstrained1;
9793 } else if (RC1 || RC2) {
9794 return RC1 != nullptr;
9795 }
9796 }
9797 }
9798
9799 // -- F1 is a constructor for a class D, F2 is a constructor for a base
9800 // class B of D, and for all arguments the corresponding parameters of
9801 // F1 and F2 have the same type.
9802 // FIXME: Implement the "all parameters have the same type" check.
9803 bool Cand1IsInherited =
9804 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9805 bool Cand2IsInherited =
9806 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9807 if (Cand1IsInherited != Cand2IsInherited)
9808 return Cand2IsInherited;
9809 else if (Cand1IsInherited) {
9810 assert(Cand2IsInherited)((Cand2IsInherited) ? static_cast<void> (0) : __assert_fail
("Cand2IsInherited", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 9810, __PRETTY_FUNCTION__))
;
9811 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9812 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9813 if (Cand1Class->isDerivedFrom(Cand2Class))
9814 return true;
9815 if (Cand2Class->isDerivedFrom(Cand1Class))
9816 return false;
9817 // Inherited from sibling base classes: still ambiguous.
9818 }
9819
9820 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9821 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9822 // with reversed order of parameters and F1 is not
9823 //
9824 // We rank reversed + different operator as worse than just reversed, but
9825 // that comparison can never happen, because we only consider reversing for
9826 // the maximally-rewritten operator (== or <=>).
9827 if (Cand1.RewriteKind != Cand2.RewriteKind)
9828 return Cand1.RewriteKind < Cand2.RewriteKind;
9829
9830 // Check C++17 tie-breakers for deduction guides.
9831 {
9832 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9833 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9834 if (Guide1 && Guide2) {
9835 // -- F1 is generated from a deduction-guide and F2 is not
9836 if (Guide1->isImplicit() != Guide2->isImplicit())
9837 return Guide2->isImplicit();
9838
9839 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9840 if (Guide1->isCopyDeductionCandidate())
9841 return true;
9842 }
9843 }
9844
9845 // Check for enable_if value-based overload resolution.
9846 if (Cand1.Function && Cand2.Function) {
9847 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9848 if (Cmp != Comparison::Equal)
9849 return Cmp == Comparison::Better;
9850 }
9851
9852 bool HasPS1 = Cand1.Function != nullptr &&
9853 functionHasPassObjectSizeParams(Cand1.Function);
9854 bool HasPS2 = Cand2.Function != nullptr &&
9855 functionHasPassObjectSizeParams(Cand2.Function);
9856 if (HasPS1 != HasPS2 && HasPS1)
9857 return true;
9858
9859 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
9860 if (MV == Comparison::Better)
9861 return true;
9862 if (MV == Comparison::Worse)
9863 return false;
9864
9865 // If other rules cannot determine which is better, CUDA preference is used
9866 // to determine which is better.
9867 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9868 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9869 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9870 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9871 }
9872
9873 return false;
9874}
9875
9876/// Determine whether two declarations are "equivalent" for the purposes of
9877/// name lookup and overload resolution. This applies when the same internal/no
9878/// linkage entity is defined by two modules (probably by textually including
9879/// the same header). In such a case, we don't consider the declarations to
9880/// declare the same entity, but we also don't want lookups with both
9881/// declarations visible to be ambiguous in some cases (this happens when using
9882/// a modularized libstdc++).
9883bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9884 const NamedDecl *B) {
9885 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9886 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9887 if (!VA || !VB)
9888 return false;
9889
9890 // The declarations must be declaring the same name as an internal linkage
9891 // entity in different modules.
9892 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9893 VB->getDeclContext()->getRedeclContext()) ||
9894 getOwningModule(VA) == getOwningModule(VB) ||
9895 VA->isExternallyVisible() || VB->isExternallyVisible())
9896 return false;
9897
9898 // Check that the declarations appear to be equivalent.
9899 //
9900 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9901 // For constants and functions, we should check the initializer or body is
9902 // the same. For non-constant variables, we shouldn't allow it at all.
9903 if (Context.hasSameType(VA->getType(), VB->getType()))
9904 return true;
9905
9906 // Enum constants within unnamed enumerations will have different types, but
9907 // may still be similar enough to be interchangeable for our purposes.
9908 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9909 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9910 // Only handle anonymous enums. If the enumerations were named and
9911 // equivalent, they would have been merged to the same type.
9912 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9913 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9914 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9915 !Context.hasSameType(EnumA->getIntegerType(),
9916 EnumB->getIntegerType()))
9917 return false;
9918 // Allow this only if the value is the same for both enumerators.
9919 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9920 }
9921 }
9922
9923 // Nothing else is sufficiently similar.
9924 return false;
9925}
9926
9927void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9928 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9929 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9930
9931 Module *M = getOwningModule(D);
19
Passing null pointer value via 1st parameter 'Entity'
20
Calling 'Sema::getOwningModule'
9932 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9933 << !M << (M ? M->getFullModuleName() : "");
9934
9935 for (auto *E : Equiv) {
9936 Module *M = getOwningModule(E);
9937 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9938 << !M << (M ? M->getFullModuleName() : "");
9939 }
9940}
9941
9942/// Computes the best viable function (C++ 13.3.3)
9943/// within an overload candidate set.
9944///
9945/// \param Loc The location of the function name (or operator symbol) for
9946/// which overload resolution occurs.
9947///
9948/// \param Best If overload resolution was successful or found a deleted
9949/// function, \p Best points to the candidate function found.
9950///
9951/// \returns The result of overload resolution.
9952OverloadingResult
9953OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9954 iterator &Best) {
9955 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9956 std::transform(begin(), end(), std::back_inserter(Candidates),
9957 [](OverloadCandidate &Cand) { return &Cand; });
9958
9959 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9960 // are accepted by both clang and NVCC. However, during a particular
9961 // compilation mode only one call variant is viable. We need to
9962 // exclude non-viable overload candidates from consideration based
9963 // only on their host/device attributes. Specifically, if one
9964 // candidate call is WrongSide and the other is SameSide, we ignore
9965 // the WrongSide candidate.
9966 // We only need to remove wrong-sided candidates here if
9967 // -fgpu-exclude-wrong-side-overloads is off. When
9968 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
9969 // uniformly in isBetterOverloadCandidate.
9970 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
3
Assuming field 'CUDA' is 0
9971 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9972 bool ContainsSameSideCandidate =
9973 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9974 // Check viable function only.
9975 return Cand->Viable && Cand->Function &&
9976 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9977 Sema::CFP_SameSide;
9978 });
9979 if (ContainsSameSideCandidate) {
9980 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9981 // Check viable function only to avoid unnecessary data copying/moving.
9982 return Cand->Viable && Cand->Function &&
9983 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9984 Sema::CFP_WrongSide;
9985 };
9986 llvm::erase_if(Candidates, IsWrongSideCandidate);
9987 }
9988 }
9989
9990 // Find the best viable function.
9991 Best = end();
9992 for (auto *Cand : Candidates) {
4
Assuming '__begin1' is equal to '__end1'
9993 Cand->Best = false;
9994 if (Cand->Viable)
9995 if (Best == end() ||
9996 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9997 Best = Cand;
9998 }
9999
10000 // If we didn't find any viable functions, abort.
10001 if (Best == end())
5
Assuming the condition is false
6
Taking false branch
10002 return OR_No_Viable_Function;
10003
10004 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10005
10006 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10007 PendingBest.push_back(&*Best);
7
Value assigned to field 'Function'
10008 Best->Best = true;
10009
10010 // Make sure that this function is better than every other viable
10011 // function. If not, we have an ambiguity.
10012 while (!PendingBest.empty()) {
8
Loop condition is false. Execution continues on line 10030
10013 auto *Curr = PendingBest.pop_back_val();
10014 for (auto *Cand : Candidates) {
10015 if (Cand->Viable && !Cand->Best &&
10016 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10017 PendingBest.push_back(Cand);
10018 Cand->Best = true;
10019
10020 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10021 Curr->Function))
10022 EquivalentCands.push_back(Cand->Function);
10023 else
10024 Best = end();
10025 }
10026 }
10027 }
10028
10029 // If we found more than one best candidate, this is ambiguous.
10030 if (Best == end())
9
Assuming the condition is false
10
Taking false branch
10031 return OR_Ambiguous;
10032
10033 // Best is the best viable function.
10034 if (Best->Function && Best->Function->isDeleted())
11
Assuming field 'Function' is null
10035 return OR_Deleted;
10036
10037 if (!EquivalentCands.empty())
12
Calling 'SmallVectorBase::empty'
15
Returning from 'SmallVectorBase::empty'
16
Taking true branch
10038 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
17
Passing null pointer value via 2nd parameter 'D'
18
Calling 'Sema::diagnoseEquivalentInternalLinkageDeclarations'
10039 EquivalentCands);
10040
10041 return OR_Success;
10042}
10043
10044namespace {
10045
10046enum OverloadCandidateKind {
10047 oc_function,
10048 oc_method,
10049 oc_reversed_binary_operator,
10050 oc_constructor,
10051 oc_implicit_default_constructor,
10052 oc_implicit_copy_constructor,
10053 oc_implicit_move_constructor,
10054 oc_implicit_copy_assignment,
10055 oc_implicit_move_assignment,
10056 oc_implicit_equality_comparison,
10057 oc_inherited_constructor
10058};
10059
10060enum OverloadCandidateSelect {
10061 ocs_non_template,
10062 ocs_template,
10063 ocs_described_template,
10064};
10065
10066static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10067ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10068 OverloadCandidateRewriteKind CRK,
10069 std::string &Description) {
10070
10071 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10072 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10073 isTemplate = true;
10074 Description = S.getTemplateArgumentBindingsText(
10075 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10076 }
10077
10078 OverloadCandidateSelect Select = [&]() {
10079 if (!Description.empty())
10080 return ocs_described_template;
10081 return isTemplate ? ocs_template : ocs_non_template;
10082 }();
10083
10084 OverloadCandidateKind Kind = [&]() {
10085 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10086 return oc_implicit_equality_comparison;
10087
10088 if (CRK & CRK_Reversed)
10089 return oc_reversed_binary_operator;
10090
10091 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10092 if (!Ctor->isImplicit()) {
10093 if (isa<ConstructorUsingShadowDecl>(Found))
10094 return oc_inherited_constructor;
10095 else
10096 return oc_constructor;
10097 }
10098
10099 if (Ctor->isDefaultConstructor())
10100 return oc_implicit_default_constructor;
10101
10102 if (Ctor->isMoveConstructor())
10103 return oc_implicit_move_constructor;
10104
10105 assert(Ctor->isCopyConstructor() &&((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10106, __PRETTY_FUNCTION__))
10106 "unexpected sort of implicit constructor")((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10106, __PRETTY_FUNCTION__))
;
10107 return oc_implicit_copy_constructor;
10108 }
10109
10110 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10111 // This actually gets spelled 'candidate function' for now, but
10112 // it doesn't hurt to split it out.
10113 if (!Meth->isImplicit())
10114 return oc_method;
10115
10116 if (Meth->isMoveAssignmentOperator())
10117 return oc_implicit_move_assignment;
10118
10119 if (Meth->isCopyAssignmentOperator())
10120 return oc_implicit_copy_assignment;
10121
10122 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")((isa<CXXConversionDecl>(Meth) && "expected conversion"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10122, __PRETTY_FUNCTION__))
;
10123 return oc_method;
10124 }
10125
10126 return oc_function;
10127 }();
10128
10129 return std::make_pair(Kind, Select);
10130}
10131
10132void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10133 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10134 // set.
10135 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10136 S.Diag(FoundDecl->getLocation(),
10137 diag::note_ovl_candidate_inherited_constructor)
10138 << Shadow->getNominatedBaseClass();
10139}
10140
10141} // end anonymous namespace
10142
10143static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10144 const FunctionDecl *FD) {
10145 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10146 bool AlwaysTrue;
10147 if (EnableIf->getCond()->isValueDependent() ||
10148 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10149 return false;
10150 if (!AlwaysTrue)
10151 return false;
10152 }
10153 return true;
10154}
10155
10156/// Returns true if we can take the address of the function.
10157///
10158/// \param Complain - If true, we'll emit a diagnostic
10159/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10160/// we in overload resolution?
10161/// \param Loc - The location of the statement we're complaining about. Ignored
10162/// if we're not complaining, or if we're in overload resolution.
10163static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10164 bool Complain,
10165 bool InOverloadResolution,
10166 SourceLocation Loc) {
10167 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10168 if (Complain) {
10169 if (InOverloadResolution)
10170 S.Diag(FD->getBeginLoc(),
10171 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10172 else
10173 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10174 }
10175 return false;
10176 }
10177
10178 if (FD->getTrailingRequiresClause()) {
10179 ConstraintSatisfaction Satisfaction;
10180 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10181 return false;
10182 if (!Satisfaction.IsSatisfied) {
10183 if (Complain) {
10184 if (InOverloadResolution)
10185 S.Diag(FD->getBeginLoc(),
10186 diag::note_ovl_candidate_unsatisfied_constraints);
10187 else
10188 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10189 << FD;
10190 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10191 }
10192 return false;
10193 }
10194 }
10195
10196 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10197 return P->hasAttr<PassObjectSizeAttr>();
10198 });
10199 if (I == FD->param_end())
10200 return true;
10201
10202 if (Complain) {
10203 // Add one to ParamNo because it's user-facing
10204 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10205 if (InOverloadResolution)
10206 S.Diag(FD->getLocation(),
10207 diag::note_ovl_candidate_has_pass_object_size_params)
10208 << ParamNo;
10209 else
10210 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10211 << FD << ParamNo;
10212 }
10213 return false;
10214}
10215
10216static bool checkAddressOfCandidateIsAvailable(Sema &S,
10217 const FunctionDecl *FD) {
10218 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10219 /*InOverloadResolution=*/true,
10220 /*Loc=*/SourceLocation());
10221}
10222
10223bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10224 bool Complain,
10225 SourceLocation Loc) {
10226 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10227 /*InOverloadResolution=*/false,
10228 Loc);
10229}
10230
10231// Don't print candidates other than the one that matches the calling
10232// convention of the call operator, since that is guaranteed to exist.
10233static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10234 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10235
10236 if (!ConvD)
10237 return false;
10238 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10239 if (!RD->isLambda())
10240 return false;
10241
10242 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10243 CallingConv CallOpCC =
10244 CallOp->getType()->getAs<FunctionType>()->getCallConv();
10245 QualType ConvRTy = ConvD->getType()->getAs<FunctionType>()->getReturnType();
10246 CallingConv ConvToCC =
10247 ConvRTy->getPointeeType()->getAs<FunctionType>()->getCallConv();
10248
10249 return ConvToCC != CallOpCC;
10250}
10251
10252// Notes the location of an overload candidate.
10253void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10254 OverloadCandidateRewriteKind RewriteKind,
10255 QualType DestType, bool TakingAddress) {
10256 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10257 return;
10258 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10259 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10260 return;
10261 if (shouldSkipNotingLambdaConversionDecl(Fn))
10262 return;
10263
10264 std::string FnDesc;
10265 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10266 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10267 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10268 << (unsigned)KSPair.first << (unsigned)KSPair.second
10269 << Fn << FnDesc;
10270
10271 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10272 Diag(Fn->getLocation(), PD);
10273 MaybeEmitInheritedConstructorNote(*this, Found);
10274}
10275
10276static void
10277MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10278 // Perhaps the ambiguity was caused by two atomic constraints that are
10279 // 'identical' but not equivalent:
10280 //
10281 // void foo() requires (sizeof(T) > 4) { } // #1
10282 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10283 //
10284 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10285 // #2 to subsume #1, but these constraint are not considered equivalent
10286 // according to the subsumption rules because they are not the same
10287 // source-level construct. This behavior is quite confusing and we should try
10288 // to help the user figure out what happened.
10289
10290 SmallVector<const Expr *, 3> FirstAC, SecondAC;
10291 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10292 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10293 if (!I->Function)
10294 continue;
10295 SmallVector<const Expr *, 3> AC;
10296 if (auto *Template = I->Function->getPrimaryTemplate())
10297 Template->getAssociatedConstraints(AC);
10298 else
10299 I->Function->getAssociatedConstraints(AC);
10300 if (AC.empty())
10301 continue;
10302 if (FirstCand == nullptr) {
10303 FirstCand = I->Function;
10304 FirstAC = AC;
10305 } else if (SecondCand == nullptr) {
10306 SecondCand = I->Function;
10307 SecondAC = AC;
10308 } else {
10309 // We have more than one pair of constrained functions - this check is
10310 // expensive and we'd rather not try to diagnose it.
10311 return;
10312 }
10313 }
10314 if (!SecondCand)
10315 return;
10316 // The diagnostic can only happen if there are associated constraints on
10317 // both sides (there needs to be some identical atomic constraint).
10318 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10319 SecondCand, SecondAC))
10320 // Just show the user one diagnostic, they'll probably figure it out
10321 // from here.
10322 return;
10323}
10324
10325// Notes the location of all overload candidates designated through
10326// OverloadedExpr
10327void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10328 bool TakingAddress) {
10329 assert(OverloadedExpr->getType() == Context.OverloadTy)((OverloadedExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10329, __PRETTY_FUNCTION__))
;
10330
10331 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10332 OverloadExpr *OvlExpr = Ovl.Expression;
10333
10334 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10335 IEnd = OvlExpr->decls_end();
10336 I != IEnd; ++I) {
10337 if (FunctionTemplateDecl *FunTmpl =
10338 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10339 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10340 TakingAddress);
10341 } else if (FunctionDecl *Fun
10342 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10343 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10344 }
10345 }
10346}
10347
10348/// Diagnoses an ambiguous conversion. The partial diagnostic is the
10349/// "lead" diagnostic; it will be given two arguments, the source and
10350/// target types of the conversion.
10351void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10352 Sema &S,
10353 SourceLocation CaretLoc,
10354 const PartialDiagnostic &PDiag) const {
10355 S.Diag(CaretLoc, PDiag)
10356 << Ambiguous.getFromType() << Ambiguous.getToType();
10357 // FIXME: The note limiting machinery is borrowed from
10358 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10359 // refactoring here.
10360 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10361 unsigned CandsShown = 0;
10362 AmbiguousConversionSequence::const_iterator I, E;
10363 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10364 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10365 break;
10366 ++CandsShown;
10367 S.NoteOverloadCandidate(I->first, I->second);
10368 }
10369 if (I != E)
10370 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10371}
10372
10373static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10374 unsigned I, bool TakingCandidateAddress) {
10375 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10376 assert(Conv.isBad())((Conv.isBad()) ? static_cast<void> (0) : __assert_fail
("Conv.isBad()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10376, __PRETTY_FUNCTION__))
;
10377 assert(Cand->Function && "for now, candidate must be a function")((Cand->Function && "for now, candidate must be a function"
) ? static_cast<void> (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10377, __PRETTY_FUNCTION__))
;
10378 FunctionDecl *Fn = Cand->Function;
10379
10380 // There's a conversion slot for the object argument if this is a
10381 // non-constructor method. Note that 'I' corresponds the
10382 // conversion-slot index.
10383 bool isObjectArgument = false;
10384 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10385 if (I == 0)
10386 isObjectArgument = true;
10387 else
10388 I--;
10389 }
10390
10391 std::string FnDesc;
10392 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10393 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10394 FnDesc);
10395
10396 Expr *FromExpr = Conv.Bad.FromExpr;
10397 QualType FromTy = Conv.Bad.getFromType();
10398 QualType ToTy = Conv.Bad.getToType();
10399
10400 if (FromTy == S.Context.OverloadTy) {
10401 assert(FromExpr && "overload set argument came from implicit argument?")((FromExpr && "overload set argument came from implicit argument?"
) ? static_cast<void> (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10401, __PRETTY_FUNCTION__))
;
10402 Expr *E = FromExpr->IgnoreParens();
10403 if (isa<UnaryOperator>(E))
10404 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10405 DeclarationName Name = cast<OverloadExpr>(E)->getName();
10406
10407 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10408 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10409 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10410 << Name << I + 1;
10411 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10412 return;
10413 }
10414
10415 // Do some hand-waving analysis to see if the non-viability is due
10416 // to a qualifier mismatch.
10417 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10418 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10419 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10420 CToTy = RT->getPointeeType();
10421 else {
10422 // TODO: detect and diagnose the full richness of const mismatches.
10423 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10424 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10425 CFromTy = FromPT->getPointeeType();
10426 CToTy = ToPT->getPointeeType();
10427 }
10428 }
10429
10430 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10431 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10432 Qualifiers FromQs = CFromTy.getQualifiers();
10433 Qualifiers ToQs = CToTy.getQualifiers();
10434
10435 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10436 if (isObjectArgument)
10437 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10438 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10439 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10440 << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10441 else
10442 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10443 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10444 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10445 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10446 << ToTy->isReferenceType() << I + 1;
10447 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10448 return;
10449 }
10450
10451 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10452 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10453 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10454 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10455 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10456 << (unsigned)isObjectArgument << I + 1;
10457 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10458 return;
10459 }
10460
10461 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10462 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10463 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10464 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10465 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10466 << (unsigned)isObjectArgument << I + 1;
10467 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10468 return;
10469 }
10470
10471 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10472 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10473 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10474 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10475 << FromQs.hasUnaligned() << I + 1;
10476 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10477 return;
10478 }
10479
10480 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10481 assert(CVR && "expected qualifiers mismatch")((CVR && "expected qualifiers mismatch") ? static_cast
<void> (0) : __assert_fail ("CVR && \"expected qualifiers mismatch\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10481, __PRETTY_FUNCTION__))
;
10482
10483 if (isObjectArgument) {
10484 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10485 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10486 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10487 << (CVR - 1);
10488 } else {
10489 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10490 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10491 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10492 << (CVR - 1) << I + 1;
10493 }
10494 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10495 return;
10496 }
10497
10498 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10499 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10500 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10501 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10502 << (unsigned)isObjectArgument << I + 1
10503 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10504 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10505 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10506 return;
10507 }
10508
10509 // Special diagnostic for failure to convert an initializer list, since
10510 // telling the user that it has type void is not useful.
10511 if (FromExpr && isa<InitListExpr>(FromExpr)) {
10512 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10513 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10514 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10515 << ToTy << (unsigned)isObjectArgument << I + 1;
10516 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10517 return;
10518 }
10519
10520 // Diagnose references or pointers to incomplete types differently,
10521 // since it's far from impossible that the incompleteness triggered
10522 // the failure.
10523 QualType TempFromTy = FromTy.getNonReferenceType();
10524 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10525 TempFromTy = PTy->getPointeeType();
10526 if (TempFromTy->isIncompleteType()) {
10527 // Emit the generic diagnostic and, optionally, add the hints to it.
10528 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10529 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10530 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10531 << ToTy << (unsigned)isObjectArgument << I + 1
10532 << (unsigned)(Cand->Fix.Kind);
10533
10534 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10535 return;
10536 }
10537
10538 // Diagnose base -> derived pointer conversions.
10539 unsigned BaseToDerivedConversion = 0;
10540 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10541 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10542 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10543 FromPtrTy->getPointeeType()) &&
10544 !FromPtrTy->getPointeeType()->isIncompleteType() &&
10545 !ToPtrTy->getPointeeType()->isIncompleteType() &&
10546 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10547 FromPtrTy->getPointeeType()))
10548 BaseToDerivedConversion = 1;
10549 }
10550 } else if (const ObjCObjectPointerType *FromPtrTy
10551 = FromTy->getAs<ObjCObjectPointerType>()) {
10552 if (const ObjCObjectPointerType *ToPtrTy
10553 = ToTy->getAs<ObjCObjectPointerType>())
10554 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10555 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10556 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10557 FromPtrTy->getPointeeType()) &&
10558 FromIface->isSuperClassOf(ToIface))
10559 BaseToDerivedConversion = 2;
10560 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10561 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10562 !FromTy->isIncompleteType() &&
10563 !ToRefTy->getPointeeType()->isIncompleteType() &&
10564 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10565 BaseToDerivedConversion = 3;
10566 }
10567 }
10568
10569 if (BaseToDerivedConversion) {
10570 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10571 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10572 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10573 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10574 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10575 return;
10576 }
10577
10578 if (isa<ObjCObjectPointerType>(CFromTy) &&
10579 isa<PointerType>(CToTy)) {
10580 Qualifiers FromQs = CFromTy.getQualifiers();
10581 Qualifiers ToQs = CToTy.getQualifiers();
10582 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10583 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10584 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10585 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10586 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10587 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10588 return;
10589 }
10590 }
10591
10592 if (TakingCandidateAddress &&
10593 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10594 return;
10595
10596 // Emit the generic diagnostic and, optionally, add the hints to it.
10597 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10598 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10599 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10600 << ToTy << (unsigned)isObjectArgument << I + 1
10601 << (unsigned)(Cand->Fix.Kind);
10602
10603 // If we can fix the conversion, suggest the FixIts.
10604 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10605 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10606 FDiag << *HI;
10607 S.Diag(Fn->getLocation(), FDiag);
10608
10609 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10610}
10611
10612/// Additional arity mismatch diagnosis specific to a function overload
10613/// candidates. This is not covered by the more general DiagnoseArityMismatch()
10614/// over a candidate in any candidate set.
10615static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10616 unsigned NumArgs) {
10617 FunctionDecl *Fn = Cand->Function;
10618 unsigned MinParams = Fn->getMinRequiredArguments();
10619
10620 // With invalid overloaded operators, it's possible that we think we
10621 // have an arity mismatch when in fact it looks like we have the
10622 // right number of arguments, because only overloaded operators have
10623 // the weird behavior of overloading member and non-member functions.
10624 // Just don't report anything.
10625 if (Fn->isInvalidDecl() &&
10626 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10627 return true;
10628
10629 if (NumArgs < MinParams) {
10630 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10632, __PRETTY_FUNCTION__))
10631 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10632, __PRETTY_FUNCTION__))
10632 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10632, __PRETTY_FUNCTION__))
;
10633 } else {
10634 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10636, __PRETTY_FUNCTION__))
10635 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10636, __PRETTY_FUNCTION__))
10636 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10636, __PRETTY_FUNCTION__))
;
10637 }
10638
10639 return false;
10640}
10641
10642/// General arity mismatch diagnosis over a candidate in a candidate set.
10643static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10644 unsigned NumFormalArgs) {
10645 assert(isa<FunctionDecl>(D) &&((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10648, __PRETTY_FUNCTION__))
10646 "The templated declaration should at least be a function"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10648, __PRETTY_FUNCTION__))
10647 " when diagnosing bad template argument deduction due to too many"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10648, __PRETTY_FUNCTION__))
10648 " or too few arguments")((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10648, __PRETTY_FUNCTION__))
;
10649
10650 FunctionDecl *Fn = cast<FunctionDecl>(D);
10651
10652 // TODO: treat calls to a missing default constructor as a special case
10653 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10654 unsigned MinParams = Fn->getMinRequiredArguments();
10655
10656 // at least / at most / exactly
10657 unsigned mode, modeCount;
10658 if (NumFormalArgs < MinParams) {
10659 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10660 FnTy->isTemplateVariadic())
10661 mode = 0; // "at least"
10662 else
10663 mode = 2; // "exactly"
10664 modeCount = MinParams;
10665 } else {
10666 if (MinParams != FnTy->getNumParams())
10667 mode = 1; // "at most"
10668 else
10669 mode = 2; // "exactly"
10670 modeCount = FnTy->getNumParams();
10671 }
10672
10673 std::string Description;
10674 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10675 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10676
10677 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10678 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10679 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10680 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10681 else
10682 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10683 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10684 << Description << mode << modeCount << NumFormalArgs;
10685
10686 MaybeEmitInheritedConstructorNote(S, Found);
10687}
10688
10689/// Arity mismatch diagnosis specific to a function overload candidate.
10690static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10691 unsigned NumFormalArgs) {
10692 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10693 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10694}
10695
10696static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10697 if (TemplateDecl *TD = Templated->getDescribedTemplate())
10698 return TD;
10699 llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10700)
10700 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10700)
;
10701}
10702
10703/// Diagnose a failed template-argument deduction.
10704static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10705 DeductionFailureInfo &DeductionFailure,
10706 unsigned NumArgs,
10707 bool TakingCandidateAddress) {
10708 TemplateParameter Param = DeductionFailure.getTemplateParameter();
10709 NamedDecl *ParamD;
10710 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10711 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10712 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10713 switch (DeductionFailure.Result) {
10714 case Sema::TDK_Success:
10715 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10715)
;
10716
10717 case Sema::TDK_Incomplete: {
10718 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10718, __PRETTY_FUNCTION__))
;
10719 S.Diag(Templated->getLocation(),
10720 diag::note_ovl_candidate_incomplete_deduction)
10721 << ParamD->getDeclName();
10722 MaybeEmitInheritedConstructorNote(S, Found);
10723 return;
10724 }
10725
10726 case Sema::TDK_IncompletePack: {
10727 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10727, __PRETTY_FUNCTION__))
;
10728 S.Diag(Templated->getLocation(),
10729 diag::note_ovl_candidate_incomplete_deduction_pack)
10730 << ParamD->getDeclName()
10731 << (DeductionFailure.getFirstArg()->pack_size() + 1)
10732 << *DeductionFailure.getFirstArg();
10733 MaybeEmitInheritedConstructorNote(S, Found);
10734 return;
10735 }
10736
10737 case Sema::TDK_Underqualified: {
10738 assert(ParamD && "no parameter found for bad qualifiers deduction result")((ParamD && "no parameter found for bad qualifiers deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10738, __PRETTY_FUNCTION__))
;
10739 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10740
10741 QualType Param = DeductionFailure.getFirstArg()->getAsType();
10742
10743 // Param will have been canonicalized, but it should just be a
10744 // qualified version of ParamD, so move the qualifiers to that.
10745 QualifierCollector Qs;
10746 Qs.strip(Param);
10747 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10748 assert(S.Context.hasSameType(Param, NonCanonParam))((S.Context.hasSameType(Param, NonCanonParam)) ? static_cast<
void> (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10748, __PRETTY_FUNCTION__))
;
10749
10750 // Arg has also been canonicalized, but there's nothing we can do
10751 // about that. It also doesn't matter as much, because it won't
10752 // have any template parameters in it (because deduction isn't
10753 // done on dependent types).
10754 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10755
10756 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10757 << ParamD->getDeclName() << Arg << NonCanonParam;
10758 MaybeEmitInheritedConstructorNote(S, Found);
10759 return;
10760 }
10761
10762 case Sema::TDK_Inconsistent: {
10763 assert(ParamD && "no parameter found for inconsistent deduction result")((ParamD && "no parameter found for inconsistent deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10763, __PRETTY_FUNCTION__))
;
10764 int which = 0;
10765 if (isa<TemplateTypeParmDecl>(ParamD))
10766 which = 0;
10767 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10768 // Deduction might have failed because we deduced arguments of two
10769 // different types for a non-type template parameter.
10770 // FIXME: Use a different TDK value for this.
10771 QualType T1 =
10772 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10773 QualType T2 =
10774 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10775 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10776 S.Diag(Templated->getLocation(),
10777 diag::note_ovl_candidate_inconsistent_deduction_types)
10778 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10779 << *DeductionFailure.getSecondArg() << T2;
10780 MaybeEmitInheritedConstructorNote(S, Found);
10781 return;
10782 }
10783
10784 which = 1;
10785 } else {
10786 which = 2;
10787 }
10788
10789 // Tweak the diagnostic if the problem is that we deduced packs of
10790 // different arities. We'll print the actual packs anyway in case that
10791 // includes additional useful information.
10792 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10793 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10794 DeductionFailure.getFirstArg()->pack_size() !=
10795 DeductionFailure.getSecondArg()->pack_size()) {
10796 which = 3;
10797 }
10798
10799 S.Diag(Templated->getLocation(),
10800 diag::note_ovl_candidate_inconsistent_deduction)
10801 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10802 << *DeductionFailure.getSecondArg();
10803 MaybeEmitInheritedConstructorNote(S, Found);
10804 return;
10805 }
10806
10807 case Sema::TDK_InvalidExplicitArguments:
10808 assert(ParamD && "no parameter found for invalid explicit arguments")((ParamD && "no parameter found for invalid explicit arguments"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 10808, __PRETTY_FUNCTION__))
;
10809 if (ParamD->getDeclName())
10810 S.Diag(Templated->getLocation(),
10811 diag::note_ovl_candidate_explicit_arg_mismatch_named)
10812 << ParamD->getDeclName();
10813 else {
10814 int index = 0;
10815 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10816 index = TTP->getIndex();
10817 else if (NonTypeTemplateParmDecl *NTTP
10818 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10819 index = NTTP->getIndex();
10820 else
10821 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10822 S.Diag(Templated->getLocation(),
10823 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10824 << (index + 1);
10825 }
10826 MaybeEmitInheritedConstructorNote(S, Found);
10827 return;
10828
10829 case Sema::TDK_ConstraintsNotSatisfied: {
10830 // Format the template argument list into the argument string.
10831 SmallString<128> TemplateArgString;
10832 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10833 TemplateArgString = " ";
10834 TemplateArgString += S.getTemplateArgumentBindingsText(
10835 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10836 if (TemplateArgString.size() == 1)
10837 TemplateArgString.clear();
10838 S.Diag(Templated->getLocation(),
10839 diag::note_ovl_candidate_unsatisfied_constraints)
10840 << TemplateArgString;
10841
10842 S.DiagnoseUnsatisfiedConstraint(
10843 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10844 return;
10845 }
10846 case Sema::TDK_TooManyArguments:
10847 case Sema::TDK_TooFewArguments:
10848 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10849 return;
10850
10851 case Sema::TDK_InstantiationDepth:
10852 S.Diag(Templated->getLocation(),
10853 diag::note_ovl_candidate_instantiation_depth);
10854 MaybeEmitInheritedConstructorNote(S, Found);
10855 return;
10856
10857 case Sema::TDK_SubstitutionFailure: {
10858 // Format the template argument list into the argument string.
10859 SmallString<128> TemplateArgString;
10860 if (TemplateArgumentList *Args =
10861 DeductionFailure.getTemplateArgumentList()) {
10862 TemplateArgString = " ";
10863 TemplateArgString += S.getTemplateArgumentBindingsText(
10864 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10865 if (TemplateArgString.size() == 1)
10866 TemplateArgString.clear();
10867 }
10868
10869 // If this candidate was disabled by enable_if, say so.
10870 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10871 if (PDiag && PDiag->second.getDiagID() ==
10872 diag::err_typename_nested_not_found_enable_if) {
10873 // FIXME: Use the source range of the condition, and the fully-qualified
10874 // name of the enable_if template. These are both present in PDiag.
10875 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10876 << "'enable_if'" << TemplateArgString;
10877 return;
10878 }
10879
10880 // We found a specific requirement that disabled the enable_if.
10881 if (PDiag && PDiag->second.getDiagID() ==
10882 diag::err_typename_nested_not_found_requirement) {
10883 S.Diag(Templated->getLocation(),
10884 diag::note_ovl_candidate_disabled_by_requirement)
10885 << PDiag->second.getStringArg(0) << TemplateArgString;
10886 return;
10887 }
10888
10889 // Format the SFINAE diagnostic into the argument string.
10890 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10891 // formatted message in another diagnostic.
10892 SmallString<128> SFINAEArgString;
10893 SourceRange R;
10894 if (PDiag) {
10895 SFINAEArgString = ": ";
10896 R = SourceRange(PDiag->first, PDiag->first);
10897 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10898 }
10899
10900 S.Diag(Templated->getLocation(),
10901 diag::note_ovl_candidate_substitution_failure)
10902 << TemplateArgString << SFINAEArgString << R;
10903 MaybeEmitInheritedConstructorNote(S, Found);
10904 return;
10905 }
10906
10907 case Sema::TDK_DeducedMismatch:
10908 case Sema::TDK_DeducedMismatchNested: {
10909 // Format the template argument list into the argument string.
10910 SmallString<128> TemplateArgString;
10911 if (TemplateArgumentList *Args =
10912 DeductionFailure.getTemplateArgumentList()) {
10913 TemplateArgString = " ";
10914 TemplateArgString += S.getTemplateArgumentBindingsText(
10915 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10916 if (TemplateArgString.size() == 1)
10917 TemplateArgString.clear();
10918 }
10919
10920 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10921 << (*DeductionFailure.getCallArgIndex() + 1)
10922 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10923 << TemplateArgString
10924 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10925 break;
10926 }
10927
10928 case Sema::TDK_NonDeducedMismatch: {
10929 // FIXME: Provide a source location to indicate what we couldn't match.
10930 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10931 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10932 if (FirstTA.getKind() == TemplateArgument::Template &&
10933 SecondTA.getKind() == TemplateArgument::Template) {
10934 TemplateName FirstTN = FirstTA.getAsTemplate();
10935 TemplateName SecondTN = SecondTA.getAsTemplate();
10936 if (FirstTN.getKind() == TemplateName::Template &&
10937 SecondTN.getKind() == TemplateName::Template) {
10938 if (FirstTN.getAsTemplateDecl()->getName() ==
10939 SecondTN.getAsTemplateDecl()->getName()) {
10940 // FIXME: This fixes a bad diagnostic where both templates are named
10941 // the same. This particular case is a bit difficult since:
10942 // 1) It is passed as a string to the diagnostic printer.
10943 // 2) The diagnostic printer only attempts to find a better
10944 // name for types, not decls.
10945 // Ideally, this should folded into the diagnostic printer.
10946 S.Diag(Templated->getLocation(),
10947 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10948 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10949 return;
10950 }
10951 }
10952 }
10953
10954 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10955 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10956 return;
10957
10958 // FIXME: For generic lambda parameters, check if the function is a lambda
10959 // call operator, and if so, emit a prettier and more informative
10960 // diagnostic that mentions 'auto' and lambda in addition to
10961 // (or instead of?) the canonical template type parameters.
10962 S.Diag(Templated->getLocation(),
10963 diag::note_ovl_candidate_non_deduced_mismatch)
10964 << FirstTA << SecondTA;
10965 return;
10966 }
10967 // TODO: diagnose these individually, then kill off
10968 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10969 case Sema::TDK_MiscellaneousDeductionFailure:
10970 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10971 MaybeEmitInheritedConstructorNote(S, Found);
10972 return;
10973 case Sema::TDK_CUDATargetMismatch:
10974 S.Diag(Templated->getLocation(),
10975 diag::note_cuda_ovl_candidate_target_mismatch);
10976 return;
10977 }
10978}
10979
10980/// Diagnose a failed template-argument deduction, for function calls.
10981static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10982 unsigned NumArgs,
10983 bool TakingCandidateAddress) {
10984 unsigned TDK = Cand->DeductionFailure.Result;
10985 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10986 if (CheckArityMismatch(S, Cand, NumArgs))
10987 return;
10988 }
10989 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10990 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10991}
10992
10993/// CUDA: diagnose an invalid call across targets.
10994static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10995 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10996 FunctionDecl *Callee = Cand->Function;
10997
10998 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10999 CalleeTarget = S.IdentifyCUDATarget(Callee);
11000
11001 std::string FnDesc;
11002 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11003 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11004 Cand->getRewriteKind(), FnDesc);
11005
11006 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11007 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11008 << FnDesc /* Ignored */
11009 << CalleeTarget << CallerTarget;
11010
11011 // This could be an implicit constructor for which we could not infer the
11012 // target due to a collsion. Diagnose that case.
11013 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11014 if (Meth != nullptr && Meth->isImplicit()) {
11015 CXXRecordDecl *ParentClass = Meth->getParent();
11016 Sema::CXXSpecialMember CSM;
11017
11018 switch (FnKindPair.first) {
11019 default:
11020 return;
11021 case oc_implicit_default_constructor:
11022 CSM = Sema::CXXDefaultConstructor;
11023 break;
11024 case oc_implicit_copy_constructor:
11025 CSM = Sema::CXXCopyConstructor;
11026 break;
11027 case oc_implicit_move_constructor:
11028 CSM = Sema::CXXMoveConstructor;
11029 break;
11030 case oc_implicit_copy_assignment:
11031 CSM = Sema::CXXCopyAssignment;
11032 break;
11033 case oc_implicit_move_assignment:
11034 CSM = Sema::CXXMoveAssignment;
11035 break;
11036 };
11037
11038 bool ConstRHS = false;
11039 if (Meth->getNumParams()) {
11040 if (const ReferenceType *RT =
11041 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11042 ConstRHS = RT->getPointeeType().isConstQualified();
11043 }
11044 }
11045
11046 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11047 /* ConstRHS */ ConstRHS,
11048 /* Diagnose */ true);
11049 }
11050}
11051
11052static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11053 FunctionDecl *Callee = Cand->Function;
11054 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11055
11056 S.Diag(Callee->getLocation(),
11057 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11058 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11059}
11060
11061static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11062 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11063 assert(ES.isExplicit() && "not an explicit candidate")((ES.isExplicit() && "not an explicit candidate") ? static_cast
<void> (0) : __assert_fail ("ES.isExplicit() && \"not an explicit candidate\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11063, __PRETTY_FUNCTION__))
;
11064
11065 unsigned Kind;
11066 switch (Cand->Function->getDeclKind()) {
11067 case Decl::Kind::CXXConstructor:
11068 Kind = 0;
11069 break;
11070 case Decl::Kind::CXXConversion:
11071 Kind = 1;
11072 break;
11073 case Decl::Kind::CXXDeductionGuide:
11074 Kind = Cand->Function->isImplicit() ? 0 : 2;
11075 break;
11076 default:
11077 llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11077)
;
11078 }
11079
11080 // Note the location of the first (in-class) declaration; a redeclaration
11081 // (particularly an out-of-class definition) will typically lack the
11082 // 'explicit' specifier.
11083 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11084 FunctionDecl *First = Cand->Function->getFirstDecl();
11085 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11086 First = Pattern->getFirstDecl();
11087
11088 S.Diag(First->getLocation(),
11089 diag::note_ovl_candidate_explicit)
11090 << Kind << (ES.getExpr() ? 1 : 0)
11091 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11092}
11093
11094static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
11095 FunctionDecl *Callee = Cand->Function;
11096
11097 S.Diag(Callee->getLocation(),
11098 diag::note_ovl_candidate_disabled_by_extension)
11099 << S.getOpenCLExtensionsFromDeclExtMap(Callee);
11100}
11101
11102/// Generates a 'note' diagnostic for an overload candidate. We've
11103/// already generated a primary error at the call site.
11104///
11105/// It really does need to be a single diagnostic with its caret
11106/// pointed at the candidate declaration. Yes, this creates some
11107/// major challenges of technical writing. Yes, this makes pointing
11108/// out problems with specific arguments quite awkward. It's still
11109/// better than generating twenty screens of text for every failed
11110/// overload.
11111///
11112/// It would be great to be able to express per-candidate problems
11113/// more richly for those diagnostic clients that cared, but we'd
11114/// still have to be just as careful with the default diagnostics.
11115/// \param CtorDestAS Addr space of object being constructed (for ctor
11116/// candidates only).
11117static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11118 unsigned NumArgs,
11119 bool TakingCandidateAddress,
11120 LangAS CtorDestAS = LangAS::Default) {
11121 FunctionDecl *Fn = Cand->Function;
11122 if (shouldSkipNotingLambdaConversionDecl(Fn))
11123 return;
11124
11125 // Note deleted candidates, but only if they're viable.
11126 if (Cand->Viable) {
11127 if (Fn->isDeleted()) {
11128 std::string FnDesc;
11129 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11130 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11131 Cand->getRewriteKind(), FnDesc);
11132
11133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11134 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11135 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11136 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11137 return;
11138 }
11139
11140 // We don't really have anything else to say about viable candidates.
11141 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11142 return;
11143 }
11144
11145 switch (Cand->FailureKind) {
11146 case ovl_fail_too_many_arguments:
11147 case ovl_fail_too_few_arguments:
11148 return DiagnoseArityMismatch(S, Cand, NumArgs);
11149
11150 case ovl_fail_bad_deduction:
11151 return DiagnoseBadDeduction(S, Cand, NumArgs,
11152 TakingCandidateAddress);
11153
11154 case ovl_fail_illegal_constructor: {
11155 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11156 << (Fn->getPrimaryTemplate() ? 1 : 0);
11157 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11158 return;
11159 }
11160
11161 case ovl_fail_object_addrspace_mismatch: {
11162 Qualifiers QualsForPrinting;
11163 QualsForPrinting.setAddressSpace(CtorDestAS);
11164 S.Diag(Fn->getLocation(),
11165 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11166 << QualsForPrinting;
11167 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11168 return;
11169 }
11170
11171 case ovl_fail_trivial_conversion:
11172 case ovl_fail_bad_final_conversion:
11173 case ovl_fail_final_conversion_not_exact:
11174 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11175
11176 case ovl_fail_bad_conversion: {
11177 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11178 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11179 if (Cand->Conversions[I].isBad())
11180 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11181
11182 // FIXME: this currently happens when we're called from SemaInit
11183 // when user-conversion overload fails. Figure out how to handle
11184 // those conditions and diagnose them well.
11185 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11186 }
11187
11188 case ovl_fail_bad_target:
11189 return DiagnoseBadTarget(S, Cand);
11190
11191 case ovl_fail_enable_if:
11192 return DiagnoseFailedEnableIfAttr(S, Cand);
11193
11194 case ovl_fail_explicit:
11195 return DiagnoseFailedExplicitSpec(S, Cand);
11196
11197 case ovl_fail_ext_disabled:
11198 return DiagnoseOpenCLExtensionDisabled(S, Cand);
11199
11200 case ovl_fail_inhctor_slice:
11201 // It's generally not interesting to note copy/move constructors here.
11202 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11203 return;
11204 S.Diag(Fn->getLocation(),
11205 diag::note_ovl_candidate_inherited_constructor_slice)
11206 << (Fn->getPrimaryTemplate() ? 1 : 0)
11207 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11208 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11209 return;
11210
11211 case ovl_fail_addr_not_available: {
11212 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11213 (void)Available;
11214 assert(!Available)((!Available) ? static_cast<void> (0) : __assert_fail (
"!Available", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11214, __PRETTY_FUNCTION__))
;
11215 break;
11216 }
11217 case ovl_non_default_multiversion_function:
11218 // Do nothing, these should simply be ignored.
11219 break;
11220
11221 case ovl_fail_constraints_not_satisfied: {
11222 std::string FnDesc;
11223 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11224 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11225 Cand->getRewriteKind(), FnDesc);
11226
11227 S.Diag(Fn->getLocation(),
11228 diag::note_ovl_candidate_constraints_not_satisfied)
11229 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11230 << FnDesc /* Ignored */;
11231 ConstraintSatisfaction Satisfaction;
11232 if (S.CheckFunctionConstraints(Fn, Satisfaction))
11233 break;
11234 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11235 }
11236 }
11237}
11238
11239static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11240 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11241 return;
11242
11243 // Desugar the type of the surrogate down to a function type,
11244 // retaining as many typedefs as possible while still showing
11245 // the function type (and, therefore, its parameter types).
11246 QualType FnType = Cand->Surrogate->getConversionType();
11247 bool isLValueReference = false;
11248 bool isRValueReference = false;
11249 bool isPointer = false;
11250 if (const LValueReferenceType *FnTypeRef =
11251 FnType->getAs<LValueReferenceType>()) {
11252 FnType = FnTypeRef->getPointeeType();
11253 isLValueReference = true;
11254 } else if (const RValueReferenceType *FnTypeRef =
11255 FnType->getAs<RValueReferenceType>()) {
11256 FnType = FnTypeRef->getPointeeType();
11257 isRValueReference = true;
11258 }
11259 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11260 FnType = FnTypePtr->getPointeeType();
11261 isPointer = true;
11262 }
11263 // Desugar down to a function type.
11264 FnType = QualType(FnType->getAs<FunctionType>(), 0);
11265 // Reconstruct the pointer/reference as appropriate.
11266 if (isPointer) FnType = S.Context.getPointerType(FnType);
11267 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11268 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11269
11270 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11271 << FnType;
11272}
11273
11274static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11275 SourceLocation OpLoc,
11276 OverloadCandidate *Cand) {
11277 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")((Cand->Conversions.size() <= 2 && "builtin operator is not binary"
) ? static_cast<void> (0) : __assert_fail ("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11277, __PRETTY_FUNCTION__))
;
11278 std::string TypeStr("operator");
11279 TypeStr += Opc;
11280 TypeStr += "(";
11281 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11282 if (Cand->Conversions.size() == 1) {
11283 TypeStr += ")";
11284 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11285 } else {
11286 TypeStr += ", ";
11287 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11288 TypeStr += ")";
11289 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11290 }
11291}
11292
11293static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11294 OverloadCandidate *Cand) {
11295 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11296 if (ICS.isBad()) break; // all meaningless after first invalid
11297 if (!ICS.isAmbiguous()) continue;
11298
11299 ICS.DiagnoseAmbiguousConversion(
11300 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11301 }
11302}
11303
11304static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11305 if (Cand->Function)
11306 return Cand->Function->getLocation();
11307 if (Cand->IsSurrogate)
11308 return Cand->Surrogate->getLocation();
11309 return SourceLocation();
11310}
11311
11312static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11313 switch ((Sema::TemplateDeductionResult)DFI.Result) {
11314 case Sema::TDK_Success:
11315 case Sema::TDK_NonDependentConversionFailure:
11316 llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11316)
;
11317
11318 case Sema::TDK_Invalid:
11319 case Sema::TDK_Incomplete:
11320 case Sema::TDK_IncompletePack:
11321 return 1;
11322
11323 case Sema::TDK_Underqualified:
11324 case Sema::TDK_Inconsistent:
11325 return 2;
11326
11327 case Sema::TDK_SubstitutionFailure:
11328 case Sema::TDK_DeducedMismatch:
11329 case Sema::TDK_ConstraintsNotSatisfied:
11330 case Sema::TDK_DeducedMismatchNested:
11331 case Sema::TDK_NonDeducedMismatch:
11332 case Sema::TDK_MiscellaneousDeductionFailure:
11333 case Sema::TDK_CUDATargetMismatch:
11334 return 3;
11335
11336 case Sema::TDK_InstantiationDepth:
11337 return 4;
11338
11339 case Sema::TDK_InvalidExplicitArguments:
11340 return 5;
11341
11342 case Sema::TDK_TooManyArguments:
11343 case Sema::TDK_TooFewArguments:
11344 return 6;
11345 }
11346 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11346)
;
11347}
11348
11349namespace {
11350struct CompareOverloadCandidatesForDisplay {
11351 Sema &S;
11352 SourceLocation Loc;
11353 size_t NumArgs;
11354 OverloadCandidateSet::CandidateSetKind CSK;
11355
11356 CompareOverloadCandidatesForDisplay(
11357 Sema &S, SourceLocation Loc, size_t NArgs,
11358 OverloadCandidateSet::CandidateSetKind CSK)
11359 : S(S), NumArgs(NArgs), CSK(CSK) {}
11360
11361 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11362 // If there are too many or too few arguments, that's the high-order bit we
11363 // want to sort by, even if the immediate failure kind was something else.
11364 if (C->FailureKind == ovl_fail_too_many_arguments ||
11365 C->FailureKind == ovl_fail_too_few_arguments)
11366 return static_cast<OverloadFailureKind>(C->FailureKind);
11367
11368 if (C->Function) {
11369 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11370 return ovl_fail_too_many_arguments;
11371 if (NumArgs < C->Function->getMinRequiredArguments())
11372 return ovl_fail_too_few_arguments;
11373 }
11374
11375 return static_cast<OverloadFailureKind>(C->FailureKind);
11376 }
11377
11378 bool operator()(const OverloadCandidate *L,
11379 const OverloadCandidate *R) {
11380 // Fast-path this check.
11381 if (L == R) return false;
11382
11383 // Order first by viability.
11384 if (L->Viable) {
11385 if (!R->Viable) return true;
11386
11387 // TODO: introduce a tri-valued comparison for overload
11388 // candidates. Would be more worthwhile if we had a sort
11389 // that could exploit it.
11390 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11391 return true;
11392 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11393 return false;
11394 } else if (R->Viable)
11395 return false;
11396
11397 assert(L->Viable == R->Viable)((L->Viable == R->Viable) ? static_cast<void> (0)
: __assert_fail ("L->Viable == R->Viable", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11397, __PRETTY_FUNCTION__))
;
11398
11399 // Criteria by which we can sort non-viable candidates:
11400 if (!L->Viable) {
11401 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11402 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11403
11404 // 1. Arity mismatches come after other candidates.
11405 if (LFailureKind == ovl_fail_too_many_arguments ||
11406 LFailureKind == ovl_fail_too_few_arguments) {
11407 if (RFailureKind == ovl_fail_too_many_arguments ||
11408 RFailureKind == ovl_fail_too_few_arguments) {
11409 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11410 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11411 if (LDist == RDist) {
11412 if (LFailureKind == RFailureKind)
11413 // Sort non-surrogates before surrogates.
11414 return !L->IsSurrogate && R->IsSurrogate;
11415 // Sort candidates requiring fewer parameters than there were
11416 // arguments given after candidates requiring more parameters
11417 // than there were arguments given.
11418 return LFailureKind == ovl_fail_too_many_arguments;
11419 }
11420 return LDist < RDist;
11421 }
11422 return false;
11423 }
11424 if (RFailureKind == ovl_fail_too_many_arguments ||
11425 RFailureKind == ovl_fail_too_few_arguments)
11426 return true;
11427
11428 // 2. Bad conversions come first and are ordered by the number
11429 // of bad conversions and quality of good conversions.
11430 if (LFailureKind == ovl_fail_bad_conversion) {
11431 if (RFailureKind != ovl_fail_bad_conversion)
11432 return true;
11433
11434 // The conversion that can be fixed with a smaller number of changes,
11435 // comes first.
11436 unsigned numLFixes = L->Fix.NumConversionsFixed;
11437 unsigned numRFixes = R->Fix.NumConversionsFixed;
11438 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes;
11439 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes;
11440 if (numLFixes != numRFixes) {
11441 return numLFixes < numRFixes;
11442 }
11443
11444 // If there's any ordering between the defined conversions...
11445 // FIXME: this might not be transitive.
11446 assert(L->Conversions.size() == R->Conversions.size())((L->Conversions.size() == R->Conversions.size()) ? static_cast
<void> (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11446, __PRETTY_FUNCTION__))
;
11447
11448 int leftBetter = 0;
11449 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11450 for (unsigned E = L->Conversions.size(); I != E; ++I) {
11451 switch (CompareImplicitConversionSequences(S, Loc,
11452 L->Conversions[I],
11453 R->Conversions[I])) {
11454 case ImplicitConversionSequence::Better:
11455 leftBetter++;
11456 break;
11457
11458 case ImplicitConversionSequence::Worse:
11459 leftBetter--;
11460 break;
11461
11462 case ImplicitConversionSequence::Indistinguishable:
11463 break;
11464 }
11465 }
11466 if (leftBetter > 0) return true;
11467 if (leftBetter < 0) return false;
11468
11469 } else if (RFailureKind == ovl_fail_bad_conversion)
11470 return false;
11471
11472 if (LFailureKind == ovl_fail_bad_deduction) {
11473 if (RFailureKind != ovl_fail_bad_deduction)
11474 return true;
11475
11476 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11477 return RankDeductionFailure(L->DeductionFailure)
11478 < RankDeductionFailure(R->DeductionFailure);
11479 } else if (RFailureKind == ovl_fail_bad_deduction)
11480 return false;
11481
11482 // TODO: others?
11483 }
11484
11485 // Sort everything else by location.
11486 SourceLocation LLoc = GetLocationForCandidate(L);
11487 SourceLocation RLoc = GetLocationForCandidate(R);
11488
11489 // Put candidates without locations (e.g. builtins) at the end.
11490 if (LLoc.isInvalid()) return false;
11491 if (RLoc.isInvalid()) return true;
11492
11493 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11494 }
11495};
11496}
11497
11498/// CompleteNonViableCandidate - Normally, overload resolution only
11499/// computes up to the first bad conversion. Produces the FixIt set if
11500/// possible.
11501static void
11502CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11503 ArrayRef<Expr *> Args,
11504 OverloadCandidateSet::CandidateSetKind CSK) {
11505 assert(!Cand->Viable)((!Cand->Viable) ? static_cast<void> (0) : __assert_fail
("!Cand->Viable", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11505, __PRETTY_FUNCTION__))
;
11506
11507 // Don't do anything on failures other than bad conversion.
11508 if (Cand->FailureKind != ovl_fail_bad_conversion)
11509 return;
11510
11511 // We only want the FixIts if all the arguments can be corrected.
11512 bool Unfixable = false;
11513 // Use a implicit copy initialization to check conversion fixes.
11514 Cand->Fix.setConversionChecker(TryCopyInitialization);
11515
11516 // Attempt to fix the bad conversion.
11517 unsigned ConvCount = Cand->Conversions.size();
11518 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11519 ++ConvIdx) {
11520 assert(ConvIdx != ConvCount && "no bad conversion in candidate")((ConvIdx != ConvCount && "no bad conversion in candidate"
) ? static_cast<void> (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11520, __PRETTY_FUNCTION__))
;
11521 if (Cand->Conversions[ConvIdx].isInitialized() &&
11522 Cand->Conversions[ConvIdx].isBad()) {
11523 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11524 break;
11525 }
11526 }
11527
11528 // FIXME: this should probably be preserved from the overload
11529 // operation somehow.
11530 bool SuppressUserConversions = false;
11531
11532 unsigned ConvIdx = 0;
11533 unsigned ArgIdx = 0;
11534 ArrayRef<QualType> ParamTypes;
11535 bool Reversed = Cand->isReversed();
11536
11537 if (Cand->IsSurrogate) {
11538 QualType ConvType
11539 = Cand->Surrogate->getConversionType().getNonReferenceType();
11540 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11541 ConvType = ConvPtrType->getPointeeType();
11542 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11543 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11544 ConvIdx = 1;
11545 } else if (Cand->Function) {
11546 ParamTypes =
11547 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11548 if (isa<CXXMethodDecl>(Cand->Function) &&
11549 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11550 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11551 ConvIdx = 1;
11552 if (CSK == OverloadCandidateSet::CSK_Operator &&
11553 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11554 // Argument 0 is 'this', which doesn't have a corresponding parameter.
11555 ArgIdx = 1;
11556 }
11557 } else {
11558 // Builtin operator.
11559 assert(ConvCount <= 3)((ConvCount <= 3) ? static_cast<void> (0) : __assert_fail
("ConvCount <= 3", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11559, __PRETTY_FUNCTION__))
;
11560 ParamTypes = Cand->BuiltinParamTypes;
11561 }
11562
11563 // Fill in the rest of the conversions.
11564 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11565 ConvIdx != ConvCount;
11566 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11567 assert(ArgIdx < Args.size() && "no argument for this arg conversion")((ArgIdx < Args.size() && "no argument for this arg conversion"
) ? static_cast<void> (0) : __assert_fail ("ArgIdx < Args.size() && \"no argument for this arg conversion\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11567, __PRETTY_FUNCTION__))
;
11568 if (Cand->Conversions[ConvIdx].isInitialized()) {
11569 // We've already checked this conversion.
11570 } else if (ParamIdx < ParamTypes.size()) {
11571 if (ParamTypes[ParamIdx]->isDependentType())
11572 Cand->Conversions[ConvIdx].setAsIdentityConversion(
11573 Args[ArgIdx]->getType());
11574 else {
11575 Cand->Conversions[ConvIdx] =
11576 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11577 SuppressUserConversions,
11578 /*InOverloadResolution=*/true,
11579 /*AllowObjCWritebackConversion=*/
11580 S.getLangOpts().ObjCAutoRefCount);
11581 // Store the FixIt in the candidate if it exists.
11582 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11583 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11584 }
11585 } else
11586 Cand->Conversions[ConvIdx].setEllipsis();
11587 }
11588}
11589
11590SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11591 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11592 SourceLocation OpLoc,
11593 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11594 // Sort the candidates by viability and position. Sorting directly would
11595 // be prohibitive, so we make a set of pointers and sort those.
11596 SmallVector<OverloadCandidate*, 32> Cands;
11597 if (OCD == OCD_AllCandidates) Cands.reserve(size());
11598 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11599 if (!Filter(*Cand))
11600 continue;
11601 switch (OCD) {
11602 case OCD_AllCandidates:
11603 if (!Cand->Viable) {
11604 if (!Cand->Function && !Cand->IsSurrogate) {
11605 // This a non-viable builtin candidate. We do not, in general,
11606 // want to list every possible builtin candidate.
11607 continue;
11608 }
11609 CompleteNonViableCandidate(S, Cand, Args, Kind);
11610 }
11611 break;
11612
11613 case OCD_ViableCandidates:
11614 if (!Cand->Viable)
11615 continue;
11616 break;
11617
11618 case OCD_AmbiguousCandidates:
11619 if (!Cand->Best)
11620 continue;
11621 break;
11622 }
11623
11624 Cands.push_back(Cand);
11625 }
11626
11627 llvm::stable_sort(
11628 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11629
11630 return Cands;
11631}
11632
11633bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11634 SourceLocation OpLoc) {
11635 bool DeferHint = false;
11636 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11637 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11638 // host device candidates.
11639 auto WrongSidedCands =
11640 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11641 return (Cand.Viable == false &&
11642 Cand.FailureKind == ovl_fail_bad_target) ||
11643 (Cand.Function->template hasAttr<CUDAHostAttr>() &&
11644 Cand.Function->template hasAttr<CUDADeviceAttr>());
11645 });
11646 DeferHint = WrongSidedCands.size();
11647 }
11648 return DeferHint;
11649}
11650
11651/// When overload resolution fails, prints diagnostic messages containing the
11652/// candidates in the candidate set.
11653void OverloadCandidateSet::NoteCandidates(
11654 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11655 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11656 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11657
11658 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11659
11660 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11661
11662 NoteCandidates(S, Args, Cands, Opc, OpLoc);
11663
11664 if (OCD == OCD_AmbiguousCandidates)
11665 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11666}
11667
11668void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11669 ArrayRef<OverloadCandidate *> Cands,
11670 StringRef Opc, SourceLocation OpLoc) {
11671 bool ReportedAmbiguousConversions = false;
11672
11673 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11674 unsigned CandsShown = 0;
11675 auto I = Cands.begin(), E = Cands.end();
11676 for (; I != E; ++I) {
11677 OverloadCandidate *Cand = *I;
11678
11679 // Set an arbitrary limit on the number of candidate functions we'll spam
11680 // the user with. FIXME: This limit should depend on details of the
11681 // candidate list.
11682 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11683 break;
11684 }
11685 ++CandsShown;
11686
11687 if (Cand->Function)
11688 NoteFunctionCandidate(S, Cand, Args.size(),
11689 /*TakingCandidateAddress=*/false, DestAS);
11690 else if (Cand->IsSurrogate)
11691 NoteSurrogateCandidate(S, Cand);
11692 else {
11693 assert(Cand->Viable &&((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11694, __PRETTY_FUNCTION__))
11694 "Non-viable built-in candidates are not added to Cands.")((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11694, __PRETTY_FUNCTION__))
;
11695 // Generally we only see ambiguities including viable builtin
11696 // operators if overload resolution got screwed up by an
11697 // ambiguous user-defined conversion.
11698 //
11699 // FIXME: It's quite possible for different conversions to see
11700 // different ambiguities, though.
11701 if (!ReportedAmbiguousConversions) {
11702 NoteAmbiguousUserConversions(S, OpLoc, Cand);
11703 ReportedAmbiguousConversions = true;
11704 }
11705
11706 // If this is a viable builtin, print it.
11707 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11708 }
11709 }
11710
11711 if (I != E)
11712 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11713 shouldDeferDiags(S, Args, OpLoc))
11714 << int(E - I);
11715}
11716
11717static SourceLocation
11718GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11719 return Cand->Specialization ? Cand->Specialization->getLocation()
11720 : SourceLocation();
11721}
11722
11723namespace {
11724struct CompareTemplateSpecCandidatesForDisplay {
11725 Sema &S;
11726 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11727
11728 bool operator()(const TemplateSpecCandidate *L,
11729 const TemplateSpecCandidate *R) {
11730 // Fast-path this check.
11731 if (L == R)
11732 return false;
11733
11734 // Assuming that both candidates are not matches...
11735
11736 // Sort by the ranking of deduction failures.
11737 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11738 return RankDeductionFailure(L->DeductionFailure) <
11739 RankDeductionFailure(R->DeductionFailure);
11740
11741 // Sort everything else by location.
11742 SourceLocation LLoc = GetLocationForCandidate(L);
11743 SourceLocation RLoc = GetLocationForCandidate(R);
11744
11745 // Put candidates without locations (e.g. builtins) at the end.
11746 if (LLoc.isInvalid())
11747 return false;
11748 if (RLoc.isInvalid())
11749 return true;
11750
11751 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11752 }
11753};
11754}
11755
11756/// Diagnose a template argument deduction failure.
11757/// We are treating these failures as overload failures due to bad
11758/// deductions.
11759void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11760 bool ForTakingAddress) {
11761 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11762 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11763}
11764
11765void TemplateSpecCandidateSet::destroyCandidates() {
11766 for (iterator i = begin(), e = end(); i != e; ++i) {
11767 i->DeductionFailure.Destroy();
11768 }
11769}
11770
11771void TemplateSpecCandidateSet::clear() {
11772 destroyCandidates();
11773 Candidates.clear();
11774}
11775
11776/// NoteCandidates - When no template specialization match is found, prints
11777/// diagnostic messages containing the non-matching specializations that form
11778/// the candidate set.
11779/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11780/// OCD == OCD_AllCandidates and Cand->Viable == false.
11781void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11782 // Sort the candidates by position (assuming no candidate is a match).
11783 // Sorting directly would be prohibitive, so we make a set of pointers
11784 // and sort those.
11785 SmallVector<TemplateSpecCandidate *, 32> Cands;
11786 Cands.reserve(size());
11787 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11788 if (Cand->Specialization)
11789 Cands.push_back(Cand);
11790 // Otherwise, this is a non-matching builtin candidate. We do not,
11791 // in general, want to list every possible builtin candidate.
11792 }
11793
11794 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11795
11796 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11797 // for generalization purposes (?).
11798 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11799
11800 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11801 unsigned CandsShown = 0;
11802 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11803 TemplateSpecCandidate *Cand = *I;
11804
11805 // Set an arbitrary limit on the number of candidates we'll spam
11806 // the user with. FIXME: This limit should depend on details of the
11807 // candidate list.
11808 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11809 break;
11810 ++CandsShown;
11811
11812 assert(Cand->Specialization &&((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11813, __PRETTY_FUNCTION__))
11813 "Non-matching built-in candidates are not added to Cands.")((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 11813, __PRETTY_FUNCTION__))
;
11814 Cand->NoteDeductionFailure(S, ForTakingAddress);
11815 }
11816
11817 if (I != E)
11818 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11819}
11820
11821// [PossiblyAFunctionType] --> [Return]
11822// NonFunctionType --> NonFunctionType
11823// R (A) --> R(A)
11824// R (*)(A) --> R (A)
11825// R (&)(A) --> R (A)
11826// R (S::*)(A) --> R (A)
11827QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11828 QualType Ret = PossiblyAFunctionType;
11829 if (const PointerType *ToTypePtr =
11830 PossiblyAFunctionType->getAs<PointerType>())
11831 Ret = ToTypePtr->getPointeeType();
11832 else if (const ReferenceType *ToTypeRef =
11833 PossiblyAFunctionType->getAs<ReferenceType>())
11834 Ret = ToTypeRef->getPointeeType();
11835 else if (const MemberPointerType *MemTypePtr =
11836 PossiblyAFunctionType->getAs<MemberPointerType>())
11837 Ret = MemTypePtr->getPointeeType();
11838 Ret =
11839 Context.getCanonicalType(Ret).getUnqualifiedType();
11840 return Ret;
11841}
11842
11843static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11844 bool Complain = true) {
11845 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11846 S.DeduceReturnType(FD, Loc, Complain))
11847 return true;
11848
11849 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11850 if (S.getLangOpts().CPlusPlus17 &&
11851 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11852 !S.ResolveExceptionSpec(Loc, FPT))
11853 return true;
11854
11855 return false;
11856}
11857
11858namespace {
11859// A helper class to help with address of function resolution
11860// - allows us to avoid passing around all those ugly parameters
11861class AddressOfFunctionResolver {
11862 Sema& S;
11863 Expr* SourceExpr;
11864 const QualType& TargetType;
11865 QualType TargetFunctionType; // Extracted function type from target type
11866
11867 bool Complain;
11868 //DeclAccessPair& ResultFunctionAccessPair;
11869 ASTContext& Context;
11870
11871 bool TargetTypeIsNonStaticMemberFunction;
11872 bool FoundNonTemplateFunction;
11873 bool StaticMemberFunctionFromBoundPointer;
11874 bool HasComplained;
11875
11876 OverloadExpr::FindResult OvlExprInfo;
11877 OverloadExpr *OvlExpr;
11878 TemplateArgumentListInfo OvlExplicitTemplateArgs;
11879 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11880 TemplateSpecCandidateSet FailedCandidates;
11881
11882public:
11883 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11884 const QualType &TargetType, bool Complain)
11885 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11886 Complain(Complain), Context(S.getASTContext()),
11887 TargetTypeIsNonStaticMemberFunction(
11888 !!TargetType->getAs<MemberPointerType>()),
11889 FoundNonTemplateFunction(false),
11890 StaticMemberFunctionFromBoundPointer(false),
11891 HasComplained(false),
11892 OvlExprInfo(OverloadExpr::find(SourceExpr)),
11893 OvlExpr(OvlExprInfo.Expression),
11894 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11895 ExtractUnqualifiedFunctionTypeFromTargetType();
11896
11897 if (TargetFunctionType->isFunctionType()) {
11898 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11899 if (!UME->isImplicitAccess() &&
11900 !S.ResolveSingleFunctionTemplateSpecialization(UME))
11901 StaticMemberFunctionFromBoundPointer = true;
11902 } else if (OvlExpr->hasExplicitTemplateArgs()) {
11903 DeclAccessPair dap;
11904 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11905 OvlExpr, false, &dap)) {
11906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11907 if (!Method->isStatic()) {
11908 // If the target type is a non-function type and the function found
11909 // is a non-static member function, pretend as if that was the
11910 // target, it's the only possible type to end up with.
11911 TargetTypeIsNonStaticMemberFunction = true;
11912
11913 // And skip adding the function if its not in the proper form.
11914 // We'll diagnose this due to an empty set of functions.
11915 if (!OvlExprInfo.HasFormOfMemberPointer)
11916 return;
11917 }
11918
11919 Matches.push_back(std::make_pair(dap, Fn));
11920 }
11921 return;
11922 }
11923
11924 if (OvlExpr->hasExplicitTemplateArgs())
11925 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11926
11927 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11928 // C++ [over.over]p4:
11929 // If more than one function is selected, [...]
11930 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11931 if (FoundNonTemplateFunction)
11932 EliminateAllTemplateMatches();
11933 else
11934 EliminateAllExceptMostSpecializedTemplate();
11935 }
11936 }
11937
11938 if (S.getLangOpts().CUDA && Matches.size() > 1)
11939 EliminateSuboptimalCudaMatches();
11940 }
11941
11942 bool hasComplained() const { return HasComplained; }
11943
11944private:
11945 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11946 QualType Discard;
11947 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11948 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11949 }
11950
11951 /// \return true if A is considered a better overload candidate for the
11952 /// desired type than B.
11953 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11954 // If A doesn't have exactly the correct type, we don't want to classify it
11955 // as "better" than anything else. This way, the user is required to
11956 // disambiguate for us if there are multiple candidates and no exact match.
11957 return candidateHasExactlyCorrectType(A) &&
11958 (!candidateHasExactlyCorrectType(B) ||
11959 compareEnableIfAttrs(S, A, B) == Comparison::Better);
11960 }
11961
11962 /// \return true if we were able to eliminate all but one overload candidate,
11963 /// false otherwise.
11964 bool eliminiateSuboptimalOverloadCandidates() {
11965 // Same algorithm as overload resolution -- one pass to pick the "best",
11966 // another pass to be sure that nothing is better than the best.
11967 auto Best = Matches.begin();
11968 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11969 if (isBetterCandidate(I->second, Best->second))
11970 Best = I;
11971
11972 const FunctionDecl *BestFn = Best->second;
11973 auto IsBestOrInferiorToBest = [this, BestFn](
11974 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11975 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11976 };
11977
11978 // Note: We explicitly leave Matches unmodified if there isn't a clear best
11979 // option, so we can potentially give the user a better error
11980 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11981 return false;
11982 Matches[0] = *Best;
11983 Matches.resize(1);
11984 return true;
11985 }
11986
11987 bool isTargetTypeAFunction() const {
11988 return TargetFunctionType->isFunctionType();
11989 }
11990
11991 // [ToType] [Return]
11992
11993 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11994 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11995 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11996 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11997 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11998 }
11999
12000 // return true if any matching specializations were found
12001 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12002 const DeclAccessPair& CurAccessFunPair) {
12003 if (CXXMethodDecl *Method
12004 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12005 // Skip non-static function templates when converting to pointer, and
12006 // static when converting to member pointer.
12007 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12008 return false;
12009 }
12010 else if (TargetTypeIsNonStaticMemberFunction)
12011 return false;
12012
12013 // C++ [over.over]p2:
12014 // If the name is a function template, template argument deduction is
12015 // done (14.8.2.2), and if the argument deduction succeeds, the
12016 // resulting template argument list is used to generate a single
12017 // function template specialization, which is added to the set of
12018 // overloaded functions considered.
12019 FunctionDecl *Specialization = nullptr;
12020 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12021 if (Sema::TemplateDeductionResult Result
12022 = S.DeduceTemplateArguments(FunctionTemplate,
12023 &OvlExplicitTemplateArgs,
12024 TargetFunctionType, Specialization,
12025 Info, /*IsAddressOfFunction*/true)) {
12026 // Make a note of the failed deduction for diagnostics.
12027 FailedCandidates.addCandidate()
12028 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12029 MakeDeductionFailureInfo(Context, Result, Info));
12030 return false;
12031 }
12032
12033 // Template argument deduction ensures that we have an exact match or
12034 // compatible pointer-to-function arguments that would be adjusted by ICS.
12035 // This function template specicalization works.
12036 assert(S.isSameOrCompatibleFunctionType(((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12038, __PRETTY_FUNCTION__))
12037 Context.getCanonicalType(Specialization->getType()),((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12038, __PRETTY_FUNCTION__))
12038 Context.getCanonicalType(TargetFunctionType)))((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12038, __PRETTY_FUNCTION__))
;
12039
12040 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12041 return false;
12042
12043 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12044 return true;
12045 }
12046
12047 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12048 const DeclAccessPair& CurAccessFunPair) {
12049 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12050 // Skip non-static functions when converting to pointer, and static
12051 // when converting to member pointer.
12052 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12053 return false;
12054 }
12055 else if (TargetTypeIsNonStaticMemberFunction)
12056 return false;
12057
12058 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12059 if (S.getLangOpts().CUDA)
12060 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
12061 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12062 return false;
12063 if (FunDecl->isMultiVersion()) {
12064 const auto *TA = FunDecl->getAttr<TargetAttr>();
12065 if (TA && !TA->isDefaultVersion())
12066 return false;
12067 }
12068
12069 // If any candidate has a placeholder return type, trigger its deduction
12070 // now.
12071 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12072 Complain)) {
12073 HasComplained |= Complain;
12074 return false;
12075 }
12076
12077 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12078 return false;
12079
12080 // If we're in C, we need to support types that aren't exactly identical.
12081 if (!S.getLangOpts().CPlusPlus ||
12082 candidateHasExactlyCorrectType(FunDecl)) {
12083 Matches.push_back(std::make_pair(
12084 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12085 FoundNonTemplateFunction = true;
12086 return true;
12087 }
12088 }
12089
12090 return false;
12091 }
12092
12093 bool FindAllFunctionsThatMatchTargetTypeExactly() {
12094 bool Ret = false;
12095
12096 // If the overload expression doesn't have the form of a pointer to
12097 // member, don't try to convert it to a pointer-to-member type.
12098 if (IsInvalidFormOfPointerToMemberFunction())
12099 return false;
12100
12101 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12102 E = OvlExpr->decls_end();
12103 I != E; ++I) {
12104 // Look through any using declarations to find the underlying function.
12105 NamedDecl *Fn = (*I)->getUnderlyingDecl();
12106
12107 // C++ [over.over]p3:
12108 // Non-member functions and static member functions match
12109 // targets of type "pointer-to-function" or "reference-to-function."
12110 // Nonstatic member functions match targets of
12111 // type "pointer-to-member-function."
12112 // Note that according to DR 247, the containing class does not matter.
12113 if (FunctionTemplateDecl *FunctionTemplate
12114 = dyn_cast<FunctionTemplateDecl>(Fn)) {
12115 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12116 Ret = true;
12117 }
12118 // If we have explicit template arguments supplied, skip non-templates.
12119 else if (!OvlExpr->hasExplicitTemplateArgs() &&
12120 AddMatchingNonTemplateFunction(Fn, I.getPair()))
12121 Ret = true;
12122 }
12123 assert(Ret || Matches.empty())((Ret || Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Ret || Matches.empty()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12123, __PRETTY_FUNCTION__))
;
12124 return Ret;
12125 }
12126
12127 void EliminateAllExceptMostSpecializedTemplate() {
12128 // [...] and any given function template specialization F1 is
12129 // eliminated if the set contains a second function template
12130 // specialization whose function template is more specialized
12131 // than the function template of F1 according to the partial
12132 // ordering rules of 14.5.5.2.
12133
12134 // The algorithm specified above is quadratic. We instead use a
12135 // two-pass algorithm (similar to the one used to identify the
12136 // best viable function in an overload set) that identifies the
12137 // best function template (if it exists).
12138
12139 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12140 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12141 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12142
12143 // TODO: It looks like FailedCandidates does not serve much purpose
12144 // here, since the no_viable diagnostic has index 0.
12145 UnresolvedSetIterator Result = S.getMostSpecialized(
12146 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12147 SourceExpr->getBeginLoc(), S.PDiag(),
12148 S.PDiag(diag::err_addr_ovl_ambiguous)
12149 << Matches[0].second->getDeclName(),
12150 S.PDiag(diag::note_ovl_candidate)
12151 << (unsigned)oc_function << (unsigned)ocs_described_template,
12152 Complain, TargetFunctionType);
12153
12154 if (Result != MatchesCopy.end()) {
12155 // Make it the first and only element
12156 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12157 Matches[0].second = cast<FunctionDecl>(*Result);
12158 Matches.resize(1);
12159 } else
12160 HasComplained |= Complain;
12161 }
12162
12163 void EliminateAllTemplateMatches() {
12164 // [...] any function template specializations in the set are
12165 // eliminated if the set also contains a non-template function, [...]
12166 for (unsigned I = 0, N = Matches.size(); I != N; ) {
12167 if (Matches[I].second->getPrimaryTemplate() == nullptr)
12168 ++I;
12169 else {
12170 Matches[I] = Matches[--N];
12171 Matches.resize(N);
12172 }
12173 }
12174 }
12175
12176 void EliminateSuboptimalCudaMatches() {
12177 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12178 }
12179
12180public:
12181 void ComplainNoMatchesFound() const {
12182 assert(Matches.empty())((Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Matches.empty()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12182, __PRETTY_FUNCTION__))
;
12183 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12184 << OvlExpr->getName() << TargetFunctionType
12185 << OvlExpr->getSourceRange();
12186 if (FailedCandidates.empty())
12187 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12188 /*TakingAddress=*/true);
12189 else {
12190 // We have some deduction failure messages. Use them to diagnose
12191 // the function templates, and diagnose the non-template candidates
12192 // normally.
12193 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12194 IEnd = OvlExpr->decls_end();
12195 I != IEnd; ++I)
12196 if (FunctionDecl *Fun =
12197 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12198 if (!functionHasPassObjectSizeParams(Fun))
12199 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12200 /*TakingAddress=*/true);
12201 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12202 }
12203 }
12204
12205 bool IsInvalidFormOfPointerToMemberFunction() const {
12206 return TargetTypeIsNonStaticMemberFunction &&
12207 !OvlExprInfo.HasFormOfMemberPointer;
12208 }
12209
12210 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12211 // TODO: Should we condition this on whether any functions might
12212 // have matched, or is it more appropriate to do that in callers?
12213 // TODO: a fixit wouldn't hurt.
12214 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12215 << TargetType << OvlExpr->getSourceRange();
12216 }
12217
12218 bool IsStaticMemberFunctionFromBoundPointer() const {
12219 return StaticMemberFunctionFromBoundPointer;
12220 }
12221
12222 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12223 S.Diag(OvlExpr->getBeginLoc(),
12224 diag::err_invalid_form_pointer_member_function)
12225 << OvlExpr->getSourceRange();
12226 }
12227
12228 void ComplainOfInvalidConversion() const {
12229 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12230 << OvlExpr->getName() << TargetType;
12231 }
12232
12233 void ComplainMultipleMatchesFound() const {
12234 assert(Matches.size() > 1)((Matches.size() > 1) ? static_cast<void> (0) : __assert_fail
("Matches.size() > 1", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12234, __PRETTY_FUNCTION__))
;
12235 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12236 << OvlExpr->getName() << OvlExpr->getSourceRange();
12237 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12238 /*TakingAddress=*/true);
12239 }
12240
12241 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12242
12243 int getNumMatches() const { return Matches.size(); }
12244
12245 FunctionDecl* getMatchingFunctionDecl() const {
12246 if (Matches.size() != 1) return nullptr;
12247 return Matches[0].second;
12248 }
12249
12250 const DeclAccessPair* getMatchingFunctionAccessPair() const {
12251 if (Matches.size() != 1) return nullptr;
12252 return &Matches[0].first;
12253 }
12254};
12255}
12256
12257/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12258/// an overloaded function (C++ [over.over]), where @p From is an
12259/// expression with overloaded function type and @p ToType is the type
12260/// we're trying to resolve to. For example:
12261///
12262/// @code
12263/// int f(double);
12264/// int f(int);
12265///
12266/// int (*pfd)(double) = f; // selects f(double)
12267/// @endcode
12268///
12269/// This routine returns the resulting FunctionDecl if it could be
12270/// resolved, and NULL otherwise. When @p Complain is true, this
12271/// routine will emit diagnostics if there is an error.
12272FunctionDecl *
12273Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12274 QualType TargetType,
12275 bool Complain,
12276 DeclAccessPair &FoundResult,
12277 bool *pHadMultipleCandidates) {
12278 assert(AddressOfExpr->getType() == Context.OverloadTy)((AddressOfExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12278, __PRETTY_FUNCTION__))
;
12279
12280 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12281 Complain);
12282 int NumMatches = Resolver.getNumMatches();
12283 FunctionDecl *Fn = nullptr;
12284 bool ShouldComplain = Complain && !Resolver.hasComplained();
12285 if (NumMatches == 0 && ShouldComplain) {
12286 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12287 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12288 else
12289 Resolver.ComplainNoMatchesFound();
12290 }
12291 else if (NumMatches > 1 && ShouldComplain)
12292 Resolver.ComplainMultipleMatchesFound();
12293 else if (NumMatches == 1) {
12294 Fn = Resolver.getMatchingFunctionDecl();
12295 assert(Fn)((Fn) ? static_cast<void> (0) : __assert_fail ("Fn", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12295, __PRETTY_FUNCTION__))
;
12296 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12297 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12298 FoundResult = *Resolver.getMatchingFunctionAccessPair();
12299 if (Complain) {
12300 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12301 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12302 else
12303 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12304 }
12305 }
12306
12307 if (pHadMultipleCandidates)
12308 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12309 return Fn;
12310}
12311
12312/// Given an expression that refers to an overloaded function, try to
12313/// resolve that function to a single function that can have its address taken.
12314/// This will modify `Pair` iff it returns non-null.
12315///
12316/// This routine can only succeed if from all of the candidates in the overload
12317/// set for SrcExpr that can have their addresses taken, there is one candidate
12318/// that is more constrained than the rest.
12319FunctionDecl *
12320Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12321 OverloadExpr::FindResult R = OverloadExpr::find(E);
12322 OverloadExpr *Ovl = R.Expression;
12323 bool IsResultAmbiguous = false;
12324 FunctionDecl *Result = nullptr;
12325 DeclAccessPair DAP;
12326 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12327
12328 auto CheckMoreConstrained =
12329 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12330 SmallVector<const Expr *, 1> AC1, AC2;
12331 FD1->getAssociatedConstraints(AC1);
12332 FD2->getAssociatedConstraints(AC2);
12333 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12334 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12335 return None;
12336 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12337 return None;
12338 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12339 return None;
12340 return AtLeastAsConstrained1;
12341 };
12342
12343 // Don't use the AddressOfResolver because we're specifically looking for
12344 // cases where we have one overload candidate that lacks
12345 // enable_if/pass_object_size/...
12346 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12347 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12348 if (!FD)
12349 return nullptr;
12350
12351 if (!checkAddressOfFunctionIsAvailable(FD))
12352 continue;
12353
12354 // We have more than one result - see if it is more constrained than the
12355 // previous one.
12356 if (Result) {
12357 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12358 Result);
12359 if (!MoreConstrainedThanPrevious) {
12360 IsResultAmbiguous = true;
12361 AmbiguousDecls.push_back(FD);
12362 continue;
12363 }
12364 if (!*MoreConstrainedThanPrevious)
12365 continue;
12366 // FD is more constrained - replace Result with it.
12367 }
12368 IsResultAmbiguous = false;
12369 DAP = I.getPair();
12370 Result = FD;
12371 }
12372
12373 if (IsResultAmbiguous)
12374 return nullptr;
12375
12376 if (Result) {
12377 SmallVector<const Expr *, 1> ResultAC;
12378 // We skipped over some ambiguous declarations which might be ambiguous with
12379 // the selected result.
12380 for (FunctionDecl *Skipped : AmbiguousDecls)
12381 if (!CheckMoreConstrained(Skipped, Result).hasValue())
12382 return nullptr;
12383 Pair = DAP;
12384 }
12385 return Result;
12386}
12387
12388/// Given an overloaded function, tries to turn it into a non-overloaded
12389/// function reference using resolveAddressOfSingleOverloadCandidate. This
12390/// will perform access checks, diagnose the use of the resultant decl, and, if
12391/// requested, potentially perform a function-to-pointer decay.
12392///
12393/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12394/// Otherwise, returns true. This may emit diagnostics and return true.
12395bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12396 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12397 Expr *E = SrcExpr.get();
12398 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")((E->getType() == Context.OverloadTy && "SrcExpr must be an overload"
) ? static_cast<void> (0) : __assert_fail ("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12398, __PRETTY_FUNCTION__))
;
12399
12400 DeclAccessPair DAP;
12401 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12402 if (!Found || Found->isCPUDispatchMultiVersion() ||
12403 Found->isCPUSpecificMultiVersion())
12404 return false;
12405
12406 // Emitting multiple diagnostics for a function that is both inaccessible and
12407 // unavailable is consistent with our behavior elsewhere. So, always check
12408 // for both.
12409 DiagnoseUseOfDecl(Found, E->getExprLoc());
12410 CheckAddressOfMemberAccess(E, DAP);
12411 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12412 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12413 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12414 else
12415 SrcExpr = Fixed;
12416 return true;
12417}
12418
12419/// Given an expression that refers to an overloaded function, try to
12420/// resolve that overloaded function expression down to a single function.
12421///
12422/// This routine can only resolve template-ids that refer to a single function
12423/// template, where that template-id refers to a single template whose template
12424/// arguments are either provided by the template-id or have defaults,
12425/// as described in C++0x [temp.arg.explicit]p3.
12426///
12427/// If no template-ids are found, no diagnostics are emitted and NULL is
12428/// returned.
12429FunctionDecl *
12430Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12431 bool Complain,
12432 DeclAccessPair *FoundResult) {
12433 // C++ [over.over]p1:
12434 // [...] [Note: any redundant set of parentheses surrounding the
12435 // overloaded function name is ignored (5.1). ]
12436 // C++ [over.over]p1:
12437 // [...] The overloaded function name can be preceded by the &
12438 // operator.
12439
12440 // If we didn't actually find any template-ids, we're done.
12441 if (!ovl->hasExplicitTemplateArgs())
12442 return nullptr;
12443
12444 TemplateArgumentListInfo ExplicitTemplateArgs;
12445 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12446 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12447
12448 // Look through all of the overloaded functions, searching for one
12449 // whose type matches exactly.
12450 FunctionDecl *Matched = nullptr;
12451 for (UnresolvedSetIterator I = ovl->decls_begin(),
12452 E = ovl->decls_end(); I != E; ++I) {
12453 // C++0x [temp.arg.explicit]p3:
12454 // [...] In contexts where deduction is done and fails, or in contexts
12455 // where deduction is not done, if a template argument list is
12456 // specified and it, along with any default template arguments,
12457 // identifies a single function template specialization, then the
12458 // template-id is an lvalue for the function template specialization.
12459 FunctionTemplateDecl *FunctionTemplate
12460 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12461
12462 // C++ [over.over]p2:
12463 // If the name is a function template, template argument deduction is
12464 // done (14.8.2.2), and if the argument deduction succeeds, the
12465 // resulting template argument list is used to generate a single
12466 // function template specialization, which is added to the set of
12467 // overloaded functions considered.
12468 FunctionDecl *Specialization = nullptr;
12469 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12470 if (TemplateDeductionResult Result
12471 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12472 Specialization, Info,
12473 /*IsAddressOfFunction*/true)) {
12474 // Make a note of the failed deduction for diagnostics.
12475 // TODO: Actually use the failed-deduction info?
12476 FailedCandidates.addCandidate()
12477 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12478 MakeDeductionFailureInfo(Context, Result, Info));
12479 continue;
12480 }
12481
12482 assert(Specialization && "no specialization and no error?")((Specialization && "no specialization and no error?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"no specialization and no error?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12482, __PRETTY_FUNCTION__))
;
12483
12484 // Multiple matches; we can't resolve to a single declaration.
12485 if (Matched) {
12486 if (Complain) {
12487 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12488 << ovl->getName();
12489 NoteAllOverloadCandidates(ovl);
12490 }
12491 return nullptr;
12492 }
12493
12494 Matched = Specialization;
12495 if (FoundResult) *FoundResult = I.getPair();
12496 }
12497
12498 if (Matched &&
12499 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12500 return nullptr;
12501
12502 return Matched;
12503}
12504
12505// Resolve and fix an overloaded expression that can be resolved
12506// because it identifies a single function template specialization.
12507//
12508// Last three arguments should only be supplied if Complain = true
12509//
12510// Return true if it was logically possible to so resolve the
12511// expression, regardless of whether or not it succeeded. Always
12512// returns true if 'complain' is set.
12513bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12514 ExprResult &SrcExpr, bool doFunctionPointerConverion,
12515 bool complain, SourceRange OpRangeForComplaining,
12516 QualType DestTypeForComplaining,
12517 unsigned DiagIDForComplaining) {
12518 assert(SrcExpr.get()->getType() == Context.OverloadTy)((SrcExpr.get()->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12518, __PRETTY_FUNCTION__))
;
12519
12520 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12521
12522 DeclAccessPair found;
12523 ExprResult SingleFunctionExpression;
12524 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12525 ovl.Expression, /*complain*/ false, &found)) {
12526 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12527 SrcExpr = ExprError();
12528 return true;
12529 }
12530
12531 // It is only correct to resolve to an instance method if we're
12532 // resolving a form that's permitted to be a pointer to member.
12533 // Otherwise we'll end up making a bound member expression, which
12534 // is illegal in all the contexts we resolve like this.
12535 if (!ovl.HasFormOfMemberPointer &&
12536 isa<CXXMethodDecl>(fn) &&
12537 cast<CXXMethodDecl>(fn)->isInstance()) {
12538 if (!complain) return false;
12539
12540 Diag(ovl.Expression->getExprLoc(),
12541 diag::err_bound_member_function)
12542 << 0 << ovl.Expression->getSourceRange();
12543
12544 // TODO: I believe we only end up here if there's a mix of
12545 // static and non-static candidates (otherwise the expression
12546 // would have 'bound member' type, not 'overload' type).
12547 // Ideally we would note which candidate was chosen and why
12548 // the static candidates were rejected.
12549 SrcExpr = ExprError();
12550 return true;
12551 }
12552
12553 // Fix the expression to refer to 'fn'.
12554 SingleFunctionExpression =
12555 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12556
12557 // If desired, do function-to-pointer decay.
12558 if (doFunctionPointerConverion) {
12559 SingleFunctionExpression =
12560 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12561 if (SingleFunctionExpression.isInvalid()) {
12562 SrcExpr = ExprError();
12563 return true;
12564 }
12565 }
12566 }
12567
12568 if (!SingleFunctionExpression.isUsable()) {
12569 if (complain) {
12570 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12571 << ovl.Expression->getName()
12572 << DestTypeForComplaining
12573 << OpRangeForComplaining
12574 << ovl.Expression->getQualifierLoc().getSourceRange();
12575 NoteAllOverloadCandidates(SrcExpr.get());
12576
12577 SrcExpr = ExprError();
12578 return true;
12579 }
12580
12581 return false;
12582 }
12583
12584 SrcExpr = SingleFunctionExpression;
12585 return true;
12586}
12587
12588/// Add a single candidate to the overload set.
12589static void AddOverloadedCallCandidate(Sema &S,
12590 DeclAccessPair FoundDecl,
12591 TemplateArgumentListInfo *ExplicitTemplateArgs,
12592 ArrayRef<Expr *> Args,
12593 OverloadCandidateSet &CandidateSet,
12594 bool PartialOverloading,
12595 bool KnownValid) {
12596 NamedDecl *Callee = FoundDecl.getDecl();
12597 if (isa<UsingShadowDecl>(Callee))
12598 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12599
12600 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12601 if (ExplicitTemplateArgs) {
12602 assert(!KnownValid && "Explicit template arguments?")((!KnownValid && "Explicit template arguments?") ? static_cast
<void> (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12602, __PRETTY_FUNCTION__))
;
12603 return;
12604 }
12605 // Prevent ill-formed function decls to be added as overload candidates.
12606 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12607 return;
12608
12609 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12610 /*SuppressUserConversions=*/false,
12611 PartialOverloading);
12612 return;
12613 }
12614
12615 if (FunctionTemplateDecl *FuncTemplate
12616 = dyn_cast<FunctionTemplateDecl>(Callee)) {
12617 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12618 ExplicitTemplateArgs, Args, CandidateSet,
12619 /*SuppressUserConversions=*/false,
12620 PartialOverloading);
12621 return;
12622 }
12623
12624 assert(!KnownValid && "unhandled case in overloaded call candidate")((!KnownValid && "unhandled case in overloaded call candidate"
) ? static_cast<void> (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12624, __PRETTY_FUNCTION__))
;
12625}
12626
12627/// Add the overload candidates named by callee and/or found by argument
12628/// dependent lookup to the given overload set.
12629void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12630 ArrayRef<Expr *> Args,
12631 OverloadCandidateSet &CandidateSet,
12632 bool PartialOverloading) {
12633
12634#ifndef NDEBUG
12635 // Verify that ArgumentDependentLookup is consistent with the rules
12636 // in C++0x [basic.lookup.argdep]p3:
12637 //
12638 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12639 // and let Y be the lookup set produced by argument dependent
12640 // lookup (defined as follows). If X contains
12641 //
12642 // -- a declaration of a class member, or
12643 //
12644 // -- a block-scope function declaration that is not a
12645 // using-declaration, or
12646 //
12647 // -- a declaration that is neither a function or a function
12648 // template
12649 //
12650 // then Y is empty.
12651
12652 if (ULE->requiresADL()) {
12653 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12654 E = ULE->decls_end(); I != E; ++I) {
12655 assert(!(*I)->getDeclContext()->isRecord())((!(*I)->getDeclContext()->isRecord()) ? static_cast<
void> (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12655, __PRETTY_FUNCTION__))
;
12656 assert(isa<UsingShadowDecl>(*I) ||((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12657, __PRETTY_FUNCTION__))
12657 !(*I)->getDeclContext()->isFunctionOrMethod())((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12657, __PRETTY_FUNCTION__))
;
12658 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? static_cast<void> (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12658, __PRETTY_FUNCTION__))
;
12659 }
12660 }
12661#endif
12662
12663 // It would be nice to avoid this copy.
12664 TemplateArgumentListInfo TABuffer;
12665 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12666 if (ULE->hasExplicitTemplateArgs()) {
12667 ULE->copyTemplateArgumentsInto(TABuffer);
12668 ExplicitTemplateArgs = &TABuffer;
12669 }
12670
12671 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12672 E = ULE->decls_end(); I != E; ++I)
12673 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12674 CandidateSet, PartialOverloading,
12675 /*KnownValid*/ true);
12676
12677 if (ULE->requiresADL())
12678 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12679 Args, ExplicitTemplateArgs,
12680 CandidateSet, PartialOverloading);
12681}
12682
12683/// Add the call candidates from the given set of lookup results to the given
12684/// overload set. Non-function lookup results are ignored.
12685void Sema::AddOverloadedCallCandidates(
12686 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12687 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12688 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12689 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12690 CandidateSet, false, /*KnownValid*/ false);
12691}
12692
12693/// Determine whether a declaration with the specified name could be moved into
12694/// a different namespace.
12695static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12696 switch (Name.getCXXOverloadedOperator()) {
12697 case OO_New: case OO_Array_New:
12698 case OO_Delete: case OO_Array_Delete:
12699 return false;
12700
12701 default:
12702 return true;
12703 }
12704}
12705
12706/// Attempt to recover from an ill-formed use of a non-dependent name in a
12707/// template, where the non-dependent name was declared after the template
12708/// was defined. This is common in code written for a compilers which do not
12709/// correctly implement two-stage name lookup.
12710///
12711/// Returns true if a viable candidate was found and a diagnostic was issued.
12712static bool DiagnoseTwoPhaseLookup(
12713 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12714 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12715 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12716 CXXRecordDecl **FoundInClass = nullptr) {
12717 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12718 return false;
12719
12720 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12721 if (DC->isTransparentContext())
12722 continue;
12723
12724 SemaRef.LookupQualifiedName(R, DC);
12725
12726 if (!R.empty()) {
12727 R.suppressDiagnostics();
12728
12729 OverloadCandidateSet Candidates(FnLoc, CSK);
12730 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12731 Candidates);
12732
12733 OverloadCandidateSet::iterator Best;
12734 OverloadingResult OR =
12735 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12736
12737 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12738 // We either found non-function declarations or a best viable function
12739 // at class scope. A class-scope lookup result disables ADL. Don't
12740 // look past this, but let the caller know that we found something that
12741 // either is, or might be, usable in this class.
12742 if (FoundInClass) {
12743 *FoundInClass = RD;
12744 if (OR == OR_Success) {
12745 R.clear();
12746 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12747 R.resolveKind();
12748 }
12749 }
12750 return false;
12751 }
12752
12753 if (OR != OR_Success) {
12754 // There wasn't a unique best function or function template.
12755 return false;
12756 }
12757
12758 // Find the namespaces where ADL would have looked, and suggest
12759 // declaring the function there instead.
12760 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12761 Sema::AssociatedClassSet AssociatedClasses;
12762 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12763 AssociatedNamespaces,
12764 AssociatedClasses);
12765 Sema::AssociatedNamespaceSet SuggestedNamespaces;
12766 if (canBeDeclaredInNamespace(R.getLookupName())) {
12767 DeclContext *Std = SemaRef.getStdNamespace();
12768 for (Sema::AssociatedNamespaceSet::iterator
12769 it = AssociatedNamespaces.begin(),
12770 end = AssociatedNamespaces.end(); it != end; ++it) {
12771 // Never suggest declaring a function within namespace 'std'.
12772 if (Std && Std->Encloses(*it))
12773 continue;
12774
12775 // Never suggest declaring a function within a namespace with a
12776 // reserved name, like __gnu_cxx.
12777 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12778 if (NS &&
12779 NS->getQualifiedNameAsString().find("__") != std::string::npos)
12780 continue;
12781
12782 SuggestedNamespaces.insert(*it);
12783 }
12784 }
12785
12786 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12787 << R.getLookupName();
12788 if (SuggestedNamespaces.empty()) {
12789 SemaRef.Diag(Best->Function->getLocation(),
12790 diag::note_not_found_by_two_phase_lookup)
12791 << R.getLookupName() << 0;
12792 } else if (SuggestedNamespaces.size() == 1) {
12793 SemaRef.Diag(Best->Function->getLocation(),
12794 diag::note_not_found_by_two_phase_lookup)
12795 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12796 } else {
12797 // FIXME: It would be useful to list the associated namespaces here,
12798 // but the diagnostics infrastructure doesn't provide a way to produce
12799 // a localized representation of a list of items.
12800 SemaRef.Diag(Best->Function->getLocation(),
12801 diag::note_not_found_by_two_phase_lookup)
12802 << R.getLookupName() << 2;
12803 }
12804
12805 // Try to recover by calling this function.
12806 return true;
12807 }
12808
12809 R.clear();
12810 }
12811
12812 return false;
12813}
12814
12815/// Attempt to recover from ill-formed use of a non-dependent operator in a
12816/// template, where the non-dependent operator was declared after the template
12817/// was defined.
12818///
12819/// Returns true if a viable candidate was found and a diagnostic was issued.
12820static bool
12821DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12822 SourceLocation OpLoc,
12823 ArrayRef<Expr *> Args) {
12824 DeclarationName OpName =
12825 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12826 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12827 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12828 OverloadCandidateSet::CSK_Operator,
12829 /*ExplicitTemplateArgs=*/nullptr, Args);
12830}
12831
12832namespace {
12833class BuildRecoveryCallExprRAII {
12834 Sema &SemaRef;
12835public:
12836 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12837 assert(SemaRef.IsBuildingRecoveryCallExpr == false)((SemaRef.IsBuildingRecoveryCallExpr == false) ? static_cast<
void> (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12837, __PRETTY_FUNCTION__))
;
12838 SemaRef.IsBuildingRecoveryCallExpr = true;
12839 }
12840
12841 ~BuildRecoveryCallExprRAII() {
12842 SemaRef.IsBuildingRecoveryCallExpr = false;
12843 }
12844};
12845
12846}
12847
12848/// Attempts to recover from a call where no functions were found.
12849///
12850/// This function will do one of three things:
12851/// * Diagnose, recover, and return a recovery expression.
12852/// * Diagnose, fail to recover, and return ExprError().
12853/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
12854/// expected to diagnose as appropriate.
12855static ExprResult
12856BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12857 UnresolvedLookupExpr *ULE,
12858 SourceLocation LParenLoc,
12859 MutableArrayRef<Expr *> Args,
12860 SourceLocation RParenLoc,
12861 bool EmptyLookup, bool AllowTypoCorrection) {
12862 // Do not try to recover if it is already building a recovery call.
12863 // This stops infinite loops for template instantiations like
12864 //
12865 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12866 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12867 if (SemaRef.IsBuildingRecoveryCallExpr)
12868 return ExprResult();
12869 BuildRecoveryCallExprRAII RCE(SemaRef);
12870
12871 CXXScopeSpec SS;
12872 SS.Adopt(ULE->getQualifierLoc());
12873 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12874
12875 TemplateArgumentListInfo TABuffer;
12876 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12877 if (ULE->hasExplicitTemplateArgs()) {
12878 ULE->copyTemplateArgumentsInto(TABuffer);
12879 ExplicitTemplateArgs = &TABuffer;
12880 }
12881
12882 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12883 Sema::LookupOrdinaryName);
12884 CXXRecordDecl *FoundInClass = nullptr;
12885 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
12886 OverloadCandidateSet::CSK_Normal,
12887 ExplicitTemplateArgs, Args, &FoundInClass)) {
12888 // OK, diagnosed a two-phase lookup issue.
12889 } else if (EmptyLookup) {
12890 // Try to recover from an empty lookup with typo correction.
12891 R.clear();
12892 NoTypoCorrectionCCC NoTypoValidator{};
12893 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12894 ExplicitTemplateArgs != nullptr,
12895 dyn_cast<MemberExpr>(Fn));
12896 CorrectionCandidateCallback &Validator =
12897 AllowTypoCorrection
12898 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12899 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12900 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12901 Args))
12902 return ExprError();
12903 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
12904 // We found a usable declaration of the name in a dependent base of some
12905 // enclosing class.
12906 // FIXME: We should also explain why the candidates found by name lookup
12907 // were not viable.
12908 if (SemaRef.DiagnoseDependentMemberLookup(R))
12909 return ExprError();
12910 } else {
12911 // We had viable candidates and couldn't recover; let the caller diagnose
12912 // this.
12913 return ExprResult();
12914 }
12915
12916 // If we get here, we should have issued a diagnostic and formed a recovery
12917 // lookup result.
12918 assert(!R.empty() && "lookup results empty despite recovery")((!R.empty() && "lookup results empty despite recovery"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12918, __PRETTY_FUNCTION__))
;
12919
12920 // If recovery created an ambiguity, just bail out.
12921 if (R.isAmbiguous()) {
12922 R.suppressDiagnostics();
12923 return ExprError();
12924 }
12925
12926 // Build an implicit member call if appropriate. Just drop the
12927 // casts and such from the call, we don't really care.
12928 ExprResult NewFn = ExprError();
12929 if ((*R.begin())->isCXXClassMember())
12930 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12931 ExplicitTemplateArgs, S);
12932 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12933 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12934 ExplicitTemplateArgs);
12935 else
12936 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12937
12938 if (NewFn.isInvalid())
12939 return ExprError();
12940
12941 // This shouldn't cause an infinite loop because we're giving it
12942 // an expression with viable lookup results, which should never
12943 // end up here.
12944 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12945 MultiExprArg(Args.data(), Args.size()),
12946 RParenLoc);
12947}
12948
12949/// Constructs and populates an OverloadedCandidateSet from
12950/// the given function.
12951/// \returns true when an the ExprResult output parameter has been set.
12952bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12953 UnresolvedLookupExpr *ULE,
12954 MultiExprArg Args,
12955 SourceLocation RParenLoc,
12956 OverloadCandidateSet *CandidateSet,
12957 ExprResult *Result) {
12958#ifndef NDEBUG
12959 if (ULE->requiresADL()) {
12960 // To do ADL, we must have found an unqualified name.
12961 assert(!ULE->getQualifier() && "qualified name with ADL")((!ULE->getQualifier() && "qualified name with ADL"
) ? static_cast<void> (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12961, __PRETTY_FUNCTION__))
;
12962
12963 // We don't perform ADL for implicit declarations of builtins.
12964 // Verify that this was correctly set up.
12965 FunctionDecl *F;
12966 if (ULE->decls_begin() != ULE->decls_end() &&
12967 ULE->decls_begin() + 1 == ULE->decls_end() &&
12968 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12969 F->getBuiltinID() && F->isImplicit())
12970 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12970)
;
12971
12972 // We don't perform ADL in C.
12973 assert(getLangOpts().CPlusPlus && "ADL enabled in C")((getLangOpts().CPlusPlus && "ADL enabled in C") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 12973, __PRETTY_FUNCTION__))
;
12974 }
12975#endif
12976
12977 UnbridgedCastsSet UnbridgedCasts;
12978 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12979 *Result = ExprError();
12980 return true;
12981 }
12982
12983 // Add the functions denoted by the callee to the set of candidate
12984 // functions, including those from argument-dependent lookup.
12985 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12986
12987 if (getLangOpts().MSVCCompat &&
12988 CurContext->isDependentContext() && !isSFINAEContext() &&
12989 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12990
12991 OverloadCandidateSet::iterator Best;
12992 if (CandidateSet->empty() ||
12993 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12994 OR_No_Viable_Function) {
12995 // In Microsoft mode, if we are inside a template class member function
12996 // then create a type dependent CallExpr. The goal is to postpone name
12997 // lookup to instantiation time to be able to search into type dependent
12998 // base classes.
12999 CallExpr *CE =
13000 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue,
13001 RParenLoc, CurFPFeatureOverrides());
13002 CE->markDependentForPostponedNameLookup();
13003 *Result = CE;
13004 return true;
13005 }
13006 }
13007
13008 if (CandidateSet->empty())
13009 return false;
13010
13011 UnbridgedCasts.restore();
13012 return false;
13013}
13014
13015// Guess at what the return type for an unresolvable overload should be.
13016static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13017 OverloadCandidateSet::iterator *Best) {
13018 llvm::Optional<QualType> Result;
13019 // Adjust Type after seeing a candidate.
13020 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13021 if (!Candidate.Function)
13022 return;
13023 if (Candidate.Function->isInvalidDecl())
13024 return;
13025 QualType T = Candidate.Function->getReturnType();
13026 if (T.isNull())
13027 return;
13028 if (!Result)
13029 Result = T;
13030 else if (Result != T)
13031 Result = QualType();
13032 };
13033
13034 // Look for an unambiguous type from a progressively larger subset.
13035 // e.g. if types disagree, but all *viable* overloads return int, choose int.
13036 //
13037 // First, consider only the best candidate.
13038 if (Best && *Best != CS.end())
13039 ConsiderCandidate(**Best);
13040 // Next, consider only viable candidates.
13041 if (!Result)
13042 for (const auto &C : CS)
13043 if (C.Viable)
13044 ConsiderCandidate(C);
13045 // Finally, consider all candidates.
13046 if (!Result)
13047 for (const auto &C : CS)
13048 ConsiderCandidate(C);
13049
13050 if (!Result)
13051 return QualType();
13052 auto Value = Result.getValue();
13053 if (Value.isNull() || Value->isUndeducedType())
13054 return QualType();
13055 return Value;
13056}
13057
13058/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13059/// the completed call expression. If overload resolution fails, emits
13060/// diagnostics and returns ExprError()
13061static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13062 UnresolvedLookupExpr *ULE,
13063 SourceLocation LParenLoc,
13064 MultiExprArg Args,
13065 SourceLocation RParenLoc,
13066 Expr *ExecConfig,
13067 OverloadCandidateSet *CandidateSet,
13068 OverloadCandidateSet::iterator *Best,
13069 OverloadingResult OverloadResult,
13070 bool AllowTypoCorrection) {
13071 switch (OverloadResult) {
13072 case OR_Success: {
13073 FunctionDecl *FDecl = (*Best)->Function;
13074 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13075 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13076 return ExprError();
13077 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13078 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13079 ExecConfig, /*IsExecConfig=*/false,
13080 (*Best)->IsADLCandidate);
13081 }
13082
13083 case OR_No_Viable_Function: {
13084 // Try to recover by looking for viable functions which the user might
13085 // have meant to call.
13086 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13087 Args, RParenLoc,
13088 CandidateSet->empty(),
13089 AllowTypoCorrection);
13090 if (Recovery.isInvalid() || Recovery.isUsable())
13091 return Recovery;
13092
13093 // If the user passes in a function that we can't take the address of, we
13094 // generally end up emitting really bad error messages. Here, we attempt to
13095 // emit better ones.
13096 for (const Expr *Arg : Args) {
13097 if (!Arg->getType()->isFunctionType())
13098 continue;
13099 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13100 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13101 if (FD &&
13102 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13103 Arg->getExprLoc()))
13104 return ExprError();
13105 }
13106 }
13107
13108 CandidateSet->NoteCandidates(
13109 PartialDiagnosticAt(
13110 Fn->getBeginLoc(),
13111 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13112 << ULE->getName() << Fn->getSourceRange()),
13113 SemaRef, OCD_AllCandidates, Args);
13114 break;
13115 }
13116
13117 case OR_Ambiguous:
13118 CandidateSet->NoteCandidates(
13119 PartialDiagnosticAt(Fn->getBeginLoc(),
13120 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13121 << ULE->getName() << Fn->getSourceRange()),
13122 SemaRef, OCD_AmbiguousCandidates, Args);
13123 break;
13124
13125 case OR_Deleted: {
13126 CandidateSet->NoteCandidates(
13127 PartialDiagnosticAt(Fn->getBeginLoc(),
13128 SemaRef.PDiag(diag::err_ovl_deleted_call)
13129 << ULE->getName() << Fn->getSourceRange()),
13130 SemaRef, OCD_AllCandidates, Args);
13131
13132 // We emitted an error for the unavailable/deleted function call but keep
13133 // the call in the AST.
13134 FunctionDecl *FDecl = (*Best)->Function;
13135 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13136 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13137 ExecConfig, /*IsExecConfig=*/false,
13138 (*Best)->IsADLCandidate);
13139 }
13140 }
13141
13142 // Overload resolution failed, try to recover.
13143 SmallVector<Expr *, 8> SubExprs = {Fn};
13144 SubExprs.append(Args.begin(), Args.end());
13145 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13146 chooseRecoveryType(*CandidateSet, Best));
13147}
13148
13149static void markUnaddressableCandidatesUnviable(Sema &S,
13150 OverloadCandidateSet &CS) {
13151 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13152 if (I->Viable &&
13153 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13154 I->Viable = false;
13155 I->FailureKind = ovl_fail_addr_not_available;
13156 }
13157 }
13158}
13159
13160/// BuildOverloadedCallExpr - Given the call expression that calls Fn
13161/// (which eventually refers to the declaration Func) and the call
13162/// arguments Args/NumArgs, attempt to resolve the function call down
13163/// to a specific function. If overload resolution succeeds, returns
13164/// the call expression produced by overload resolution.
13165/// Otherwise, emits diagnostics and returns ExprError.
13166ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13167 UnresolvedLookupExpr *ULE,
13168 SourceLocation LParenLoc,
13169 MultiExprArg Args,
13170 SourceLocation RParenLoc,
13171 Expr *ExecConfig,
13172 bool AllowTypoCorrection,
13173 bool CalleesAddressIsTaken) {
13174 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13175 OverloadCandidateSet::CSK_Normal);
13176 ExprResult result;
13177
13178 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13179 &result))
13180 return result;
13181
13182 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13183 // functions that aren't addressible are considered unviable.
13184 if (CalleesAddressIsTaken)
13185 markUnaddressableCandidatesUnviable(*this, CandidateSet);
13186
13187 OverloadCandidateSet::iterator Best;
13188 OverloadingResult OverloadResult =
13189 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13190
13191 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13192 ExecConfig, &CandidateSet, &Best,
13193 OverloadResult, AllowTypoCorrection);
13194}
13195
13196static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13197 return Functions.size() > 1 ||
13198 (Functions.size() == 1 &&
13199 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13200}
13201
13202ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13203 NestedNameSpecifierLoc NNSLoc,
13204 DeclarationNameInfo DNI,
13205 const UnresolvedSetImpl &Fns,
13206 bool PerformADL) {
13207 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13208 PerformADL, IsOverloaded(Fns),
13209 Fns.begin(), Fns.end());
13210}
13211
13212/// Create a unary operation that may resolve to an overloaded
13213/// operator.
13214///
13215/// \param OpLoc The location of the operator itself (e.g., '*').
13216///
13217/// \param Opc The UnaryOperatorKind that describes this operator.
13218///
13219/// \param Fns The set of non-member functions that will be
13220/// considered by overload resolution. The caller needs to build this
13221/// set based on the context using, e.g.,
13222/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13223/// set should not contain any member functions; those will be added
13224/// by CreateOverloadedUnaryOp().
13225///
13226/// \param Input The input argument.
13227ExprResult
13228Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13229 const UnresolvedSetImpl &Fns,
13230 Expr *Input, bool PerformADL) {
13231 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13232 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")((Op != OO_None && "Invalid opcode for overloaded unary operator"
) ? static_cast<void> (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 13232, __PRETTY_FUNCTION__))
;
13233 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13234 // TODO: provide better source location info.
13235 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13236
13237 if (checkPlaceholderForOverload(*this, Input))
13238 return ExprError();
13239
13240 Expr *Args[2] = { Input, nullptr };
13241 unsigned NumArgs = 1;
13242
13243 // For post-increment and post-decrement, add the implicit '0' as
13244 // the second argument, so that we know this is a post-increment or
13245 // post-decrement.
13246 if (Opc == UO_PostInc || Opc == UO_PostDec) {
13247 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13248 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13249 SourceLocation());
13250 NumArgs = 2;
13251 }
13252
13253 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13254
13255 if (Input->isTypeDependent()) {
13256 if (Fns.empty())
13257 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13258 VK_RValue, OK_Ordinary, OpLoc, false,
13259 CurFPFeatureOverrides());
13260
13261 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13262 ExprResult Fn = CreateUnresolvedLookupExpr(
13263 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13264 if (Fn.isInvalid())
13265 return ExprError();
13266 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13267 Context.DependentTy, VK_RValue, OpLoc,
13268 CurFPFeatureOverrides());
13269 }
13270
13271 // Build an empty overload set.
13272 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13273
13274 // Add the candidates from the given function set.
13275 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13276
13277 // Add operator candidates that are member functions.
13278 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13279
13280 // Add candidates from ADL.
13281 if (PerformADL) {
13282 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13283 /*ExplicitTemplateArgs*/nullptr,
13284 CandidateSet);
13285 }
13286
13287 // Add builtin operator candidates.
13288 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13289
13290 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13291
13292 // Perform overload resolution.
13293 OverloadCandidateSet::iterator Best;
13294 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13295 case OR_Success: {
13296 // We found a built-in operator or an overloaded operator.
13297 FunctionDecl *FnDecl = Best->Function;
13298
13299 if (FnDecl) {
13300 Expr *Base = nullptr;
13301 // We matched an overloaded operator. Build a call to that
13302 // operator.
13303
13304 // Convert the arguments.
13305 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13306 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13307
13308 ExprResult InputRes =
13309 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13310 Best->FoundDecl, Method);
13311 if (InputRes.isInvalid())
13312 return ExprError();
13313 Base = Input = InputRes.get();
13314 } else {
13315 // Convert the arguments.
13316 ExprResult InputInit
13317 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13318 Context,
13319 FnDecl->getParamDecl(0)),
13320 SourceLocation(),
13321 Input);
13322 if (InputInit.isInvalid())
13323 return ExprError();
13324 Input = InputInit.get();
13325 }
13326
13327 // Build the actual expression node.
13328 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13329 Base, HadMultipleCandidates,
13330 OpLoc);
13331 if (FnExpr.isInvalid())
13332 return ExprError();
13333
13334 // Determine the result type.
13335 QualType ResultTy = FnDecl->getReturnType();
13336 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13337 ResultTy = ResultTy.getNonLValueExprType(Context);
13338
13339 Args[0] = Input;
13340 CallExpr *TheCall = CXXOperatorCallExpr::Create(
13341 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13342 CurFPFeatureOverrides(), Best->IsADLCandidate);
13343
13344 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13345 return ExprError();
13346
13347 if (CheckFunctionCall(FnDecl, TheCall,
13348 FnDecl->getType()->castAs<FunctionProtoType>()))
13349 return ExprError();
13350 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13351 } else {
13352 // We matched a built-in operator. Convert the arguments, then
13353 // break out so that we will build the appropriate built-in
13354 // operator node.
13355 ExprResult InputRes = PerformImplicitConversion(
13356 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13357 CCK_ForBuiltinOverloadedOp);
13358 if (InputRes.isInvalid())
13359 return ExprError();
13360 Input = InputRes.get();
13361 break;
13362 }
13363 }
13364
13365 case OR_No_Viable_Function:
13366 // This is an erroneous use of an operator which can be overloaded by
13367 // a non-member function. Check for non-member operators which were
13368 // defined too late to be candidates.
13369 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13370 // FIXME: Recover by calling the found function.
13371 return ExprError();
13372
13373 // No viable function; fall through to handling this as a
13374 // built-in operator, which will produce an error message for us.
13375 break;
13376
13377 case OR_Ambiguous:
13378 CandidateSet.NoteCandidates(
13379 PartialDiagnosticAt(OpLoc,
13380 PDiag(diag::err_ovl_ambiguous_oper_unary)
13381 << UnaryOperator::getOpcodeStr(Opc)
13382 << Input->getType() << Input->getSourceRange()),
13383 *this, OCD_AmbiguousCandidates, ArgsArray,
13384 UnaryOperator::getOpcodeStr(Opc), OpLoc);
13385 return ExprError();
13386
13387 case OR_Deleted:
13388 CandidateSet.NoteCandidates(
13389 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13390 << UnaryOperator::getOpcodeStr(Opc)
13391 << Input->getSourceRange()),
13392 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13393 OpLoc);
13394 return ExprError();
13395 }
13396
13397 // Either we found no viable overloaded operator or we matched a
13398 // built-in operator. In either case, fall through to trying to
13399 // build a built-in operation.
13400 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13401}
13402
13403/// Perform lookup for an overloaded binary operator.
13404void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13405 OverloadedOperatorKind Op,
13406 const UnresolvedSetImpl &Fns,
13407 ArrayRef<Expr *> Args, bool PerformADL) {
13408 SourceLocation OpLoc = CandidateSet.getLocation();
13409
13410 OverloadedOperatorKind ExtraOp =
13411 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13412 ? getRewrittenOverloadedOperator(Op)
13413 : OO_None;
13414
13415 // Add the candidates from the given function set. This also adds the
13416 // rewritten candidates using these functions if necessary.
13417 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13418
13419 // Add operator candidates that are member functions.
13420 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13421 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13422 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13423 OverloadCandidateParamOrder::Reversed);
13424
13425 // In C++20, also add any rewritten member candidates.
13426 if (ExtraOp) {
13427 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13428 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13429 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13430 CandidateSet,
13431 OverloadCandidateParamOrder::Reversed);
13432 }
13433
13434 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13435 // performed for an assignment operator (nor for operator[] nor operator->,
13436 // which don't get here).
13437 if (Op != OO_Equal && PerformADL) {
13438 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13439 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13440 /*ExplicitTemplateArgs*/ nullptr,
13441 CandidateSet);
13442 if (ExtraOp) {
13443 DeclarationName ExtraOpName =
13444 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13445 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13446 /*ExplicitTemplateArgs*/ nullptr,
13447 CandidateSet);
13448 }
13449 }
13450
13451 // Add builtin operator candidates.
13452 //
13453 // FIXME: We don't add any rewritten candidates here. This is strictly
13454 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13455 // resulting in our selecting a rewritten builtin candidate. For example:
13456 //
13457 // enum class E { e };
13458 // bool operator!=(E, E) requires false;
13459 // bool k = E::e != E::e;
13460 //
13461 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13462 // it seems unreasonable to consider rewritten builtin candidates. A core
13463 // issue has been filed proposing to removed this requirement.
13464 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13465}
13466
13467/// Create a binary operation that may resolve to an overloaded
13468/// operator.
13469///
13470/// \param OpLoc The location of the operator itself (e.g., '+').
13471///
13472/// \param Opc The BinaryOperatorKind that describes this operator.
13473///
13474/// \param Fns The set of non-member functions that will be
13475/// considered by overload resolution. The caller needs to build this
13476/// set based on the context using, e.g.,
13477/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13478/// set should not contain any member functions; those will be added
13479/// by CreateOverloadedBinOp().
13480///
13481/// \param LHS Left-hand argument.
13482/// \param RHS Right-hand argument.
13483/// \param PerformADL Whether to consider operator candidates found by ADL.
13484/// \param AllowRewrittenCandidates Whether to consider candidates found by
13485/// C++20 operator rewrites.
13486/// \param DefaultedFn If we are synthesizing a defaulted operator function,
13487/// the function in question. Such a function is never a candidate in
13488/// our overload resolution. This also enables synthesizing a three-way
13489/// comparison from < and == as described in C++20 [class.spaceship]p1.
13490ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13491 BinaryOperatorKind Opc,
13492 const UnresolvedSetImpl &Fns, Expr *LHS,
13493 Expr *RHS, bool PerformADL,
13494 bool AllowRewrittenCandidates,
13495 FunctionDecl *DefaultedFn) {
13496 Expr *Args[2] = { LHS, RHS };
13497 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13498
13499 if (!getLangOpts().CPlusPlus20)
13500 AllowRewrittenCandidates = false;
13501
13502 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13503
13504 // If either side is type-dependent, create an appropriate dependent
13505 // expression.
13506 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13507 if (Fns.empty()) {
13508 // If there are no functions to store, just build a dependent
13509 // BinaryOperator or CompoundAssignment.
13510 if (BinaryOperator::isCompoundAssignmentOp(Opc))
13511 return CompoundAssignOperator::Create(
13512 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13513 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13514 Context.DependentTy);
13515 return BinaryOperator::Create(Context, Args[0], Args[1], Opc,
13516 Context.DependentTy, VK_RValue, OK_Ordinary,
13517 OpLoc, CurFPFeatureOverrides());
13518 }
13519
13520 // FIXME: save results of ADL from here?
13521 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13522 // TODO: provide better source location info in DNLoc component.
13523 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13524 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13525 ExprResult Fn = CreateUnresolvedLookupExpr(
13526 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13527 if (Fn.isInvalid())
13528 return ExprError();
13529 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13530 Context.DependentTy, VK_RValue, OpLoc,
13531 CurFPFeatureOverrides());
13532 }
13533
13534 // Always do placeholder-like conversions on the RHS.
13535 if (checkPlaceholderForOverload(*this, Args[1]))
13536 return ExprError();
13537
13538 // Do placeholder-like conversion on the LHS; note that we should
13539 // not get here with a PseudoObject LHS.
13540 assert(Args[0]->getObjectKind() != OK_ObjCProperty)((Args[0]->getObjectKind() != OK_ObjCProperty) ? static_cast
<void> (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 13540, __PRETTY_FUNCTION__))
;
13541 if (checkPlaceholderForOverload(*this, Args[0]))
13542 return ExprError();
13543
13544 // If this is the assignment operator, we only perform overload resolution
13545 // if the left-hand side is a class or enumeration type. This is actually
13546 // a hack. The standard requires that we do overload resolution between the
13547 // various built-in candidates, but as DR507 points out, this can lead to
13548 // problems. So we do it this way, which pretty much follows what GCC does.
13549 // Note that we go the traditional code path for compound assignment forms.
13550 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13551 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13552
13553 // If this is the .* operator, which is not overloadable, just
13554 // create a built-in binary operator.
13555 if (Opc == BO_PtrMemD)
13556 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13557
13558 // Build the overload set.
13559 OverloadCandidateSet CandidateSet(
13560 OpLoc, OverloadCandidateSet::CSK_Operator,
13561 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13562 if (DefaultedFn)
13563 CandidateSet.exclude(DefaultedFn);
13564 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13565
13566 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13567
13568 // Perform overload resolution.
13569 OverloadCandidateSet::iterator Best;
13570 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13571 case OR_Success: {
13572 // We found a built-in operator or an overloaded operator.
13573 FunctionDecl *FnDecl = Best->Function;
13574
13575 bool IsReversed = Best->isReversed();
13576 if (IsReversed)
13577 std::swap(Args[0], Args[1]);
13578
13579 if (FnDecl) {
13580 Expr *Base = nullptr;
13581 // We matched an overloaded operator. Build a call to that
13582 // operator.
13583
13584 OverloadedOperatorKind ChosenOp =
13585 FnDecl->getDeclName().getCXXOverloadedOperator();
13586
13587 // C++2a [over.match.oper]p9:
13588 // If a rewritten operator== candidate is selected by overload
13589 // resolution for an operator@, its return type shall be cv bool
13590 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13591 !FnDecl->getReturnType()->isBooleanType()) {
13592 bool IsExtension =
13593 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13594 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13595 : diag::err_ovl_rewrite_equalequal_not_bool)
13596 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13597 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13598 Diag(FnDecl->getLocation(), diag::note_declared_at);
13599 if (!IsExtension)
13600 return ExprError();
13601 }
13602
13603 if (AllowRewrittenCandidates && !IsReversed &&
13604 CandidateSet.getRewriteInfo().isReversible()) {
13605 // We could have reversed this operator, but didn't. Check if some
13606 // reversed form was a viable candidate, and if so, if it had a
13607 // better conversion for either parameter. If so, this call is
13608 // formally ambiguous, and allowing it is an extension.
13609 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13610 for (OverloadCandidate &Cand : CandidateSet) {
13611 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13612 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13613 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13614 if (CompareImplicitConversionSequences(
13615 *this, OpLoc, Cand.Conversions[ArgIdx],
13616 Best->Conversions[ArgIdx]) ==
13617 ImplicitConversionSequence::Better) {
13618 AmbiguousWith.push_back(Cand.Function);
13619 break;
13620 }
13621 }
13622 }
13623 }
13624
13625 if (!AmbiguousWith.empty()) {
13626 bool AmbiguousWithSelf =
13627 AmbiguousWith.size() == 1 &&
13628 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13629 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13630 << BinaryOperator::getOpcodeStr(Opc)
13631 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13632 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13633 if (AmbiguousWithSelf) {
13634 Diag(FnDecl->getLocation(),
13635 diag::note_ovl_ambiguous_oper_binary_reversed_self);
13636 } else {
13637 Diag(FnDecl->getLocation(),
13638 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13639 for (auto *F : AmbiguousWith)
13640 Diag(F->getLocation(),
13641 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13642 }
13643 }
13644 }
13645
13646 // Convert the arguments.
13647 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13648 // Best->Access is only meaningful for class members.
13649 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13650
13651 ExprResult Arg1 =
13652 PerformCopyInitialization(
13653 InitializedEntity::InitializeParameter(Context,
13654 FnDecl->getParamDecl(0)),
13655 SourceLocation(), Args[1]);
13656 if (Arg1.isInvalid())
13657 return ExprError();
13658
13659 ExprResult Arg0 =
13660 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13661 Best->FoundDecl, Method);
13662 if (Arg0.isInvalid())
13663 return ExprError();
13664 Base = Args[0] = Arg0.getAs<Expr>();
13665 Args[1] = RHS = Arg1.getAs<Expr>();
13666 } else {
13667 // Convert the arguments.
13668 ExprResult Arg0 = PerformCopyInitialization(
13669 InitializedEntity::InitializeParameter(Context,
13670 FnDecl->getParamDecl(0)),
13671 SourceLocation(), Args[0]);
13672 if (Arg0.isInvalid())
13673 return ExprError();
13674
13675 ExprResult Arg1 =
13676 PerformCopyInitialization(
13677 InitializedEntity::InitializeParameter(Context,
13678 FnDecl->getParamDecl(1)),
13679 SourceLocation(), Args[1]);
13680 if (Arg1.isInvalid())
13681 return ExprError();
13682 Args[0] = LHS = Arg0.getAs<Expr>();
13683 Args[1] = RHS = Arg1.getAs<Expr>();
13684 }
13685
13686 // Build the actual expression node.
13687 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13688 Best->FoundDecl, Base,
13689 HadMultipleCandidates, OpLoc);
13690 if (FnExpr.isInvalid())
13691 return ExprError();
13692
13693 // Determine the result type.
13694 QualType ResultTy = FnDecl->getReturnType();
13695 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13696 ResultTy = ResultTy.getNonLValueExprType(Context);
13697
13698 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13699 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13700 CurFPFeatureOverrides(), Best->IsADLCandidate);
13701
13702 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13703 FnDecl))
13704 return ExprError();
13705
13706 ArrayRef<const Expr *> ArgsArray(Args, 2);
13707 const Expr *ImplicitThis = nullptr;
13708 // Cut off the implicit 'this'.
13709 if (isa<CXXMethodDecl>(FnDecl)) {
13710 ImplicitThis = ArgsArray[0];
13711 ArgsArray = ArgsArray.slice(1);
13712 }
13713
13714 // Check for a self move.
13715 if (Op == OO_Equal)
13716 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13717
13718 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13719 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13720 VariadicDoesNotApply);
13721
13722 ExprResult R = MaybeBindToTemporary(TheCall);
13723 if (R.isInvalid())
13724 return ExprError();
13725
13726 R = CheckForImmediateInvocation(R, FnDecl);
13727 if (R.isInvalid())
13728 return ExprError();
13729
13730 // For a rewritten candidate, we've already reversed the arguments
13731 // if needed. Perform the rest of the rewrite now.
13732 if ((Best->RewriteKind & CRK_DifferentOperator) ||
13733 (Op == OO_Spaceship && IsReversed)) {
13734 if (Op == OO_ExclaimEqual) {
13735 assert(ChosenOp == OO_EqualEqual && "unexpected operator name")((ChosenOp == OO_EqualEqual && "unexpected operator name"
) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_EqualEqual && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 13735, __PRETTY_FUNCTION__))
;
13736 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13737 } else {
13738 assert(ChosenOp == OO_Spaceship && "unexpected operator name")((ChosenOp == OO_Spaceship && "unexpected operator name"
) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_Spaceship && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 13738, __PRETTY_FUNCTION__))
;
13739 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13740 Expr *ZeroLiteral =
13741 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13742
13743 Sema::CodeSynthesisContext Ctx;
13744 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13745 Ctx.Entity = FnDecl;
13746 pushCodeSynthesisContext(Ctx);
13747
13748 R = CreateOverloadedBinOp(
13749 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13750 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13751 /*AllowRewrittenCandidates=*/false);
13752
13753 popCodeSynthesisContext();
13754 }
13755 if (R.isInvalid())
13756 return ExprError();
13757 } else {
13758 assert(ChosenOp == Op && "unexpected operator name")((ChosenOp == Op && "unexpected operator name") ? static_cast
<void> (0) : __assert_fail ("ChosenOp == Op && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 13758, __PRETTY_FUNCTION__))
;
13759 }
13760
13761 // Make a note in the AST if we did any rewriting.
13762 if (Best->RewriteKind != CRK_None)
13763 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13764
13765 return R;
13766 } else {
13767 // We matched a built-in operator. Convert the arguments, then
13768 // break out so that we will build the appropriate built-in
13769 // operator node.
13770 ExprResult ArgsRes0 = PerformImplicitConversion(
13771 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13772 AA_Passing, CCK_ForBuiltinOverloadedOp);
13773 if (ArgsRes0.isInvalid())
13774 return ExprError();
13775 Args[0] = ArgsRes0.get();
13776
13777 ExprResult ArgsRes1 = PerformImplicitConversion(
13778 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13779 AA_Passing, CCK_ForBuiltinOverloadedOp);
13780 if (ArgsRes1.isInvalid())
13781 return ExprError();
13782 Args[1] = ArgsRes1.get();
13783 break;
13784 }
13785 }
13786
13787 case OR_No_Viable_Function: {
13788 // C++ [over.match.oper]p9:
13789 // If the operator is the operator , [...] and there are no
13790 // viable functions, then the operator is assumed to be the
13791 // built-in operator and interpreted according to clause 5.
13792 if (Opc == BO_Comma)
13793 break;
13794
13795 // When defaulting an 'operator<=>', we can try to synthesize a three-way
13796 // compare result using '==' and '<'.
13797 if (DefaultedFn && Opc == BO_Cmp) {
13798 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13799 Args[1], DefaultedFn);
13800 if (E.isInvalid() || E.isUsable())
13801 return E;
13802 }
13803
13804 // For class as left operand for assignment or compound assignment
13805 // operator do not fall through to handling in built-in, but report that
13806 // no overloaded assignment operator found
13807 ExprResult Result = ExprError();
13808 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13809 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13810 Args, OpLoc);
13811 if (Args[0]->getType()->isRecordType() &&
13812 Opc >= BO_Assign && Opc <= BO_OrAssign) {
13813 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13814 << BinaryOperator::getOpcodeStr(Opc)
13815 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13816 if (Args[0]->getType()->isIncompleteType()) {
13817 Diag(OpLoc, diag::note_assign_lhs_incomplete)
13818 << Args[0]->getType()
13819 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13820 }
13821 } else {
13822 // This is an erroneous use of an operator which can be overloaded by
13823 // a non-member function. Check for non-member operators which were
13824 // defined too late to be candidates.
13825 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13826 // FIXME: Recover by calling the found function.
13827 return ExprError();
13828
13829 // No viable function; try to create a built-in operation, which will
13830 // produce an error. Then, show the non-viable candidates.
13831 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13832 }
13833 assert(Result.isInvalid() &&((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 13834, __PRETTY_FUNCTION__))
13834 "C++ binary operator overloading is missing candidates!")((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 13834, __PRETTY_FUNCTION__))
;
13835 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13836 return Result;
13837 }
13838
13839 case OR_Ambiguous:
13840 CandidateSet.NoteCandidates(
13841 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13842 << BinaryOperator::getOpcodeStr(Opc)
13843 << Args[0]->getType()
13844 << Args[1]->getType()
13845 << Args[0]->getSourceRange()
13846 << Args[1]->getSourceRange()),
13847 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13848 OpLoc);
13849 return ExprError();
13850
13851 case OR_Deleted:
13852 if (isImplicitlyDeleted(Best->Function)) {
13853 FunctionDecl *DeletedFD = Best->Function;
13854 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13855 if (DFK.isSpecialMember()) {
13856 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13857 << Args[0]->getType() << DFK.asSpecialMember();
13858 } else {
13859 assert(DFK.isComparison())((DFK.isComparison()) ? static_cast<void> (0) : __assert_fail
("DFK.isComparison()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 13859, __PRETTY_FUNCTION__))
;
13860 Diag(OpLoc, diag::err_ovl_deleted_comparison)
13861 << Args[0]->getType() << DeletedFD;
13862 }
13863
13864 // The user probably meant to call this special member. Just
13865 // explain why it's deleted.
13866 NoteDeletedFunction(DeletedFD);
13867 return ExprError();
13868 }
13869 CandidateSet.NoteCandidates(
13870 PartialDiagnosticAt(
13871 OpLoc, PDiag(diag::err_ovl_deleted_oper)
13872 << getOperatorSpelling(Best->Function->getDeclName()
13873 .getCXXOverloadedOperator())
13874 << Args[0]->getSourceRange()
13875 << Args[1]->getSourceRange()),
13876 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13877 OpLoc);
13878 return ExprError();
13879 }
13880
13881 // We matched a built-in operator; build it.
13882 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13883}
13884
13885ExprResult Sema::BuildSynthesizedThreeWayComparison(
13886 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13887 FunctionDecl *DefaultedFn) {
13888 const ComparisonCategoryInfo *Info =
13889 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13890 // If we're not producing a known comparison category type, we can't
13891 // synthesize a three-way comparison. Let the caller diagnose this.
13892 if (!Info)
13893 return ExprResult((Expr*)nullptr);
13894
13895 // If we ever want to perform this synthesis more generally, we will need to
13896 // apply the temporary materialization conversion to the operands.
13897 assert(LHS->isGLValue() && RHS->isGLValue() &&((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 13898, __PRETTY_FUNCTION__))
13898 "cannot use prvalue expressions more than once")((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 13898, __PRETTY_FUNCTION__))
;
13899 Expr *OrigLHS = LHS;
13900 Expr *OrigRHS = RHS;
13901
13902 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13903 // each of them multiple times below.
13904 LHS = new (Context)
13905 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13906 LHS->getObjectKind(), LHS);
13907 RHS = new (Context)
13908 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13909 RHS->getObjectKind(), RHS);
13910
13911 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13912 DefaultedFn);
13913 if (Eq.isInvalid())
13914 return ExprError();
13915
13916 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13917 true, DefaultedFn);
13918 if (Less.isInvalid())
13919 return ExprError();
13920
13921 ExprResult Greater;
13922 if (Info->isPartial()) {
13923 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13924 DefaultedFn);
13925 if (Greater.isInvalid())
13926 return ExprError();
13927 }
13928
13929 // Form the list of comparisons we're going to perform.
13930 struct Comparison {
13931 ExprResult Cmp;
13932 ComparisonCategoryResult Result;
13933 } Comparisons[4] =
13934 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13935 : ComparisonCategoryResult::Equivalent},
13936 {Less, ComparisonCategoryResult::Less},
13937 {Greater, ComparisonCategoryResult::Greater},
13938 {ExprResult(), ComparisonCategoryResult::Unordered},
13939 };
13940
13941 int I = Info->isPartial() ? 3 : 2;
13942
13943 // Combine the comparisons with suitable conditional expressions.
13944 ExprResult Result;
13945 for (; I >= 0; --I) {
13946 // Build a reference to the comparison category constant.
13947 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13948 // FIXME: Missing a constant for a comparison category. Diagnose this?
13949 if (!VI)
13950 return ExprResult((Expr*)nullptr);
13951 ExprResult ThisResult =
13952 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13953 if (ThisResult.isInvalid())
13954 return ExprError();
13955
13956 // Build a conditional unless this is the final case.
13957 if (Result.get()) {
13958 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13959 ThisResult.get(), Result.get());
13960 if (Result.isInvalid())
13961 return ExprError();
13962 } else {
13963 Result = ThisResult;
13964 }
13965 }
13966
13967 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13968 // bind the OpaqueValueExprs before they're (repeatedly) used.
13969 Expr *SyntacticForm = BinaryOperator::Create(
13970 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13971 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
13972 CurFPFeatureOverrides());
13973 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13974 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13975}
13976
13977ExprResult
13978Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13979 SourceLocation RLoc,
13980 Expr *Base, Expr *Idx) {
13981 Expr *Args[2] = { Base, Idx };
13982 DeclarationName OpName =
13983 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13984
13985 // If either side is type-dependent, create an appropriate dependent
13986 // expression.
13987 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13988
13989 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13990 // CHECKME: no 'operator' keyword?
13991 DeclarationNameInfo OpNameInfo(OpName, LLoc);
13992 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13993 ExprResult Fn = CreateUnresolvedLookupExpr(
13994 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
13995 if (Fn.isInvalid())
13996 return ExprError();
13997 // Can't add any actual overloads yet
13998
13999 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14000 Context.DependentTy, VK_RValue, RLoc,
14001 CurFPFeatureOverrides());
14002 }
14003
14004 // Handle placeholders on both operands.
14005 if (checkPlaceholderForOverload(*this, Args[0]))
14006 return ExprError();
14007 if (checkPlaceholderForOverload(*this, Args[1]))
14008 return ExprError();
14009
14010 // Build an empty overload set.
14011 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14012
14013 // Subscript can only be overloaded as a member function.
14014
14015 // Add operator candidates that are member functions.
14016 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14017
14018 // Add builtin operator candidates.
14019 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14020
14021 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14022
14023 // Perform overload resolution.
14024 OverloadCandidateSet::iterator Best;
14025 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14026 case OR_Success: {
14027 // We found a built-in operator or an overloaded operator.
14028 FunctionDecl *FnDecl = Best->Function;
14029
14030 if (FnDecl) {
14031 // We matched an overloaded operator. Build a call to that
14032 // operator.
14033
14034 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
14035
14036 // Convert the arguments.
14037 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14038 ExprResult Arg0 =
14039 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
14040 Best->FoundDecl, Method);
14041 if (Arg0.isInvalid())
14042 return ExprError();
14043 Args[0] = Arg0.get();
14044
14045 // Convert the arguments.
14046 ExprResult InputInit
14047 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14048 Context,
14049 FnDecl->getParamDecl(0)),
14050 SourceLocation(),
14051 Args[1]);
14052 if (InputInit.isInvalid())
14053 return ExprError();
14054
14055 Args[1] = InputInit.getAs<Expr>();
14056
14057 // Build the actual expression node.
14058 DeclarationNameInfo OpLocInfo(OpName, LLoc);
14059 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14060 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14061 Best->FoundDecl,
14062 Base,
14063 HadMultipleCandidates,
14064 OpLocInfo.getLoc(),
14065 OpLocInfo.getInfo());
14066 if (FnExpr.isInvalid())
14067 return ExprError();
14068
14069 // Determine the result type
14070 QualType ResultTy = FnDecl->getReturnType();
14071 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14072 ResultTy = ResultTy.getNonLValueExprType(Context);
14073
14074 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14075 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc,
14076 CurFPFeatureOverrides());
14077 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14078 return ExprError();
14079
14080 if (CheckFunctionCall(Method, TheCall,
14081 Method->getType()->castAs<FunctionProtoType>()))
14082 return ExprError();
14083
14084 return MaybeBindToTemporary(TheCall);
14085 } else {
14086 // We matched a built-in operator. Convert the arguments, then
14087 // break out so that we will build the appropriate built-in
14088 // operator node.
14089 ExprResult ArgsRes0 = PerformImplicitConversion(
14090 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14091 AA_Passing, CCK_ForBuiltinOverloadedOp);
14092 if (ArgsRes0.isInvalid())
14093 return ExprError();
14094 Args[0] = ArgsRes0.get();
14095
14096 ExprResult ArgsRes1 = PerformImplicitConversion(
14097 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14098 AA_Passing, CCK_ForBuiltinOverloadedOp);
14099 if (ArgsRes1.isInvalid())
14100 return ExprError();
14101 Args[1] = ArgsRes1.get();
14102
14103 break;
14104 }
14105 }
14106
14107 case OR_No_Viable_Function: {
14108 PartialDiagnostic PD = CandidateSet.empty()
14109 ? (PDiag(diag::err_ovl_no_oper)
14110 << Args[0]->getType() << /*subscript*/ 0
14111 << Args[0]->getSourceRange() << Args[1]->getSourceRange())
14112 : (PDiag(diag::err_ovl_no_viable_subscript)
14113 << Args[0]->getType() << Args[0]->getSourceRange()
14114 << Args[1]->getSourceRange());
14115 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14116 OCD_AllCandidates, Args, "[]", LLoc);
14117 return ExprError();
14118 }
14119
14120 case OR_Ambiguous:
14121 CandidateSet.NoteCandidates(
14122 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14123 << "[]" << Args[0]->getType()
14124 << Args[1]->getType()
14125 << Args[0]->getSourceRange()
14126 << Args[1]->getSourceRange()),
14127 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14128 return ExprError();
14129
14130 case OR_Deleted:
14131 CandidateSet.NoteCandidates(
14132 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14133 << "[]" << Args[0]->getSourceRange()
14134 << Args[1]->getSourceRange()),
14135 *this, OCD_AllCandidates, Args, "[]", LLoc);
14136 return ExprError();
14137 }
14138
14139 // We matched a built-in operator; build it.
14140 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14141}
14142
14143/// BuildCallToMemberFunction - Build a call to a member
14144/// function. MemExpr is the expression that refers to the member
14145/// function (and includes the object parameter), Args/NumArgs are the
14146/// arguments to the function call (not including the object
14147/// parameter). The caller needs to validate that the member
14148/// expression refers to a non-static member function or an overloaded
14149/// member function.
14150ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14151 SourceLocation LParenLoc,
14152 MultiExprArg Args,
14153 SourceLocation RParenLoc,
14154 bool AllowRecovery) {
14155 assert(MemExprE->getType() == Context.BoundMemberTy ||((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14156, __PRETTY_FUNCTION__))
14156 MemExprE->getType() == Context.OverloadTy)((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14156, __PRETTY_FUNCTION__))
;
14157
14158 // Dig out the member expression. This holds both the object
14159 // argument and the member function we're referring to.
14160 Expr *NakedMemExpr = MemExprE->IgnoreParens();
14161
14162 // Determine whether this is a call to a pointer-to-member function.
14163 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14164 assert(op->getType() == Context.BoundMemberTy)((op->getType() == Context.BoundMemberTy) ? static_cast<
void> (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14164, __PRETTY_FUNCTION__))
;
14165 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)((op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI
) ? static_cast<void> (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14165, __PRETTY_FUNCTION__))
;
14166
14167 QualType fnType =
14168 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14169
14170 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14171 QualType resultType = proto->getCallResultType(Context);
14172 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14173
14174 // Check that the object type isn't more qualified than the
14175 // member function we're calling.
14176 Qualifiers funcQuals = proto->getMethodQuals();
14177
14178 QualType objectType = op->getLHS()->getType();
14179 if (op->getOpcode() == BO_PtrMemI)
14180 objectType = objectType->castAs<PointerType>()->getPointeeType();
14181 Qualifiers objectQuals = objectType.getQualifiers();
14182
14183 Qualifiers difference = objectQuals - funcQuals;
14184 difference.removeObjCGCAttr();
14185 difference.removeAddressSpace();
14186 if (difference) {
14187 std::string qualsString = difference.getAsString();
14188 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14189 << fnType.getUnqualifiedType()
14190 << qualsString
14191 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14192 }
14193
14194 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14195 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14196 CurFPFeatureOverrides(), proto->getNumParams());
14197
14198 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14199 call, nullptr))
14200 return ExprError();
14201
14202 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14203 return ExprError();
14204
14205 if (CheckOtherCall(call, proto))
14206 return ExprError();
14207
14208 return MaybeBindToTemporary(call);
14209 }
14210
14211 // We only try to build a recovery expr at this level if we can preserve
14212 // the return type, otherwise we return ExprError() and let the caller
14213 // recover.
14214 auto BuildRecoveryExpr = [&](QualType Type) {
14215 if (!AllowRecovery)
14216 return ExprError();
14217 std::vector<Expr *> SubExprs = {MemExprE};
14218 llvm::for_each(Args, [&SubExprs](Expr *E) { SubExprs.push_back(E); });
14219 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14220 Type);
14221 };
14222 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14223 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
14224 RParenLoc, CurFPFeatureOverrides());
14225
14226 UnbridgedCastsSet UnbridgedCasts;
14227 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14228 return ExprError();
14229
14230 MemberExpr *MemExpr;
14231 CXXMethodDecl *Method = nullptr;
14232 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14233 NestedNameSpecifier *Qualifier = nullptr;
14234 if (isa<MemberExpr>(NakedMemExpr)) {
14235 MemExpr = cast<MemberExpr>(NakedMemExpr);
14236 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14237 FoundDecl = MemExpr->getFoundDecl();
14238 Qualifier = MemExpr->getQualifier();
14239 UnbridgedCasts.restore();
14240 } else {
14241 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14242 Qualifier = UnresExpr->getQualifier();
14243
14244 QualType ObjectType = UnresExpr->getBaseType();
14245 Expr::Classification ObjectClassification
14246 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14247 : UnresExpr->getBase()->Classify(Context);
14248
14249 // Add overload candidates
14250 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14251 OverloadCandidateSet::CSK_Normal);
14252
14253 // FIXME: avoid copy.
14254 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14255 if (UnresExpr->hasExplicitTemplateArgs()) {
14256 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14257 TemplateArgs = &TemplateArgsBuffer;
14258 }
14259
14260 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14261 E = UnresExpr->decls_end(); I != E; ++I) {
14262
14263 NamedDecl *Func = *I;
14264 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14265 if (isa<UsingShadowDecl>(Func))
14266 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14267
14268
14269 // Microsoft supports direct constructor calls.
14270 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14271 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14272 CandidateSet,
14273 /*SuppressUserConversions*/ false);
14274 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14275 // If explicit template arguments were provided, we can't call a
14276 // non-template member function.
14277 if (TemplateArgs)
14278 continue;
14279
14280 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14281 ObjectClassification, Args, CandidateSet,
14282 /*SuppressUserConversions=*/false);
14283 } else {
14284 AddMethodTemplateCandidate(
14285 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14286 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14287 /*SuppressUserConversions=*/false);
14288 }
14289 }
14290
14291 DeclarationName DeclName = UnresExpr->getMemberName();
14292
14293 UnbridgedCasts.restore();
14294
14295 OverloadCandidateSet::iterator Best;
14296 bool Succeeded = false;
14297 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14298 Best)) {
14299 case OR_Success:
14300 Method = cast<CXXMethodDecl>(Best->Function);
14301 FoundDecl = Best->FoundDecl;
14302 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14303 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14304 break;
14305 // If FoundDecl is different from Method (such as if one is a template
14306 // and the other a specialization), make sure DiagnoseUseOfDecl is
14307 // called on both.
14308 // FIXME: This would be more comprehensively addressed by modifying
14309 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14310 // being used.
14311 if (Method != FoundDecl.getDecl() &&
14312 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14313 break;
14314 Succeeded = true;
14315 break;
14316
14317 case OR_No_Viable_Function:
14318 CandidateSet.NoteCandidates(
14319 PartialDiagnosticAt(
14320 UnresExpr->getMemberLoc(),
14321 PDiag(diag::err_ovl_no_viable_member_function_in_call)
14322 << DeclName << MemExprE->getSourceRange()),
14323 *this, OCD_AllCandidates, Args);
14324 break;
14325 case OR_Ambiguous:
14326 CandidateSet.NoteCandidates(
14327 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14328 PDiag(diag::err_ovl_ambiguous_member_call)
14329 << DeclName << MemExprE->getSourceRange()),
14330 *this, OCD_AmbiguousCandidates, Args);
14331 break;
14332 case OR_Deleted:
14333 CandidateSet.NoteCandidates(
14334 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14335 PDiag(diag::err_ovl_deleted_member_call)
14336 << DeclName << MemExprE->getSourceRange()),
14337 *this, OCD_AllCandidates, Args);
14338 break;
14339 }
14340 // Overload resolution fails, try to recover.
14341 if (!Succeeded)
14342 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14343
14344 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14345
14346 // If overload resolution picked a static member, build a
14347 // non-member call based on that function.
14348 if (Method->isStatic()) {
14349 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
14350 RParenLoc);
14351 }
14352
14353 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14354 }
14355
14356 QualType ResultType = Method->getReturnType();
14357 ExprValueKind VK = Expr::getValueKindForType(ResultType);
14358 ResultType = ResultType.getNonLValueExprType(Context);
14359
14360 assert(Method && "Member call to something that isn't a method?")((Method && "Member call to something that isn't a method?"
) ? static_cast<void> (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14360, __PRETTY_FUNCTION__))
;
14361 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14362 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14363 Context, MemExprE, Args, ResultType, VK, RParenLoc,
14364 CurFPFeatureOverrides(), Proto->getNumParams());
14365
14366 // Check for a valid return type.
14367 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14368 TheCall, Method))
14369 return BuildRecoveryExpr(ResultType);
14370
14371 // Convert the object argument (for a non-static member function call).
14372 // We only need to do this if there was actually an overload; otherwise
14373 // it was done at lookup.
14374 if (!Method->isStatic()) {
14375 ExprResult ObjectArg =
14376 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14377 FoundDecl, Method);
14378 if (ObjectArg.isInvalid())
14379 return ExprError();
14380 MemExpr->setBase(ObjectArg.get());
14381 }
14382
14383 // Convert the rest of the arguments
14384 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14385 RParenLoc))
14386 return BuildRecoveryExpr(ResultType);
14387
14388 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14389
14390 if (CheckFunctionCall(Method, TheCall, Proto))
14391 return ExprError();
14392
14393 // In the case the method to call was not selected by the overloading
14394 // resolution process, we still need to handle the enable_if attribute. Do
14395 // that here, so it will not hide previous -- and more relevant -- errors.
14396 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14397 if (const EnableIfAttr *Attr =
14398 CheckEnableIf(Method, LParenLoc, Args, true)) {
14399 Diag(MemE->getMemberLoc(),
14400 diag::err_ovl_no_viable_member_function_in_call)
14401 << Method << Method->getSourceRange();
14402 Diag(Method->getLocation(),
14403 diag::note_ovl_candidate_disabled_by_function_cond_attr)
14404 << Attr->getCond()->getSourceRange() << Attr->getMessage();
14405 return ExprError();
14406 }
14407 }
14408
14409 if ((isa<CXXConstructorDecl>(CurContext) ||
14410 isa<CXXDestructorDecl>(CurContext)) &&
14411 TheCall->getMethodDecl()->isPure()) {
14412 const CXXMethodDecl *MD = TheCall->getMethodDecl();
14413
14414 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14415 MemExpr->performsVirtualDispatch(getLangOpts())) {
14416 Diag(MemExpr->getBeginLoc(),
14417 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14418 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14419 << MD->getParent();
14420
14421 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14422 if (getLangOpts().AppleKext)
14423 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14424 << MD->getParent() << MD->getDeclName();
14425 }
14426 }
14427
14428 if (CXXDestructorDecl *DD =
14429 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14430 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14431 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14432 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14433 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14434 MemExpr->getMemberLoc());
14435 }
14436
14437 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14438 TheCall->getMethodDecl());
14439}
14440
14441/// BuildCallToObjectOfClassType - Build a call to an object of class
14442/// type (C++ [over.call.object]), which can end up invoking an
14443/// overloaded function call operator (@c operator()) or performing a
14444/// user-defined conversion on the object argument.
14445ExprResult
14446Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14447 SourceLocation LParenLoc,
14448 MultiExprArg Args,
14449 SourceLocation RParenLoc) {
14450 if (checkPlaceholderForOverload(*this, Obj))
14451 return ExprError();
14452 ExprResult Object = Obj;
14453
14454 UnbridgedCastsSet UnbridgedCasts;
14455 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14456 return ExprError();
14457
14458 assert(Object.get()->getType()->isRecordType() &&((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14459, __PRETTY_FUNCTION__))
14459 "Requires object type argument")((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14459, __PRETTY_FUNCTION__))
;
14460
14461 // C++ [over.call.object]p1:
14462 // If the primary-expression E in the function call syntax
14463 // evaluates to a class object of type "cv T", then the set of
14464 // candidate functions includes at least the function call
14465 // operators of T. The function call operators of T are obtained by
14466 // ordinary lookup of the name operator() in the context of
14467 // (E).operator().
14468 OverloadCandidateSet CandidateSet(LParenLoc,
14469 OverloadCandidateSet::CSK_Operator);
14470 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14471
14472 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14473 diag::err_incomplete_object_call, Object.get()))
14474 return true;
14475
14476 const auto *Record = Object.get()->getType()->castAs<RecordType>();
14477 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14478 LookupQualifiedName(R, Record->getDecl());
14479 R.suppressDiagnostics();
14480
14481 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14482 Oper != OperEnd; ++Oper) {
14483 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14484 Object.get()->Classify(Context), Args, CandidateSet,
14485 /*SuppressUserConversion=*/false);
14486 }
14487
14488 // C++ [over.call.object]p2:
14489 // In addition, for each (non-explicit in C++0x) conversion function
14490 // declared in T of the form
14491 //
14492 // operator conversion-type-id () cv-qualifier;
14493 //
14494 // where cv-qualifier is the same cv-qualification as, or a
14495 // greater cv-qualification than, cv, and where conversion-type-id
14496 // denotes the type "pointer to function of (P1,...,Pn) returning
14497 // R", or the type "reference to pointer to function of
14498 // (P1,...,Pn) returning R", or the type "reference to function
14499 // of (P1,...,Pn) returning R", a surrogate call function [...]
14500 // is also considered as a candidate function. Similarly,
14501 // surrogate call functions are added to the set of candidate
14502 // functions for each conversion function declared in an
14503 // accessible base class provided the function is not hidden
14504 // within T by another intervening declaration.
14505 const auto &Conversions =
14506 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14507 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14508 NamedDecl *D = *I;
14509 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14510 if (isa<UsingShadowDecl>(D))
14511 D = cast<UsingShadowDecl>(D)->getTargetDecl();
14512
14513 // Skip over templated conversion functions; they aren't
14514 // surrogates.
14515 if (isa<FunctionTemplateDecl>(D))
14516 continue;
14517
14518 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14519 if (!Conv->isExplicit()) {
14520 // Strip the reference type (if any) and then the pointer type (if
14521 // any) to get down to what might be a function type.
14522 QualType ConvType = Conv->getConversionType().getNonReferenceType();
14523 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14524 ConvType = ConvPtrType->getPointeeType();
14525
14526 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14527 {
14528 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14529 Object.get(), Args, CandidateSet);
14530 }
14531 }
14532 }
14533
14534 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14535
14536 // Perform overload resolution.
14537 OverloadCandidateSet::iterator Best;
14538 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14539 Best)) {
14540 case OR_Success:
14541 // Overload resolution succeeded; we'll build the appropriate call
14542 // below.
14543 break;
14544
14545 case OR_No_Viable_Function: {
14546 PartialDiagnostic PD =
14547 CandidateSet.empty()
14548 ? (PDiag(diag::err_ovl_no_oper)
14549 << Object.get()->getType() << /*call*/ 1
14550 << Object.get()->getSourceRange())
14551 : (PDiag(diag::err_ovl_no_viable_object_call)
14552 << Object.get()->getType() << Object.get()->getSourceRange());
14553 CandidateSet.NoteCandidates(
14554 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14555 OCD_AllCandidates, Args);
14556 break;
14557 }
14558 case OR_Ambiguous:
14559 CandidateSet.NoteCandidates(
14560 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14561 PDiag(diag::err_ovl_ambiguous_object_call)
14562 << Object.get()->getType()
14563 << Object.get()->getSourceRange()),
14564 *this, OCD_AmbiguousCandidates, Args);
14565 break;
14566
14567 case OR_Deleted:
14568 CandidateSet.NoteCandidates(
14569 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14570 PDiag(diag::err_ovl_deleted_object_call)
14571 << Object.get()->getType()
14572 << Object.get()->getSourceRange()),
14573 *this, OCD_AllCandidates, Args);
14574 break;
14575 }
14576
14577 if (Best == CandidateSet.end())
14578 return true;
14579
14580 UnbridgedCasts.restore();
14581
14582 if (Best->Function == nullptr) {
14583 // Since there is no function declaration, this is one of the
14584 // surrogate candidates. Dig out the conversion function.
14585 CXXConversionDecl *Conv
14586 = cast<CXXConversionDecl>(
14587 Best->Conversions[0].UserDefined.ConversionFunction);
14588
14589 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14590 Best->FoundDecl);
14591 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14592 return ExprError();
14593 assert(Conv == Best->FoundDecl.getDecl() &&((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14594, __PRETTY_FUNCTION__))
14594 "Found Decl & conversion-to-functionptr should be same, right?!")((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14594, __PRETTY_FUNCTION__))
;
14595 // We selected one of the surrogate functions that converts the
14596 // object parameter to a function pointer. Perform the conversion
14597 // on the object argument, then let BuildCallExpr finish the job.
14598
14599 // Create an implicit member expr to refer to the conversion operator.
14600 // and then call it.
14601 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14602 Conv, HadMultipleCandidates);
14603 if (Call.isInvalid())
14604 return ExprError();
14605 // Record usage of conversion in an implicit cast.
14606 Call = ImplicitCastExpr::Create(
14607 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14608 nullptr, VK_RValue, CurFPFeatureOverrides());
14609
14610 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14611 }
14612
14613 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14614
14615 // We found an overloaded operator(). Build a CXXOperatorCallExpr
14616 // that calls this method, using Object for the implicit object
14617 // parameter and passing along the remaining arguments.
14618 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14619
14620 // An error diagnostic has already been printed when parsing the declaration.
14621 if (Method->isInvalidDecl())
14622 return ExprError();
14623
14624 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14625 unsigned NumParams = Proto->getNumParams();
14626
14627 DeclarationNameInfo OpLocInfo(
14628 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14629 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14630 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14631 Obj, HadMultipleCandidates,
14632 OpLocInfo.getLoc(),
14633 OpLocInfo.getInfo());
14634 if (NewFn.isInvalid())
14635 return true;
14636
14637 // The number of argument slots to allocate in the call. If we have default
14638 // arguments we need to allocate space for them as well. We additionally
14639 // need one more slot for the object parameter.
14640 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14641
14642 // Build the full argument list for the method call (the implicit object
14643 // parameter is placed at the beginning of the list).
14644 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14645
14646 bool IsError = false;
14647
14648 // Initialize the implicit object parameter.
14649 ExprResult ObjRes =
14650 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14651 Best->FoundDecl, Method);
14652 if (ObjRes.isInvalid())
14653 IsError = true;
14654 else
14655 Object = ObjRes;
14656 MethodArgs[0] = Object.get();
14657
14658 // Check the argument types.
14659 for (unsigned i = 0; i != NumParams; i++) {
14660 Expr *Arg;
14661 if (i < Args.size()) {
14662 Arg = Args[i];
14663
14664 // Pass the argument.
14665
14666 ExprResult InputInit
14667 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14668 Context,
14669 Method->getParamDecl(i)),
14670 SourceLocation(), Arg);
14671
14672 IsError |= InputInit.isInvalid();
14673 Arg = InputInit.getAs<Expr>();
14674 } else {
14675 ExprResult DefArg
14676 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14677 if (DefArg.isInvalid()) {
14678 IsError = true;
14679 break;
14680 }
14681
14682 Arg = DefArg.getAs<Expr>();
14683 }
14684
14685 MethodArgs[i + 1] = Arg;
14686 }
14687
14688 // If this is a variadic call, handle args passed through "...".
14689 if (Proto->isVariadic()) {
14690 // Promote the arguments (C99 6.5.2.2p7).
14691 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14692 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14693 nullptr);
14694 IsError |= Arg.isInvalid();
14695 MethodArgs[i + 1] = Arg.get();
14696 }
14697 }
14698
14699 if (IsError)
14700 return true;
14701
14702 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14703
14704 // Once we've built TheCall, all of the expressions are properly owned.
14705 QualType ResultTy = Method->getReturnType();
14706 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14707 ResultTy = ResultTy.getNonLValueExprType(Context);
14708
14709 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14710 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14711 CurFPFeatureOverrides());
14712
14713 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14714 return true;
14715
14716 if (CheckFunctionCall(Method, TheCall, Proto))
14717 return true;
14718
14719 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14720}
14721
14722/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14723/// (if one exists), where @c Base is an expression of class type and
14724/// @c Member is the name of the member we're trying to find.
14725ExprResult
14726Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14727 bool *NoArrowOperatorFound) {
14728 assert(Base->getType()->isRecordType() &&((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14729, __PRETTY_FUNCTION__))
14729 "left-hand side must have class type")((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 14729, __PRETTY_FUNCTION__))
;
14730
14731 if (checkPlaceholderForOverload(*this, Base))
14732 return ExprError();
14733
14734 SourceLocation Loc = Base->getExprLoc();
14735
14736 // C++ [over.ref]p1:
14737 //
14738 // [...] An expression x->m is interpreted as (x.operator->())->m
14739 // for a class object x of type T if T::operator->() exists and if
14740 // the operator is selected as the best match function by the
14741 // overload resolution mechanism (13.3).
14742 DeclarationName OpName =
14743 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14744 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14745
14746 if (RequireCompleteType(Loc, Base->getType(),
14747 diag::err_typecheck_incomplete_tag, Base))
14748 return ExprError();
14749
14750 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14751 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14752 R.suppressDiagnostics();
14753
14754 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14755 Oper != OperEnd; ++Oper) {
14756 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14757 None, CandidateSet, /*SuppressUserConversion=*/false);
14758 }
14759
14760 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14761
14762 // Perform overload resolution.
14763 OverloadCandidateSet::iterator Best;
14764 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14765 case OR_Success:
14766 // Overload resolution succeeded; we'll build the call below.
14767 break;
14768
14769 case OR_No_Viable_Function: {
14770 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14771 if (CandidateSet.empty()) {
14772 QualType BaseType = Base->getType();
14773 if (NoArrowOperatorFound) {
14774 // Report this specific error to the caller instead of emitting a
14775 // diagnostic, as requested.
14776 *NoArrowOperatorFound = true;
14777 return ExprError();
14778 }
14779 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14780 << BaseType << Base->getSourceRange();
14781 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14782 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14783 << FixItHint::CreateReplacement(OpLoc, ".");
14784 }
14785 } else
14786 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14787 << "operator->" << Base->getSourceRange();
14788 CandidateSet.NoteCandidates(*this, Base, Cands);
14789 return ExprError();
14790 }
14791 case OR_Ambiguous:
14792 CandidateSet.NoteCandidates(
14793 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14794 << "->" << Base->getType()
14795 << Base->getSourceRange()),
14796 *this, OCD_AmbiguousCandidates, Base);
14797 return ExprError();
14798
14799 case OR_Deleted:
14800 CandidateSet.NoteCandidates(
14801 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14802 << "->" << Base->getSourceRange()),
14803 *this, OCD_AllCandidates, Base);
14804 return ExprError();
14805 }
14806
14807 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14808
14809 // Convert the object parameter.
14810 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14811 ExprResult BaseResult =
14812 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14813 Best->FoundDecl, Method);
14814 if (BaseResult.isInvalid())
14815 return ExprError();
14816 Base = BaseResult.get();
14817
14818 // Build the operator call.
14819 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14820 Base, HadMultipleCandidates, OpLoc);
14821 if (FnExpr.isInvalid())
14822 return ExprError();
14823
14824 QualType ResultTy = Method->getReturnType();
14825 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14826 ResultTy = ResultTy.getNonLValueExprType(Context);
14827 CXXOperatorCallExpr *TheCall =
14828 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14829 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14830
14831 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14832 return ExprError();
14833
14834 if (CheckFunctionCall(Method, TheCall,
14835 Method->getType()->castAs<FunctionProtoType>()))
14836 return ExprError();
14837
14838 return MaybeBindToTemporary(TheCall);
14839}
14840
14841/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14842/// a literal operator described by the provided lookup results.
14843ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14844 DeclarationNameInfo &SuffixInfo,
14845 ArrayRef<Expr*> Args,
14846 SourceLocation LitEndLoc,
14847 TemplateArgumentListInfo *TemplateArgs) {
14848 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14849
14850 OverloadCandidateSet CandidateSet(UDSuffixLoc,
14851 OverloadCandidateSet::CSK_Normal);
14852 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14853 TemplateArgs);
14854
14855 bool HadMultipleCandidates = (CandidateSet.size() > 1);
1
Assuming the condition is false
14856
14857 // Perform overload resolution. This will usually be trivial, but might need
14858 // to perform substitutions for a literal operator template.
14859 OverloadCandidateSet::iterator Best;
14860 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
2
Calling 'OverloadCandidateSet::BestViableFunction'
14861 case OR_Success:
14862 case OR_Deleted:
14863 break;
14864
14865 case OR_No_Viable_Function:
14866 CandidateSet.NoteCandidates(
14867 PartialDiagnosticAt(UDSuffixLoc,
14868 PDiag(diag::err_ovl_no_viable_function_in_call)
14869 << R.getLookupName()),
14870 *this, OCD_AllCandidates, Args);
14871 return ExprError();
14872
14873 case OR_Ambiguous:
14874 CandidateSet.NoteCandidates(
14875 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14876 << R.getLookupName()),
14877 *this, OCD_AmbiguousCandidates, Args);
14878 return ExprError();
14879 }
14880
14881 FunctionDecl *FD = Best->Function;
14882 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14883 nullptr, HadMultipleCandidates,
14884 SuffixInfo.getLoc(),
14885 SuffixInfo.getInfo());
14886 if (Fn.isInvalid())
14887 return true;
14888
14889 // Check the argument types. This should almost always be a no-op, except
14890 // that array-to-pointer decay is applied to string literals.
14891 Expr *ConvArgs[2];
14892 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14893 ExprResult InputInit = PerformCopyInitialization(
14894 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14895 SourceLocation(), Args[ArgIdx]);
14896 if (InputInit.isInvalid())
14897 return true;
14898 ConvArgs[ArgIdx] = InputInit.get();
14899 }
14900
14901 QualType ResultTy = FD->getReturnType();
14902 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14903 ResultTy = ResultTy.getNonLValueExprType(Context);
14904
14905 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14906 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14907 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
14908
14909 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14910 return ExprError();
14911
14912 if (CheckFunctionCall(FD, UDL, nullptr))
14913 return ExprError();
14914
14915 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14916}
14917
14918/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14919/// given LookupResult is non-empty, it is assumed to describe a member which
14920/// will be invoked. Otherwise, the function will be found via argument
14921/// dependent lookup.
14922/// CallExpr is set to a valid expression and FRS_Success returned on success,
14923/// otherwise CallExpr is set to ExprError() and some non-success value
14924/// is returned.
14925Sema::ForRangeStatus
14926Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14927 SourceLocation RangeLoc,
14928 const DeclarationNameInfo &NameInfo,
14929 LookupResult &MemberLookup,
14930 OverloadCandidateSet *CandidateSet,
14931 Expr *Range, ExprResult *CallExpr) {
14932 Scope *S = nullptr;
14933
14934 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14935 if (!MemberLookup.empty()) {
14936 ExprResult MemberRef =
14937 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14938 /*IsPtr=*/false, CXXScopeSpec(),
14939 /*TemplateKWLoc=*/SourceLocation(),
14940 /*FirstQualifierInScope=*/nullptr,
14941 MemberLookup,
14942 /*TemplateArgs=*/nullptr, S);
14943 if (MemberRef.isInvalid()) {
14944 *CallExpr = ExprError();
14945 return FRS_DiagnosticIssued;
14946 }
14947 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14948 if (CallExpr->isInvalid()) {
14949 *CallExpr = ExprError();
14950 return FRS_DiagnosticIssued;
14951 }
14952 } else {
14953 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
14954 NestedNameSpecifierLoc(),
14955 NameInfo, UnresolvedSet<0>());
14956 if (FnR.isInvalid())
14957 return FRS_DiagnosticIssued;
14958 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
14959
14960 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14961 CandidateSet, CallExpr);
14962 if (CandidateSet->empty() || CandidateSetError) {
14963 *CallExpr = ExprError();
14964 return FRS_NoViableFunction;
14965 }
14966 OverloadCandidateSet::iterator Best;
14967 OverloadingResult OverloadResult =
14968 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14969
14970 if (OverloadResult == OR_No_Viable_Function) {
14971 *CallExpr = ExprError();
14972 return FRS_NoViableFunction;
14973 }
14974 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14975 Loc, nullptr, CandidateSet, &Best,
14976 OverloadResult,
14977 /*AllowTypoCorrection=*/false);
14978 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14979 *CallExpr = ExprError();
14980 return FRS_DiagnosticIssued;
14981 }
14982 }
14983 return FRS_Success;
14984}
14985
14986
14987/// FixOverloadedFunctionReference - E is an expression that refers to
14988/// a C++ overloaded function (possibly with some parentheses and
14989/// perhaps a '&' around it). We have resolved the overloaded function
14990/// to the function declaration Fn, so patch up the expression E to
14991/// refer (possibly indirectly) to Fn. Returns the new expr.
14992Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14993 FunctionDecl *Fn) {
14994 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14995 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14996 Found, Fn);
14997 if (SubExpr == PE->getSubExpr())
14998 return PE;
14999
15000 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15001 }
15002
15003 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15004 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15005 Found, Fn);
15006 assert(Context.hasSameType(ICE->getSubExpr()->getType(),((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15008, __PRETTY_FUNCTION__))
15007 SubExpr->getType()) &&((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15008, __PRETTY_FUNCTION__))
15008 "Implicit cast type cannot be determined from overload")((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15008, __PRETTY_FUNCTION__))
;
15009 assert(ICE->path_empty() && "fixing up hierarchy conversion?")((ICE->path_empty() && "fixing up hierarchy conversion?"
) ? static_cast<void> (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15009, __PRETTY_FUNCTION__))
;
15010 if (SubExpr == ICE->getSubExpr())
15011 return ICE;
15012
15013 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15014 SubExpr, nullptr, ICE->getValueKind(),
15015 CurFPFeatureOverrides());
15016 }
15017
15018 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15019 if (!GSE->isResultDependent()) {
15020 Expr *SubExpr =
15021 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15022 if (SubExpr == GSE->getResultExpr())
15023 return GSE;
15024
15025 // Replace the resulting type information before rebuilding the generic
15026 // selection expression.
15027 ArrayRef<Expr *> A = GSE->getAssocExprs();
15028 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15029 unsigned ResultIdx = GSE->getResultIndex();
15030 AssocExprs[ResultIdx] = SubExpr;
15031
15032 return GenericSelectionExpr::Create(
15033 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15034 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15035 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15036 ResultIdx);
15037 }
15038 // Rather than fall through to the unreachable, return the original generic
15039 // selection expression.
15040 return GSE;
15041 }
15042
15043 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15044 assert(UnOp->getOpcode() == UO_AddrOf &&((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15045, __PRETTY_FUNCTION__))
15045 "Can only take the address of an overloaded function")((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15045, __PRETTY_FUNCTION__))
;
15046 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15047 if (Method->isStatic()) {
15048 // Do nothing: static member functions aren't any different
15049 // from non-member functions.
15050 } else {
15051 // Fix the subexpression, which really has to be an
15052 // UnresolvedLookupExpr holding an overloaded member function
15053 // or template.
15054 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15055 Found, Fn);
15056 if (SubExpr == UnOp->getSubExpr())
15057 return UnOp;
15058
15059 assert(isa<DeclRefExpr>(SubExpr)((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15060, __PRETTY_FUNCTION__))
15060 && "fixed to something other than a decl ref")((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15060, __PRETTY_FUNCTION__))
;
15061 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15062, __PRETTY_FUNCTION__))
15062 && "fixed to a member ref with no nested name qualifier")((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15062, __PRETTY_FUNCTION__))
;
15063
15064 // We have taken the address of a pointer to member
15065 // function. Perform the computation here so that we get the
15066 // appropriate pointer to member type.
15067 QualType ClassType
15068 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15069 QualType MemPtrType
15070 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15071 // Under the MS ABI, lock down the inheritance model now.
15072 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15073 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15074
15075 return UnaryOperator::Create(
15076 Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary,
15077 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15078 }
15079 }
15080 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15081 Found, Fn);
15082 if (SubExpr == UnOp->getSubExpr())
15083 return UnOp;
15084
15085 return UnaryOperator::Create(Context, SubExpr, UO_AddrOf,
15086 Context.getPointerType(SubExpr->getType()),
15087 VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(),
15088 false, CurFPFeatureOverrides());
15089 }
15090
15091 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15092 // FIXME: avoid copy.
15093 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15094 if (ULE->hasExplicitTemplateArgs()) {
15095 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15096 TemplateArgs = &TemplateArgsBuffer;
15097 }
15098
15099 DeclRefExpr *DRE =
15100 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
15101 ULE->getQualifierLoc(), Found.getDecl(),
15102 ULE->getTemplateKeywordLoc(), TemplateArgs);
15103 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15104 return DRE;
15105 }
15106
15107 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15108 // FIXME: avoid copy.
15109 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15110 if (MemExpr->hasExplicitTemplateArgs()) {
15111 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15112 TemplateArgs = &TemplateArgsBuffer;
15113 }
15114
15115 Expr *Base;
15116
15117 // If we're filling in a static method where we used to have an
15118 // implicit member access, rewrite to a simple decl ref.
15119 if (MemExpr->isImplicitAccess()) {
15120 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15121 DeclRefExpr *DRE = BuildDeclRefExpr(
15122 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15123 MemExpr->getQualifierLoc(), Found.getDecl(),
15124 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15125 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15126 return DRE;
15127 } else {
15128 SourceLocation Loc = MemExpr->getMemberLoc();
15129 if (MemExpr->getQualifier())
15130 Loc = MemExpr->getQualifierLoc().getBeginLoc();
15131 Base =
15132 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15133 }
15134 } else
15135 Base = MemExpr->getBase();
15136
15137 ExprValueKind valueKind;
15138 QualType type;
15139 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15140 valueKind = VK_LValue;
15141 type = Fn->getType();
15142 } else {
15143 valueKind = VK_RValue;
15144 type = Context.BoundMemberTy;
15145 }
15146
15147 return BuildMemberExpr(
15148 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15149 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15150 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15151 type, valueKind, OK_Ordinary, TemplateArgs);
15152 }
15153
15154 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/lib/Sema/SemaOverload.cpp"
, 15154)
;
15155}
15156
15157ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15158 DeclAccessPair Found,
15159 FunctionDecl *Fn) {
15160 return FixOverloadedFunctionReference(E.get(), Found, Fn);
15161}

/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h

1//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the SmallVector class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_SMALLVECTOR_H
14#define LLVM_ADT_SMALLVECTOR_H
15
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/ErrorHandling.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Support/MemAlloc.h"
21#include "llvm/Support/type_traits.h"
22#include <algorithm>
23#include <cassert>
24#include <cstddef>
25#include <cstdlib>
26#include <cstring>
27#include <initializer_list>
28#include <iterator>
29#include <limits>
30#include <memory>
31#include <new>
32#include <type_traits>
33#include <utility>
34
35namespace llvm {
36
37/// This is all the stuff common to all SmallVectors.
38///
39/// The template parameter specifies the type which should be used to hold the
40/// Size and Capacity of the SmallVector, so it can be adjusted.
41/// Using 32 bit size is desirable to shrink the size of the SmallVector.
42/// Using 64 bit size is desirable for cases like SmallVector<char>, where a
43/// 32 bit size would limit the vector to ~4GB. SmallVectors are used for
44/// buffering bitcode output - which can exceed 4GB.
45template <class Size_T> class SmallVectorBase {
46protected:
47 void *BeginX;
48 Size_T Size = 0, Capacity;
49
50 /// The maximum value of the Size_T used.
51 static constexpr size_t SizeTypeMax() {
52 return std::numeric_limits<Size_T>::max();
53 }
54
55 SmallVectorBase() = delete;
56 SmallVectorBase(void *FirstEl, size_t TotalCapacity)
57 : BeginX(FirstEl), Capacity(TotalCapacity) {}
58
59 /// This is a helper for \a grow() that's out of line to reduce code
60 /// duplication. This function will report a fatal error if it can't grow at
61 /// least to \p MinSize.
62 void *mallocForGrow(size_t MinSize, size_t TSize, size_t &NewCapacity);
63
64 /// This is an implementation of the grow() method which only works
65 /// on POD-like data types and is out of line to reduce code duplication.
66 /// This function will report a fatal error if it cannot increase capacity.
67 void grow_pod(void *FirstEl, size_t MinSize, size_t TSize);
68
69public:
70 size_t size() const { return Size; }
71 size_t capacity() const { return Capacity; }
72
73 LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const { return !Size; }
13
Assuming field 'Size' is not equal to 0
14
Returning zero, which participates in a condition later
74
75 /// Set the array size to \p N, which the current array must have enough
76 /// capacity for.
77 ///
78 /// This does not construct or destroy any elements in the vector.
79 ///
80 /// Clients can use this in conjunction with capacity() to write past the end
81 /// of the buffer when they know that more elements are available, and only
82 /// update the size later. This avoids the cost of value initializing elements
83 /// which will only be overwritten.
84 void set_size(size_t N) {
85 assert(N <= capacity())((N <= capacity()) ? static_cast<void> (0) : __assert_fail
("N <= capacity()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 85, __PRETTY_FUNCTION__))
;
86 Size = N;
87 }
88};
89
90template <class T>
91using SmallVectorSizeType =
92 typename std::conditional<sizeof(T) < 4 && sizeof(void *) >= 8, uint64_t,
93 uint32_t>::type;
94
95/// Figure out the offset of the first element.
96template <class T, typename = void> struct SmallVectorAlignmentAndSize {
97 alignas(SmallVectorBase<SmallVectorSizeType<T>>) char Base[sizeof(
98 SmallVectorBase<SmallVectorSizeType<T>>)];
99 alignas(T) char FirstEl[sizeof(T)];
100};
101
102/// This is the part of SmallVectorTemplateBase which does not depend on whether
103/// the type T is a POD. The extra dummy template argument is used by ArrayRef
104/// to avoid unnecessarily requiring T to be complete.
105template <typename T, typename = void>
106class SmallVectorTemplateCommon
107 : public SmallVectorBase<SmallVectorSizeType<T>> {
108 using Base = SmallVectorBase<SmallVectorSizeType<T>>;
109
110 /// Find the address of the first element. For this pointer math to be valid
111 /// with small-size of 0 for T with lots of alignment, it's important that
112 /// SmallVectorStorage is properly-aligned even for small-size of 0.
113 void *getFirstEl() const {
114 return const_cast<void *>(reinterpret_cast<const void *>(
115 reinterpret_cast<const char *>(this) +
116 offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)__builtin_offsetof(SmallVectorAlignmentAndSize<T>, FirstEl
)
));
117 }
118 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
119
120protected:
121 SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {}
122
123 void grow_pod(size_t MinSize, size_t TSize) {
124 Base::grow_pod(getFirstEl(), MinSize, TSize);
125 }
126
127 /// Return true if this is a smallvector which has not had dynamic
128 /// memory allocated for it.
129 bool isSmall() const { return this->BeginX == getFirstEl(); }
130
131 /// Put this vector in a state of being small.
132 void resetToSmall() {
133 this->BeginX = getFirstEl();
134 this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
135 }
136
137 /// Return true if V is an internal reference to the given range.
138 bool isReferenceToRange(const void *V, const void *First, const void *Last) const {
139 // Use std::less to avoid UB.
140 std::less<> LessThan;
141 return !LessThan(V, First) && LessThan(V, Last);
142 }
143
144 /// Return true if V is an internal reference to this vector.
145 bool isReferenceToStorage(const void *V) const {
146 return isReferenceToRange(V, this->begin(), this->end());
147 }
148
149 /// Return true if First and Last form a valid (possibly empty) range in this
150 /// vector's storage.
151 bool isRangeInStorage(const void *First, const void *Last) const {
152 // Use std::less to avoid UB.
153 std::less<> LessThan;
154 return !LessThan(First, this->begin()) && !LessThan(Last, First) &&
155 !LessThan(this->end(), Last);
156 }
157
158 /// Return true unless Elt will be invalidated by resizing the vector to
159 /// NewSize.
160 bool isSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
161 // Past the end.
162 if (LLVM_LIKELY(!isReferenceToStorage(Elt))__builtin_expect((bool)(!isReferenceToStorage(Elt)), true))
163 return true;
164
165 // Return false if Elt will be destroyed by shrinking.
166 if (NewSize <= this->size())
167 return Elt < this->begin() + NewSize;
168
169 // Return false if we need to grow.
170 return NewSize <= this->capacity();
171 }
172
173 /// Check whether Elt will be invalidated by resizing the vector to NewSize.
174 void assertSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
175 assert(isSafeToReferenceAfterResize(Elt, NewSize) &&((isSafeToReferenceAfterResize(Elt, NewSize) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? static_cast<void> (0) : __assert_fail
("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 177, __PRETTY_FUNCTION__))
176 "Attempting to reference an element of the vector in an operation "((isSafeToReferenceAfterResize(Elt, NewSize) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? static_cast<void> (0) : __assert_fail
("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 177, __PRETTY_FUNCTION__))
177 "that invalidates it")((isSafeToReferenceAfterResize(Elt, NewSize) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? static_cast<void> (0) : __assert_fail
("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 177, __PRETTY_FUNCTION__))
;
178 }
179
180 /// Check whether Elt will be invalidated by increasing the size of the
181 /// vector by N.
182 void assertSafeToAdd(const void *Elt, size_t N = 1) {
183 this->assertSafeToReferenceAfterResize(Elt, this->size() + N);
184 }
185
186 /// Check whether any part of the range will be invalidated by clearing.
187 void assertSafeToReferenceAfterClear(const T *From, const T *To) {
188 if (From == To)
189 return;
190 this->assertSafeToReferenceAfterResize(From, 0);
191 this->assertSafeToReferenceAfterResize(To - 1, 0);
192 }
193 template <
194 class ItTy,
195 std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
196 bool> = false>
197 void assertSafeToReferenceAfterClear(ItTy, ItTy) {}
198
199 /// Check whether any part of the range will be invalidated by growing.
200 void assertSafeToAddRange(const T *From, const T *To) {
201 if (From == To)
202 return;
203 this->assertSafeToAdd(From, To - From);
204 this->assertSafeToAdd(To - 1, To - From);
205 }
206 template <
207 class ItTy,
208 std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
209 bool> = false>
210 void assertSafeToAddRange(ItTy, ItTy) {}
211
212 /// Reserve enough space to add one element, and return the updated element
213 /// pointer in case it was a reference to the storage.
214 template <class U>
215 static const T *reserveForParamAndGetAddressImpl(U *This, const T &Elt,
216 size_t N) {
217 size_t NewSize = This->size() + N;
218 if (LLVM_LIKELY(NewSize <= This->capacity())__builtin_expect((bool)(NewSize <= This->capacity()), true
)
)
219 return &Elt;
220
221 bool ReferencesStorage = false;
222 int64_t Index = -1;
223 if (!U::TakesParamByValue) {
224 if (LLVM_UNLIKELY(This->isReferenceToStorage(&Elt))__builtin_expect((bool)(This->isReferenceToStorage(&Elt
)), false)
) {
225 ReferencesStorage = true;
226 Index = &Elt - This->begin();
227 }
228 }
229 This->grow(NewSize);
230 return ReferencesStorage ? This->begin() + Index : &Elt;
231 }
232
233public:
234 using size_type = size_t;
235 using difference_type = ptrdiff_t;
236 using value_type = T;
237 using iterator = T *;
238 using const_iterator = const T *;
239
240 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
241 using reverse_iterator = std::reverse_iterator<iterator>;
242
243 using reference = T &;
244 using const_reference = const T &;
245 using pointer = T *;
246 using const_pointer = const T *;
247
248 using Base::capacity;
249 using Base::empty;
250 using Base::size;
251
252 // forward iterator creation methods.
253 iterator begin() { return (iterator)this->BeginX; }
254 const_iterator begin() const { return (const_iterator)this->BeginX; }
255 iterator end() { return begin() + size(); }
256 const_iterator end() const { return begin() + size(); }
257
258 // reverse iterator creation methods.
259 reverse_iterator rbegin() { return reverse_iterator(end()); }
260 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
261 reverse_iterator rend() { return reverse_iterator(begin()); }
262 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
263
264 size_type size_in_bytes() const { return size() * sizeof(T); }
265 size_type max_size() const {
266 return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T));
267 }
268
269 size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
270
271 /// Return a pointer to the vector's buffer, even if empty().
272 pointer data() { return pointer(begin()); }
273 /// Return a pointer to the vector's buffer, even if empty().
274 const_pointer data() const { return const_pointer(begin()); }
275
276 reference operator[](size_type idx) {
277 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 277, __PRETTY_FUNCTION__))
;
278 return begin()[idx];
279 }
280 const_reference operator[](size_type idx) const {
281 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 281, __PRETTY_FUNCTION__))
;
282 return begin()[idx];
283 }
284
285 reference front() {
286 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 286, __PRETTY_FUNCTION__))
;
287 return begin()[0];
288 }
289 const_reference front() const {
290 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 290, __PRETTY_FUNCTION__))
;
291 return begin()[0];
292 }
293
294 reference back() {
295 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 295, __PRETTY_FUNCTION__))
;
296 return end()[-1];
297 }
298 const_reference back() const {
299 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 299, __PRETTY_FUNCTION__))
;
300 return end()[-1];
301 }
302};
303
304/// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put
305/// method implementations that are designed to work with non-trivial T's.
306///
307/// We approximate is_trivially_copyable with trivial move/copy construction and
308/// trivial destruction. While the standard doesn't specify that you're allowed
309/// copy these types with memcpy, there is no way for the type to observe this.
310/// This catches the important case of std::pair<POD, POD>, which is not
311/// trivially assignable.
312template <typename T, bool = (is_trivially_copy_constructible<T>::value) &&
313 (is_trivially_move_constructible<T>::value) &&
314 std::is_trivially_destructible<T>::value>
315class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
316 friend class SmallVectorTemplateCommon<T>;
317
318protected:
319 static constexpr bool TakesParamByValue = false;
320 using ValueParamT = const T &;
321
322 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
323
324 static void destroy_range(T *S, T *E) {
325 while (S != E) {
326 --E;
327 E->~T();
328 }
329 }
330
331 /// Move the range [I, E) into the uninitialized memory starting with "Dest",
332 /// constructing elements as needed.
333 template<typename It1, typename It2>
334 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
335 std::uninitialized_copy(std::make_move_iterator(I),
336 std::make_move_iterator(E), Dest);
337 }
338
339 /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
340 /// constructing elements as needed.
341 template<typename It1, typename It2>
342 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
343 std::uninitialized_copy(I, E, Dest);
344 }
345
346 /// Grow the allocated memory (without initializing new elements), doubling
347 /// the size of the allocated memory. Guarantees space for at least one more
348 /// element, or MinSize more elements if specified.
349 void grow(size_t MinSize = 0);
350
351 /// Create a new allocation big enough for \p MinSize and pass back its size
352 /// in \p NewCapacity. This is the first section of \a grow().
353 T *mallocForGrow(size_t MinSize, size_t &NewCapacity) {
354 return static_cast<T *>(
355 SmallVectorBase<SmallVectorSizeType<T>>::mallocForGrow(
356 MinSize, sizeof(T), NewCapacity));
357 }
358
359 /// Move existing elements over to the new allocation \p NewElts, the middle
360 /// section of \a grow().
361 void moveElementsForGrow(T *NewElts);
362
363 /// Transfer ownership of the allocation, finishing up \a grow().
364 void takeAllocationForGrow(T *NewElts, size_t NewCapacity);
365
366 /// Reserve enough space to add one element, and return the updated element
367 /// pointer in case it was a reference to the storage.
368 const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
369 return this->reserveForParamAndGetAddressImpl(this, Elt, N);
370 }
371
372 /// Reserve enough space to add one element, and return the updated element
373 /// pointer in case it was a reference to the storage.
374 T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
375 return const_cast<T *>(
376 this->reserveForParamAndGetAddressImpl(this, Elt, N));
377 }
378
379 static T &&forward_value_param(T &&V) { return std::move(V); }
380 static const T &forward_value_param(const T &V) { return V; }
381
382 void growAndAssign(size_t NumElts, const T &Elt) {
383 // Grow manually in case Elt is an internal reference.
384 size_t NewCapacity;
385 T *NewElts = mallocForGrow(NumElts, NewCapacity);
386 std::uninitialized_fill_n(NewElts, NumElts, Elt);
387 this->destroy_range(this->begin(), this->end());
388 takeAllocationForGrow(NewElts, NewCapacity);
389 this->set_size(NumElts);
390 }
391
392 template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
393 // Grow manually in case one of Args is an internal reference.
394 size_t NewCapacity;
395 T *NewElts = mallocForGrow(0, NewCapacity);
396 ::new ((void *)(NewElts + this->size())) T(std::forward<ArgTypes>(Args)...);
397 moveElementsForGrow(NewElts);
398 takeAllocationForGrow(NewElts, NewCapacity);
399 this->set_size(this->size() + 1);
400 return this->back();
401 }
402
403public:
404 void push_back(const T &Elt) {
405 const T *EltPtr = reserveForParamAndGetAddress(Elt);
406 ::new ((void *)this->end()) T(*EltPtr);
407 this->set_size(this->size() + 1);
408 }
409
410 void push_back(T &&Elt) {
411 T *EltPtr = reserveForParamAndGetAddress(Elt);
412 ::new ((void *)this->end()) T(::std::move(*EltPtr));
413 this->set_size(this->size() + 1);
414 }
415
416 void pop_back() {
417 this->set_size(this->size() - 1);
418 this->end()->~T();
419 }
420};
421
422// Define this out-of-line to dissuade the C++ compiler from inlining it.
423template <typename T, bool TriviallyCopyable>
424void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
425 size_t NewCapacity;
426 T *NewElts = mallocForGrow(MinSize, NewCapacity);
427 moveElementsForGrow(NewElts);
428 takeAllocationForGrow(NewElts, NewCapacity);
429}
430
431// Define this out-of-line to dissuade the C++ compiler from inlining it.
432template <typename T, bool TriviallyCopyable>
433void SmallVectorTemplateBase<T, TriviallyCopyable>::moveElementsForGrow(
434 T *NewElts) {
435 // Move the elements over.
436 this->uninitialized_move(this->begin(), this->end(), NewElts);
437
438 // Destroy the original elements.
439 destroy_range(this->begin(), this->end());
440}
441
442// Define this out-of-line to dissuade the C++ compiler from inlining it.
443template <typename T, bool TriviallyCopyable>
444void SmallVectorTemplateBase<T, TriviallyCopyable>::takeAllocationForGrow(
445 T *NewElts, size_t NewCapacity) {
446 // If this wasn't grown from the inline copy, deallocate the old space.
447 if (!this->isSmall())
448 free(this->begin());
449
450 this->BeginX = NewElts;
451 this->Capacity = NewCapacity;
452}
453
454/// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put
455/// method implementations that are designed to work with trivially copyable
456/// T's. This allows using memcpy in place of copy/move construction and
457/// skipping destruction.
458template <typename T>
459class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
460 friend class SmallVectorTemplateCommon<T>;
461
462protected:
463 /// True if it's cheap enough to take parameters by value. Doing so avoids
464 /// overhead related to mitigations for reference invalidation.
465 static constexpr bool TakesParamByValue = sizeof(T) <= 2 * sizeof(void *);
466
467 /// Either const T& or T, depending on whether it's cheap enough to take
468 /// parameters by value.
469 using ValueParamT =
470 typename std::conditional<TakesParamByValue, T, const T &>::type;
471
472 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
473
474 // No need to do a destroy loop for POD's.
475 static void destroy_range(T *, T *) {}
476
477 /// Move the range [I, E) onto the uninitialized memory
478 /// starting with "Dest", constructing elements into it as needed.
479 template<typename It1, typename It2>
480 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
481 // Just do a copy.
482 uninitialized_copy(I, E, Dest);
483 }
484
485 /// Copy the range [I, E) onto the uninitialized memory
486 /// starting with "Dest", constructing elements into it as needed.
487 template<typename It1, typename It2>
488 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
489 // Arbitrary iterator types; just use the basic implementation.
490 std::uninitialized_copy(I, E, Dest);
491 }
492
493 /// Copy the range [I, E) onto the uninitialized memory
494 /// starting with "Dest", constructing elements into it as needed.
495 template <typename T1, typename T2>
496 static void uninitialized_copy(
497 T1 *I, T1 *E, T2 *Dest,
498 std::enable_if_t<std::is_same<typename std::remove_const<T1>::type,
499 T2>::value> * = nullptr) {
500 // Use memcpy for PODs iterated by pointers (which includes SmallVector
501 // iterators): std::uninitialized_copy optimizes to memmove, but we can
502 // use memcpy here. Note that I and E are iterators and thus might be
503 // invalid for memcpy if they are equal.
504 if (I != E)
505 memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T));
506 }
507
508 /// Double the size of the allocated memory, guaranteeing space for at
509 /// least one more element or MinSize if specified.
510 void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); }
511
512 /// Reserve enough space to add one element, and return the updated element
513 /// pointer in case it was a reference to the storage.
514 const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
515 return this->reserveForParamAndGetAddressImpl(this, Elt, N);
516 }
517
518 /// Reserve enough space to add one element, and return the updated element
519 /// pointer in case it was a reference to the storage.
520 T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
521 return const_cast<T *>(
522 this->reserveForParamAndGetAddressImpl(this, Elt, N));
523 }
524
525 /// Copy \p V or return a reference, depending on \a ValueParamT.
526 static ValueParamT forward_value_param(ValueParamT V) { return V; }
527
528 void growAndAssign(size_t NumElts, T Elt) {
529 // Elt has been copied in case it's an internal reference, side-stepping
530 // reference invalidation problems without losing the realloc optimization.
531 this->set_size(0);
532 this->grow(NumElts);
533 std::uninitialized_fill_n(this->begin(), NumElts, Elt);
534 this->set_size(NumElts);
535 }
536
537 template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
538 // Use push_back with a copy in case Args has an internal reference,
539 // side-stepping reference invalidation problems without losing the realloc
540 // optimization.
541 push_back(T(std::forward<ArgTypes>(Args)...));
542 return this->back();
543 }
544
545public:
546 void push_back(ValueParamT Elt) {
547 const T *EltPtr = reserveForParamAndGetAddress(Elt);
548 memcpy(reinterpret_cast<void *>(this->end()), EltPtr, sizeof(T));
549 this->set_size(this->size() + 1);
550 }
551
552 void pop_back() { this->set_size(this->size() - 1); }
553};
554
555/// This class consists of common code factored out of the SmallVector class to
556/// reduce code duplication based on the SmallVector 'N' template parameter.
557template <typename T>
558class SmallVectorImpl : public SmallVectorTemplateBase<T> {
559 using SuperClass = SmallVectorTemplateBase<T>;
560
561public:
562 using iterator = typename SuperClass::iterator;
563 using const_iterator = typename SuperClass::const_iterator;
564 using reference = typename SuperClass::reference;
565 using size_type = typename SuperClass::size_type;
566
567protected:
568 using SmallVectorTemplateBase<T>::TakesParamByValue;
569 using ValueParamT = typename SuperClass::ValueParamT;
570
571 // Default ctor - Initialize to empty.
572 explicit SmallVectorImpl(unsigned N)
573 : SmallVectorTemplateBase<T>(N) {}
574
575public:
576 SmallVectorImpl(const SmallVectorImpl &) = delete;
577
578 ~SmallVectorImpl() {
579 // Subclass has already destructed this vector's elements.
580 // If this wasn't grown from the inline copy, deallocate the old space.
581 if (!this->isSmall())
582 free(this->begin());
583 }
584
585 void clear() {
586 this->destroy_range(this->begin(), this->end());
587 this->Size = 0;
588 }
589
590private:
591 template <bool ForOverwrite> void resizeImpl(size_type N) {
592 if (N < this->size()) {
593 this->pop_back_n(this->size() - N);
594 } else if (N > this->size()) {
595 this->reserve(N);
596 for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
597 if (ForOverwrite)
598 new (&*I) T;
599 else
600 new (&*I) T();
601 this->set_size(N);
602 }
603 }
604
605public:
606 void resize(size_type N) { resizeImpl<false>(N); }
607
608 /// Like resize, but \ref T is POD, the new values won't be initialized.
609 void resize_for_overwrite(size_type N) { resizeImpl<true>(N); }
610
611 void resize(size_type N, ValueParamT NV) {
612 if (N == this->size())
613 return;
614
615 if (N < this->size()) {
616 this->pop_back_n(this->size() - N);
617 return;
618 }
619
620 // N > this->size(). Defer to append.
621 this->append(N - this->size(), NV);
622 }
623
624 void reserve(size_type N) {
625 if (this->capacity() < N)
626 this->grow(N);
627 }
628
629 void pop_back_n(size_type NumItems) {
630 assert(this->size() >= NumItems)((this->size() >= NumItems) ? static_cast<void> (
0) : __assert_fail ("this->size() >= NumItems", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 630, __PRETTY_FUNCTION__))
;
631 this->destroy_range(this->end() - NumItems, this->end());
632 this->set_size(this->size() - NumItems);
633 }
634
635 LLVM_NODISCARD[[clang::warn_unused_result]] T pop_back_val() {
636 T Result = ::std::move(this->back());
637 this->pop_back();
638 return Result;
639 }
640
641 void swap(SmallVectorImpl &RHS);
642
643 /// Add the specified range to the end of the SmallVector.
644 template <typename in_iter,
645 typename = std::enable_if_t<std::is_convertible<
646 typename std::iterator_traits<in_iter>::iterator_category,
647 std::input_iterator_tag>::value>>
648 void append(in_iter in_start, in_iter in_end) {
649 this->assertSafeToAddRange(in_start, in_end);
650 size_type NumInputs = std::distance(in_start, in_end);
651 this->reserve(this->size() + NumInputs);
652 this->uninitialized_copy(in_start, in_end, this->end());
653 this->set_size(this->size() + NumInputs);
654 }
655
656 /// Append \p NumInputs copies of \p Elt to the end.
657 void append(size_type NumInputs, ValueParamT Elt) {
658 const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumInputs);
659 std::uninitialized_fill_n(this->end(), NumInputs, *EltPtr);
660 this->set_size(this->size() + NumInputs);
661 }
662
663 void append(std::initializer_list<T> IL) {
664 append(IL.begin(), IL.end());
665 }
666
667 void append(const SmallVectorImpl &RHS) { append(RHS.begin(), RHS.end()); }
668
669 void assign(size_type NumElts, ValueParamT Elt) {
670 // Note that Elt could be an internal reference.
671 if (NumElts > this->capacity()) {
672 this->growAndAssign(NumElts, Elt);
673 return;
674 }
675
676 // Assign over existing elements.
677 std::fill_n(this->begin(), std::min(NumElts, this->size()), Elt);
678 if (NumElts > this->size())
679 std::uninitialized_fill_n(this->end(), NumElts - this->size(), Elt);
680 else if (NumElts < this->size())
681 this->destroy_range(this->begin() + NumElts, this->end());
682 this->set_size(NumElts);
683 }
684
685 // FIXME: Consider assigning over existing elements, rather than clearing &
686 // re-initializing them - for all assign(...) variants.
687
688 template <typename in_iter,
689 typename = std::enable_if_t<std::is_convertible<
690 typename std::iterator_traits<in_iter>::iterator_category,
691 std::input_iterator_tag>::value>>
692 void assign(in_iter in_start, in_iter in_end) {
693 this->assertSafeToReferenceAfterClear(in_start, in_end);
694 clear();
695 append(in_start, in_end);
696 }
697
698 void assign(std::initializer_list<T> IL) {
699 clear();
700 append(IL);
701 }
702
703 void assign(const SmallVectorImpl &RHS) { assign(RHS.begin(), RHS.end()); }
704
705 iterator erase(const_iterator CI) {
706 // Just cast away constness because this is a non-const member function.
707 iterator I = const_cast<iterator>(CI);
708
709 assert(this->isReferenceToStorage(CI) && "Iterator to erase is out of bounds.")((this->isReferenceToStorage(CI) && "Iterator to erase is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("this->isReferenceToStorage(CI) && \"Iterator to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 709, __PRETTY_FUNCTION__))
;
710
711 iterator N = I;
712 // Shift all elts down one.
713 std::move(I+1, this->end(), I);
714 // Drop the last elt.
715 this->pop_back();
716 return(N);
717 }
718
719 iterator erase(const_iterator CS, const_iterator CE) {
720 // Just cast away constness because this is a non-const member function.
721 iterator S = const_cast<iterator>(CS);
722 iterator E = const_cast<iterator>(CE);
723
724 assert(this->isRangeInStorage(S, E) && "Range to erase is out of bounds.")((this->isRangeInStorage(S, E) && "Range to erase is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("this->isRangeInStorage(S, E) && \"Range to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 724, __PRETTY_FUNCTION__))
;
725
726 iterator N = S;
727 // Shift all elts down.
728 iterator I = std::move(E, this->end(), S);
729 // Drop the last elts.
730 this->destroy_range(I, this->end());
731 this->set_size(I - this->begin());
732 return(N);
733 }
734
735private:
736 template <class ArgType> iterator insert_one_impl(iterator I, ArgType &&Elt) {
737 // Callers ensure that ArgType is derived from T.
738 static_assert(
739 std::is_same<std::remove_const_t<std::remove_reference_t<ArgType>>,
740 T>::value,
741 "ArgType must be derived from T!");
742
743 if (I == this->end()) { // Important special case for empty vector.
744 this->push_back(::std::forward<ArgType>(Elt));
745 return this->end()-1;
746 }
747
748 assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.")((this->isReferenceToStorage(I) && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("this->isReferenceToStorage(I) && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 748, __PRETTY_FUNCTION__))
;
749
750 // Grow if necessary.
751 size_t Index = I - this->begin();
752 std::remove_reference_t<ArgType> *EltPtr =
753 this->reserveForParamAndGetAddress(Elt);
754 I = this->begin() + Index;
755
756 ::new ((void*) this->end()) T(::std::move(this->back()));
757 // Push everything else over.
758 std::move_backward(I, this->end()-1, this->end());
759 this->set_size(this->size() + 1);
760
761 // If we just moved the element we're inserting, be sure to update
762 // the reference (never happens if TakesParamByValue).
763 static_assert(!TakesParamByValue || std::is_same<ArgType, T>::value,
764 "ArgType must be 'T' when taking by value!");
765 if (!TakesParamByValue && this->isReferenceToRange(EltPtr, I, this->end()))
766 ++EltPtr;
767
768 *I = ::std::forward<ArgType>(*EltPtr);
769 return I;
770 }
771
772public:
773 iterator insert(iterator I, T &&Elt) {
774 return insert_one_impl(I, this->forward_value_param(std::move(Elt)));
775 }
776
777 iterator insert(iterator I, const T &Elt) {
778 return insert_one_impl(I, this->forward_value_param(Elt));
779 }
780
781 iterator insert(iterator I, size_type NumToInsert, ValueParamT Elt) {
782 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
783 size_t InsertElt = I - this->begin();
784
785 if (I == this->end()) { // Important special case for empty vector.
786 append(NumToInsert, Elt);
787 return this->begin()+InsertElt;
788 }
789
790 assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.")((this->isReferenceToStorage(I) && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("this->isReferenceToStorage(I) && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 790, __PRETTY_FUNCTION__))
;
791
792 // Ensure there is enough space, and get the (maybe updated) address of
793 // Elt.
794 const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumToInsert);
795
796 // Uninvalidate the iterator.
797 I = this->begin()+InsertElt;
798
799 // If there are more elements between the insertion point and the end of the
800 // range than there are being inserted, we can use a simple approach to
801 // insertion. Since we already reserved space, we know that this won't
802 // reallocate the vector.
803 if (size_t(this->end()-I) >= NumToInsert) {
804 T *OldEnd = this->end();
805 append(std::move_iterator<iterator>(this->end() - NumToInsert),
806 std::move_iterator<iterator>(this->end()));
807
808 // Copy the existing elements that get replaced.
809 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
810
811 // If we just moved the element we're inserting, be sure to update
812 // the reference (never happens if TakesParamByValue).
813 if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
814 EltPtr += NumToInsert;
815
816 std::fill_n(I, NumToInsert, *EltPtr);
817 return I;
818 }
819
820 // Otherwise, we're inserting more elements than exist already, and we're
821 // not inserting at the end.
822
823 // Move over the elements that we're about to overwrite.
824 T *OldEnd = this->end();
825 this->set_size(this->size() + NumToInsert);
826 size_t NumOverwritten = OldEnd-I;
827 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
828
829 // If we just moved the element we're inserting, be sure to update
830 // the reference (never happens if TakesParamByValue).
831 if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
832 EltPtr += NumToInsert;
833
834 // Replace the overwritten part.
835 std::fill_n(I, NumOverwritten, *EltPtr);
836
837 // Insert the non-overwritten middle part.
838 std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, *EltPtr);
839 return I;
840 }
841
842 template <typename ItTy,
843 typename = std::enable_if_t<std::is_convertible<
844 typename std::iterator_traits<ItTy>::iterator_category,
845 std::input_iterator_tag>::value>>
846 iterator insert(iterator I, ItTy From, ItTy To) {
847 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
848 size_t InsertElt = I - this->begin();
849
850 if (I == this->end()) { // Important special case for empty vector.
851 append(From, To);
852 return this->begin()+InsertElt;
853 }
854
855 assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.")((this->isReferenceToStorage(I) && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("this->isReferenceToStorage(I) && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/llvm/include/llvm/ADT/SmallVector.h"
, 855, __PRETTY_FUNCTION__))
;
856
857 // Check that the reserve that follows doesn't invalidate the iterators.
858 this->assertSafeToAddRange(From, To);
859
860 size_t NumToInsert = std::distance(From, To);
861
862 // Ensure there is enough space.
863 reserve(this->size() + NumToInsert);
864
865 // Uninvalidate the iterator.
866 I = this->begin()+InsertElt;
867
868 // If there are more elements between the insertion point and the end of the
869 // range than there are being inserted, we can use a simple approach to
870 // insertion. Since we already reserved space, we know that this won't
871 // reallocate the vector.
872 if (size_t(this->end()-I) >= NumToInsert) {
873 T *OldEnd = this->end();
874 append(std::move_iterator<iterator>(this->end() - NumToInsert),
875 std::move_iterator<iterator>(this->end()));
876
877 // Copy the existing elements that get replaced.
878 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
879
880 std::copy(From, To, I);
881 return I;
882 }
883
884 // Otherwise, we're inserting more elements than exist already, and we're
885 // not inserting at the end.
886
887 // Move over the elements that we're about to overwrite.
888 T *OldEnd = this->end();
889 this->set_size(this->size() + NumToInsert);
890 size_t NumOverwritten = OldEnd-I;
891 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
892
893 // Replace the overwritten part.
894 for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
895 *J = *From;
896 ++J; ++From;
897 }
898
899 // Insert the non-overwritten middle part.
900 this->uninitialized_copy(From, To, OldEnd);
901 return I;
902 }
903
904 void insert(iterator I, std::initializer_list<T> IL) {
905 insert(I, IL.begin(), IL.end());
906 }
907
908 template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) {
909 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
910 return this->growAndEmplaceBack(std::forward<ArgTypes>(Args)...);
911
912 ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
913 this->set_size(this->size() + 1);
914 return this->back();
915 }
916
917 SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
918
919 SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
920
921 bool operator==(const SmallVectorImpl &RHS) const {
922 if (this->size() != RHS.size()) return false;
923 return std::equal(this->begin(), this->end(), RHS.begin());
924 }
925 bool operator!=(const SmallVectorImpl &RHS) const {
926 return !(*this == RHS);
927 }
928
929 bool operator<(const SmallVectorImpl &RHS) const {
930 return std::lexicographical_compare(this->begin(), this->end(),
931 RHS.begin(), RHS.end());
932 }
933};
934
935template <typename T>
936void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
937 if (this == &RHS) return;
938
939 // We can only avoid copying elements if neither vector is small.
940 if (!this->isSmall() && !RHS.isSmall()) {
941 std::swap(this->BeginX, RHS.BeginX);
942 std::swap(this->Size, RHS.Size);
943 std::swap(this->Capacity, RHS.Capacity);
944 return;
945 }
946 this->reserve(RHS.size());
947 RHS.reserve(this->size());
948
949 // Swap the shared elements.
950 size_t NumShared = this->size();
951 if (NumShared > RHS.size()) NumShared = RHS.size();
952 for (size_type i = 0; i != NumShared; ++i)
953 std::swap((*this)[i], RHS[i]);
954
955 // Copy over the extra elts.
956 if (this->size() > RHS.size()) {
957 size_t EltDiff = this->size() - RHS.size();
958 this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
959 RHS.set_size(RHS.size() + EltDiff);
960 this->destroy_range(this->begin()+NumShared, this->end());
961 this->set_size(NumShared);
962 } else if (RHS.size() > this->size()) {
963 size_t EltDiff = RHS.size() - this->size();
964 this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
965 this->set_size(this->size() + EltDiff);
966 this->destroy_range(RHS.begin()+NumShared, RHS.end());
967 RHS.set_size(NumShared);
968 }
969}
970
971template <typename T>
972SmallVectorImpl<T> &SmallVectorImpl<T>::
973 operator=(const SmallVectorImpl<T> &RHS) {
974 // Avoid self-assignment.
975 if (this == &RHS) return *this;
976
977 // If we already have sufficient space, assign the common elements, then
978 // destroy any excess.
979 size_t RHSSize = RHS.size();
980 size_t CurSize = this->size();
981 if (CurSize >= RHSSize) {
982 // Assign common elements.
983 iterator NewEnd;
984 if (RHSSize)
985 NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
986 else
987 NewEnd = this->begin();
988
989 // Destroy excess elements.
990 this->destroy_range(NewEnd, this->end());
991
992 // Trim.
993 this->set_size(RHSSize);
994 return *this;
995 }
996
997 // If we have to grow to have enough elements, destroy the current elements.
998 // This allows us to avoid copying them during the grow.
999 // FIXME: don't do this if they're efficiently moveable.
1000 if (this->capacity() < RHSSize) {
1001 // Destroy current elements.
1002 this->clear();
1003 CurSize = 0;
1004 this->grow(RHSSize);
1005 } else if (CurSize) {
1006 // Otherwise, use assignment for the already-constructed elements.
1007 std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
1008 }
1009
1010 // Copy construct the new elements in place.
1011 this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
1012 this->begin()+CurSize);
1013
1014 // Set end.
1015 this->set_size(RHSSize);
1016 return *this;
1017}
1018
1019template <typename T>
1020SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
1021 // Avoid self-assignment.
1022 if (this == &RHS) return *this;
1023
1024 // If the RHS isn't small, clear this vector and then steal its buffer.
1025 if (!RHS.isSmall()) {
1026 this->destroy_range(this->begin(), this->end());
1027 if (!this->isSmall()) free(this->begin());
1028 this->BeginX = RHS.BeginX;
1029 this->Size = RHS.Size;
1030 this->Capacity = RHS.Capacity;
1031 RHS.resetToSmall();
1032 return *this;
1033 }
1034
1035 // If we already have sufficient space, assign the common elements, then
1036 // destroy any excess.
1037 size_t RHSSize = RHS.size();
1038 size_t CurSize = this->size();
1039 if (CurSize >= RHSSize) {
1040 // Assign common elements.
1041 iterator NewEnd = this->begin();
1042 if (RHSSize)
1043 NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
1044
1045 // Destroy excess elements and trim the bounds.
1046 this->destroy_range(NewEnd, this->end());
1047 this->set_size(RHSSize);
1048
1049 // Clear the RHS.
1050 RHS.clear();
1051
1052 return *this;
1053 }
1054
1055 // If we have to grow to have enough elements, destroy the current elements.
1056 // This allows us to avoid copying them during the grow.
1057 // FIXME: this may not actually make any sense if we can efficiently move
1058 // elements.
1059 if (this->capacity() < RHSSize) {
1060 // Destroy current elements.
1061 this->clear();
1062 CurSize = 0;
1063 this->grow(RHSSize);
1064 } else if (CurSize) {
1065 // Otherwise, use assignment for the already-constructed elements.
1066 std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
1067 }
1068
1069 // Move-construct the new elements in place.
1070 this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
1071 this->begin()+CurSize);
1072
1073 // Set end.
1074 this->set_size(RHSSize);
1075
1076 RHS.clear();
1077 return *this;
1078}
1079
1080/// Storage for the SmallVector elements. This is specialized for the N=0 case
1081/// to avoid allocating unnecessary storage.
1082template <typename T, unsigned N>
1083struct SmallVectorStorage {
1084 alignas(T) char InlineElts[N * sizeof(T)];
1085};
1086
1087/// We need the storage to be properly aligned even for small-size of 0 so that
1088/// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
1089/// well-defined.
1090template <typename T> struct alignas(T) SmallVectorStorage<T, 0> {};
1091
1092/// Forward declaration of SmallVector so that
1093/// calculateSmallVectorDefaultInlinedElements can reference
1094/// `sizeof(SmallVector<T, 0>)`.
1095template <typename T, unsigned N> class LLVM_GSL_OWNER[[gsl::Owner]] SmallVector;
1096
1097/// Helper class for calculating the default number of inline elements for
1098/// `SmallVector<T>`.
1099///
1100/// This should be migrated to a constexpr function when our minimum
1101/// compiler support is enough for multi-statement constexpr functions.
1102template <typename T> struct CalculateSmallVectorDefaultInlinedElements {
1103 // Parameter controlling the default number of inlined elements
1104 // for `SmallVector<T>`.
1105 //
1106 // The default number of inlined elements ensures that
1107 // 1. There is at least one inlined element.
1108 // 2. `sizeof(SmallVector<T>) <= kPreferredSmallVectorSizeof` unless
1109 // it contradicts 1.
1110 static constexpr size_t kPreferredSmallVectorSizeof = 64;
1111
1112 // static_assert that sizeof(T) is not "too big".
1113 //
1114 // Because our policy guarantees at least one inlined element, it is possible
1115 // for an arbitrarily large inlined element to allocate an arbitrarily large
1116 // amount of inline storage. We generally consider it an antipattern for a
1117 // SmallVector to allocate an excessive amount of inline storage, so we want
1118 // to call attention to these cases and make sure that users are making an
1119 // intentional decision if they request a lot of inline storage.
1120 //
1121 // We want this assertion to trigger in pathological cases, but otherwise
1122 // not be too easy to hit. To accomplish that, the cutoff is actually somewhat
1123 // larger than kPreferredSmallVectorSizeof (otherwise,
1124 // `SmallVector<SmallVector<T>>` would be one easy way to trip it, and that
1125 // pattern seems useful in practice).
1126 //
1127 // One wrinkle is that this assertion is in theory non-portable, since
1128 // sizeof(T) is in general platform-dependent. However, we don't expect this
1129 // to be much of an issue, because most LLVM development happens on 64-bit
1130 // hosts, and therefore sizeof(T) is expected to *decrease* when compiled for
1131 // 32-bit hosts, dodging the issue. The reverse situation, where development
1132 // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a
1133 // 64-bit host, is expected to be very rare.
1134 static_assert(
1135 sizeof(T) <= 256,
1136 "You are trying to use a default number of inlined elements for "
1137 "`SmallVector<T>` but `sizeof(T)` is really big! Please use an "
1138 "explicit number of inlined elements with `SmallVector<T, N>` to make "
1139 "sure you really want that much inline storage.");
1140
1141 // Discount the size of the header itself when calculating the maximum inline
1142 // bytes.
1143 static constexpr size_t PreferredInlineBytes =
1144 kPreferredSmallVectorSizeof - sizeof(SmallVector<T, 0>);
1145 static constexpr size_t NumElementsThatFit = PreferredInlineBytes / sizeof(T);
1146 static constexpr size_t value =
1147 NumElementsThatFit == 0 ? 1 : NumElementsThatFit;
1148};
1149
1150/// This is a 'vector' (really, a variable-sized array), optimized
1151/// for the case when the array is small. It contains some number of elements
1152/// in-place, which allows it to avoid heap allocation when the actual number of
1153/// elements is below that threshold. This allows normal "small" cases to be
1154/// fast without losing generality for large inputs.
1155///
1156/// \note
1157/// In the absence of a well-motivated choice for the number of inlined
1158/// elements \p N, it is recommended to use \c SmallVector<T> (that is,
1159/// omitting the \p N). This will choose a default number of inlined elements
1160/// reasonable for allocation on the stack (for example, trying to keep \c
1161/// sizeof(SmallVector<T>) around 64 bytes).
1162///
1163/// \warning This does not attempt to be exception safe.
1164///
1165/// \see https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h
1166template <typename T,
1167 unsigned N = CalculateSmallVectorDefaultInlinedElements<T>::value>
1168class LLVM_GSL_OWNER[[gsl::Owner]] SmallVector : public SmallVectorImpl<T>,
1169 SmallVectorStorage<T, N> {
1170public:
1171 SmallVector() : SmallVectorImpl<T>(N) {}
1172
1173 ~SmallVector() {
1174 // Destroy the constructed elements in the vector.
1175 this->destroy_range(this->begin(), this->end());
1176 }
1177
1178 explicit SmallVector(size_t Size, const T &Value = T())
1179 : SmallVectorImpl<T>(N) {
1180 this->assign(Size, Value);
1181 }
1182
1183 template <typename ItTy,
1184 typename = std::enable_if_t<std::is_convertible<
1185 typename std::iterator_traits<ItTy>::iterator_category,
1186 std::input_iterator_tag>::value>>
1187 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
1188 this->append(S, E);
1189 }
1190
1191 template <typename RangeTy>
1192 explicit SmallVector(const iterator_range<RangeTy> &R)
1193 : SmallVectorImpl<T>(N) {
1194 this->append(R.begin(), R.end());
1195 }
1196
1197 SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
1198 this->assign(IL);
1199 }
1200
1201 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
1202 if (!RHS.empty())
1203 SmallVectorImpl<T>::operator=(RHS);
1204 }
1205
1206 SmallVector &operator=(const SmallVector &RHS) {
1207 SmallVectorImpl<T>::operator=(RHS);
1208 return *this;
1209 }
1210
1211 SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
1212 if (!RHS.empty())
1213 SmallVectorImpl<T>::operator=(::std::move(RHS));
1214 }
1215
1216 SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
1217 if (!RHS.empty())
1218 SmallVectorImpl<T>::operator=(::std::move(RHS));
1219 }
1220
1221 SmallVector &operator=(SmallVector &&RHS) {
1222 SmallVectorImpl<T>::operator=(::std::move(RHS));
1223 return *this;
1224 }
1225
1226 SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
1227 SmallVectorImpl<T>::operator=(::std::move(RHS));
1228 return *this;
1229 }
1230
1231 SmallVector &operator=(std::initializer_list<T> IL) {
1232 this->assign(IL);
1233 return *this;
1234 }
1235};
1236
1237template <typename T, unsigned N>
1238inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
1239 return X.capacity_in_bytes();
1240}
1241
1242/// Given a range of type R, iterate the entire range and return a
1243/// SmallVector with elements of the vector. This is useful, for example,
1244/// when you want to iterate a range and then sort the results.
1245template <unsigned Size, typename R>
1246SmallVector<typename std::remove_const<typename std::remove_reference<
1247 decltype(*std::begin(std::declval<R &>()))>::type>::type,
1248 Size>
1249to_vector(R &&Range) {
1250 return {std::begin(Range), std::end(Range)};
1251}
1252
1253} // end namespace llvm
1254
1255namespace std {
1256
1257 /// Implement std::swap in terms of SmallVector swap.
1258 template<typename T>
1259 inline void
1260 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
1261 LHS.swap(RHS);
1262 }
1263
1264 /// Implement std::swap in terms of SmallVector swap.
1265 template<typename T, unsigned N>
1266 inline void
1267 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
1268 LHS.swap(RHS);
1269 }
1270
1271} // end namespace std
1272
1273#endif // LLVM_ADT_SMALLVECTOR_H

/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LocInfoType.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/PrettyPrinter.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/AST/TypeOrdering.h"
37#include "clang/Basic/BitmaskEnum.h"
38#include "clang/Basic/ExpressionTraits.h"
39#include "clang/Basic/Module.h"
40#include "clang/Basic/OpenCLOptions.h"
41#include "clang/Basic/OpenMPKinds.h"
42#include "clang/Basic/PragmaKinds.h"
43#include "clang/Basic/Specifiers.h"
44#include "clang/Basic/TemplateKinds.h"
45#include "clang/Basic/TypeTraits.h"
46#include "clang/Sema/AnalysisBasedWarnings.h"
47#include "clang/Sema/CleanupInfo.h"
48#include "clang/Sema/DeclSpec.h"
49#include "clang/Sema/ExternalSemaSource.h"
50#include "clang/Sema/IdentifierResolver.h"
51#include "clang/Sema/ObjCMethodList.h"
52#include "clang/Sema/Ownership.h"
53#include "clang/Sema/Scope.h"
54#include "clang/Sema/SemaConcept.h"
55#include "clang/Sema/TypoCorrection.h"
56#include "clang/Sema/Weak.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/Optional.h"
59#include "llvm/ADT/SetVector.h"
60#include "llvm/ADT/SmallBitVector.h"
61#include "llvm/ADT/SmallPtrSet.h"
62#include "llvm/ADT/SmallSet.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/ADT/TinyPtrVector.h"
65#include "llvm/Frontend/OpenMP/OMPConstants.h"
66#include <deque>
67#include <memory>
68#include <string>
69#include <tuple>
70#include <vector>
71
72namespace llvm {
73 class APSInt;
74 template <typename ValueT> struct DenseMapInfo;
75 template <typename ValueT, typename ValueInfoT> class DenseSet;
76 class SmallBitVector;
77 struct InlineAsmIdentifierInfo;
78}
79
80namespace clang {
81 class ADLResult;
82 class ASTConsumer;
83 class ASTContext;
84 class ASTMutationListener;
85 class ASTReader;
86 class ASTWriter;
87 class ArrayType;
88 class ParsedAttr;
89 class BindingDecl;
90 class BlockDecl;
91 class CapturedDecl;
92 class CXXBasePath;
93 class CXXBasePaths;
94 class CXXBindTemporaryExpr;
95 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
96 class CXXConstructorDecl;
97 class CXXConversionDecl;
98 class CXXDeleteExpr;
99 class CXXDestructorDecl;
100 class CXXFieldCollector;
101 class CXXMemberCallExpr;
102 class CXXMethodDecl;
103 class CXXScopeSpec;
104 class CXXTemporary;
105 class CXXTryStmt;
106 class CallExpr;
107 class ClassTemplateDecl;
108 class ClassTemplatePartialSpecializationDecl;
109 class ClassTemplateSpecializationDecl;
110 class VarTemplatePartialSpecializationDecl;
111 class CodeCompleteConsumer;
112 class CodeCompletionAllocator;
113 class CodeCompletionTUInfo;
114 class CodeCompletionResult;
115 class CoroutineBodyStmt;
116 class Decl;
117 class DeclAccessPair;
118 class DeclContext;
119 class DeclRefExpr;
120 class DeclaratorDecl;
121 class DeducedTemplateArgument;
122 class DependentDiagnostic;
123 class DesignatedInitExpr;
124 class Designation;
125 class EnableIfAttr;
126 class EnumConstantDecl;
127 class Expr;
128 class ExtVectorType;
129 class FormatAttr;
130 class FriendDecl;
131 class FunctionDecl;
132 class FunctionProtoType;
133 class FunctionTemplateDecl;
134 class ImplicitConversionSequence;
135 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
136 class InitListExpr;
137 class InitializationKind;
138 class InitializationSequence;
139 class InitializedEntity;
140 class IntegerLiteral;
141 class LabelStmt;
142 class LambdaExpr;
143 class LangOptions;
144 class LocalInstantiationScope;
145 class LookupResult;
146 class MacroInfo;
147 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
148 class ModuleLoader;
149 class MultiLevelTemplateArgumentList;
150 class NamedDecl;
151 class ObjCCategoryDecl;
152 class ObjCCategoryImplDecl;
153 class ObjCCompatibleAliasDecl;
154 class ObjCContainerDecl;
155 class ObjCImplDecl;
156 class ObjCImplementationDecl;
157 class ObjCInterfaceDecl;
158 class ObjCIvarDecl;
159 template <class T> class ObjCList;
160 class ObjCMessageExpr;
161 class ObjCMethodDecl;
162 class ObjCPropertyDecl;
163 class ObjCProtocolDecl;
164 class OMPThreadPrivateDecl;
165 class OMPRequiresDecl;
166 class OMPDeclareReductionDecl;
167 class OMPDeclareSimdDecl;
168 class OMPClause;
169 struct OMPVarListLocTy;
170 struct OverloadCandidate;
171 enum class OverloadCandidateParamOrder : char;
172 enum OverloadCandidateRewriteKind : unsigned;
173 class OverloadCandidateSet;
174 class OverloadExpr;
175 class ParenListExpr;
176 class ParmVarDecl;
177 class Preprocessor;
178 class PseudoDestructorTypeStorage;
179 class PseudoObjectExpr;
180 class QualType;
181 class StandardConversionSequence;
182 class Stmt;
183 class StringLiteral;
184 class SwitchStmt;
185 class TemplateArgument;
186 class TemplateArgumentList;
187 class TemplateArgumentLoc;
188 class TemplateDecl;
189 class TemplateInstantiationCallback;
190 class TemplateParameterList;
191 class TemplatePartialOrderingContext;
192 class TemplateTemplateParmDecl;
193 class Token;
194 class TypeAliasDecl;
195 class TypedefDecl;
196 class TypedefNameDecl;
197 class TypeLoc;
198 class TypoCorrectionConsumer;
199 class UnqualifiedId;
200 class UnresolvedLookupExpr;
201 class UnresolvedMemberExpr;
202 class UnresolvedSetImpl;
203 class UnresolvedSetIterator;
204 class UsingDecl;
205 class UsingShadowDecl;
206 class ValueDecl;
207 class VarDecl;
208 class VarTemplateSpecializationDecl;
209 class VisibilityAttr;
210 class VisibleDeclConsumer;
211 class IndirectFieldDecl;
212 struct DeductionFailureInfo;
213 class TemplateSpecCandidateSet;
214
215namespace sema {
216 class AccessedEntity;
217 class BlockScopeInfo;
218 class Capture;
219 class CapturedRegionScopeInfo;
220 class CapturingScopeInfo;
221 class CompoundScopeInfo;
222 class DelayedDiagnostic;
223 class DelayedDiagnosticPool;
224 class FunctionScopeInfo;
225 class LambdaScopeInfo;
226 class PossiblyUnreachableDiag;
227 class SemaPPCallbacks;
228 class TemplateDeductionInfo;
229}
230
231namespace threadSafety {
232 class BeforeSet;
233 void threadSafetyCleanup(BeforeSet* Cache);
234}
235
236// FIXME: No way to easily map from TemplateTypeParmTypes to
237// TemplateTypeParmDecls, so we have this horrible PointerUnion.
238typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
239 SourceLocation> UnexpandedParameterPack;
240
241/// Describes whether we've seen any nullability information for the given
242/// file.
243struct FileNullability {
244 /// The first pointer declarator (of any pointer kind) in the file that does
245 /// not have a corresponding nullability annotation.
246 SourceLocation PointerLoc;
247
248 /// The end location for the first pointer declarator in the file. Used for
249 /// placing fix-its.
250 SourceLocation PointerEndLoc;
251
252 /// Which kind of pointer declarator we saw.
253 uint8_t PointerKind;
254
255 /// Whether we saw any type nullability annotations in the given file.
256 bool SawTypeNullability = false;
257};
258
259/// A mapping from file IDs to a record of whether we've seen nullability
260/// information in that file.
261class FileNullabilityMap {
262 /// A mapping from file IDs to the nullability information for each file ID.
263 llvm::DenseMap<FileID, FileNullability> Map;
264
265 /// A single-element cache based on the file ID.
266 struct {
267 FileID File;
268 FileNullability Nullability;
269 } Cache;
270
271public:
272 FileNullability &operator[](FileID file) {
273 // Check the single-element cache.
274 if (file == Cache.File)
275 return Cache.Nullability;
276
277 // It's not in the single-element cache; flush the cache if we have one.
278 if (!Cache.File.isInvalid()) {
279 Map[Cache.File] = Cache.Nullability;
280 }
281
282 // Pull this entry into the cache.
283 Cache.File = file;
284 Cache.Nullability = Map[file];
285 return Cache.Nullability;
286 }
287};
288
289/// Keeps track of expected type during expression parsing. The type is tied to
290/// a particular token, all functions that update or consume the type take a
291/// start location of the token they are looking at as a parameter. This allows
292/// to avoid updating the type on hot paths in the parser.
293class PreferredTypeBuilder {
294public:
295 PreferredTypeBuilder() = default;
296 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
297
298 void enterCondition(Sema &S, SourceLocation Tok);
299 void enterReturn(Sema &S, SourceLocation Tok);
300 void enterVariableInit(SourceLocation Tok, Decl *D);
301 /// Computing a type for the function argument may require running
302 /// overloading, so we postpone its computation until it is actually needed.
303 ///
304 /// Clients should be very careful when using this funciton, as it stores a
305 /// function_ref, clients should make sure all calls to get() with the same
306 /// location happen while function_ref is alive.
307 void enterFunctionArgument(SourceLocation Tok,
308 llvm::function_ref<QualType()> ComputeType);
309
310 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
311 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
312 SourceLocation OpLoc);
313 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
314 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
315 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
316 /// Handles all type casts, including C-style cast, C++ casts, etc.
317 void enterTypeCast(SourceLocation Tok, QualType CastType);
318
319 QualType get(SourceLocation Tok) const {
320 if (Tok != ExpectedLoc)
321 return QualType();
322 if (!Type.isNull())
323 return Type;
324 if (ComputeType)
325 return ComputeType();
326 return QualType();
327 }
328
329private:
330 /// Start position of a token for which we store expected type.
331 SourceLocation ExpectedLoc;
332 /// Expected type for a token starting at ExpectedLoc.
333 QualType Type;
334 /// A function to compute expected type at ExpectedLoc. It is only considered
335 /// if Type is null.
336 llvm::function_ref<QualType()> ComputeType;
337};
338
339/// Sema - This implements semantic analysis and AST building for C.
340class Sema final {
341 Sema(const Sema &) = delete;
342 void operator=(const Sema &) = delete;
343
344 /// A key method to reduce duplicate debug info from Sema.
345 virtual void anchor();
346
347 ///Source of additional semantic information.
348 ExternalSemaSource *ExternalSource;
349
350 ///Whether Sema has generated a multiplexer and has to delete it.
351 bool isMultiplexExternalSource;
352
353 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
354
355 bool isVisibleSlow(const NamedDecl *D);
356
357 /// Determine whether two declarations should be linked together, given that
358 /// the old declaration might not be visible and the new declaration might
359 /// not have external linkage.
360 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
361 const NamedDecl *New) {
362 if (isVisible(Old))
363 return true;
364 // See comment in below overload for why it's safe to compute the linkage
365 // of the new declaration here.
366 if (New->isExternallyDeclarable()) {
367 assert(Old->isExternallyDeclarable() &&((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 368, __PRETTY_FUNCTION__))
368 "should not have found a non-externally-declarable previous decl")((Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"
) ? static_cast<void> (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 368, __PRETTY_FUNCTION__))
;
369 return true;
370 }
371 return false;
372 }
373 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
374
375 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
376 QualType ResultTy,
377 ArrayRef<QualType> Args);
378
379public:
380 /// The maximum alignment, same as in llvm::Value. We duplicate them here
381 /// because that allows us not to duplicate the constants in clang code,
382 /// which we must to since we can't directly use the llvm constants.
383 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
384 ///
385 /// This is the greatest alignment value supported by load, store, and alloca
386 /// instructions, and global values.
387 static const unsigned MaxAlignmentExponent = 29;
388 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
389
390 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
391 typedef OpaquePtr<TemplateName> TemplateTy;
392 typedef OpaquePtr<QualType> TypeTy;
393
394 OpenCLOptions OpenCLFeatures;
395 FPOptions CurFPFeatures;
396
397 const LangOptions &LangOpts;
398 Preprocessor &PP;
399 ASTContext &Context;
400 ASTConsumer &Consumer;
401 DiagnosticsEngine &Diags;
402 SourceManager &SourceMgr;
403
404 /// Flag indicating whether or not to collect detailed statistics.
405 bool CollectStats;
406
407 /// Code-completion consumer.
408 CodeCompleteConsumer *CodeCompleter;
409
410 /// CurContext - This is the current declaration context of parsing.
411 DeclContext *CurContext;
412
413 /// Generally null except when we temporarily switch decl contexts,
414 /// like in \see ActOnObjCTemporaryExitContainerContext.
415 DeclContext *OriginalLexicalContext;
416
417 /// VAListTagName - The declaration name corresponding to __va_list_tag.
418 /// This is used as part of a hack to omit that class from ADL results.
419 DeclarationName VAListTagName;
420
421 bool MSStructPragmaOn; // True when \#pragma ms_struct on
422
423 /// Controls member pointer representation format under the MS ABI.
424 LangOptions::PragmaMSPointersToMembersKind
425 MSPointerToMemberRepresentationMethod;
426
427 /// Stack of active SEH __finally scopes. Can be empty.
428 SmallVector<Scope*, 2> CurrentSEHFinally;
429
430 /// Source location for newly created implicit MSInheritanceAttrs
431 SourceLocation ImplicitMSInheritanceAttrLoc;
432
433 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
434 /// `TransformTypos` in order to keep track of any TypoExprs that are created
435 /// recursively during typo correction and wipe them away if the correction
436 /// fails.
437 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
438
439 /// pragma clang section kind
440 enum PragmaClangSectionKind {
441 PCSK_Invalid = 0,
442 PCSK_BSS = 1,
443 PCSK_Data = 2,
444 PCSK_Rodata = 3,
445 PCSK_Text = 4,
446 PCSK_Relro = 5
447 };
448
449 enum PragmaClangSectionAction {
450 PCSA_Set = 0,
451 PCSA_Clear = 1
452 };
453
454 struct PragmaClangSection {
455 std::string SectionName;
456 bool Valid = false;
457 SourceLocation PragmaLocation;
458 };
459
460 PragmaClangSection PragmaClangBSSSection;
461 PragmaClangSection PragmaClangDataSection;
462 PragmaClangSection PragmaClangRodataSection;
463 PragmaClangSection PragmaClangRelroSection;
464 PragmaClangSection PragmaClangTextSection;
465
466 enum PragmaMsStackAction {
467 PSK_Reset = 0x0, // #pragma ()
468 PSK_Set = 0x1, // #pragma (value)
469 PSK_Push = 0x2, // #pragma (push[, id])
470 PSK_Pop = 0x4, // #pragma (pop[, id])
471 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
472 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
473 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
474 };
475
476 // #pragma pack and align.
477 class AlignPackInfo {
478 public:
479 // `Native` represents default align mode, which may vary based on the
480 // platform.
481 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
482
483 // #pragma pack info constructor
484 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
485 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
486 assert(Num == PackNumber && "The pack number has been truncated.")((Num == PackNumber && "The pack number has been truncated."
) ? static_cast<void> (0) : __assert_fail ("Num == PackNumber && \"The pack number has been truncated.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 486, __PRETTY_FUNCTION__))
;
487 }
488
489 // #pragma align info constructor
490 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
491 : PackAttr(false), AlignMode(M),
492 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
493
494 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
495
496 AlignPackInfo() : AlignPackInfo(Native, false) {}
497
498 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
499 // integer encoding for it. This should only be passed to
500 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
501 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
502 std::uint32_t Encoding{};
503 if (Info.IsXLStack())
504 Encoding |= IsXLMask;
505
506 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
507
508 if (Info.IsPackAttr())
509 Encoding |= PackAttrMask;
510
511 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
512
513 return Encoding;
514 }
515
516 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
517 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
518 AlignPackInfo::Mode M =
519 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
520 int PackNumber = (Encoding & PackNumMask) >> 4;
521
522 if (Encoding & PackAttrMask)
523 return AlignPackInfo(M, PackNumber, IsXL);
524
525 return AlignPackInfo(M, IsXL);
526 }
527
528 bool IsPackAttr() const { return PackAttr; }
529
530 bool IsAlignAttr() const { return !PackAttr; }
531
532 Mode getAlignMode() const { return AlignMode; }
533
534 unsigned getPackNumber() const { return PackNumber; }
535
536 bool IsPackSet() const {
537 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
538 // attriute on a decl.
539 return PackNumber != UninitPackVal && PackNumber != 0;
540 }
541
542 bool IsXLStack() const { return XLStack; }
543
544 bool operator==(const AlignPackInfo &Info) const {
545 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
546 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
547 Info.XLStack);
548 }
549
550 bool operator!=(const AlignPackInfo &Info) const {
551 return !(*this == Info);
552 }
553
554 private:
555 /// \brief True if this is a pragma pack attribute,
556 /// not a pragma align attribute.
557 bool PackAttr;
558
559 /// \brief The alignment mode that is in effect.
560 Mode AlignMode;
561
562 /// \brief The pack number of the stack.
563 unsigned char PackNumber;
564
565 /// \brief True if it is a XL #pragma align/pack stack.
566 bool XLStack;
567
568 /// \brief Uninitialized pack value.
569 static constexpr unsigned char UninitPackVal = -1;
570
571 // Masks to encode and decode an AlignPackInfo.
572 static constexpr uint32_t IsXLMask{0x0000'0001};
573 static constexpr uint32_t AlignModeMask{0x0000'0006};
574 static constexpr uint32_t PackAttrMask{0x00000'0008};
575 static constexpr uint32_t PackNumMask{0x0000'01F0};
576 };
577
578 template<typename ValueType>
579 struct PragmaStack {
580 struct Slot {
581 llvm::StringRef StackSlotLabel;
582 ValueType Value;
583 SourceLocation PragmaLocation;
584 SourceLocation PragmaPushLocation;
585 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
586 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
587 : StackSlotLabel(StackSlotLabel), Value(Value),
588 PragmaLocation(PragmaLocation),
589 PragmaPushLocation(PragmaPushLocation) {}
590 };
591
592 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
593 llvm::StringRef StackSlotLabel, ValueType Value) {
594 if (Action == PSK_Reset) {
595 CurrentValue = DefaultValue;
596 CurrentPragmaLocation = PragmaLocation;
597 return;
598 }
599 if (Action & PSK_Push)
600 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
601 PragmaLocation);
602 else if (Action & PSK_Pop) {
603 if (!StackSlotLabel.empty()) {
604 // If we've got a label, try to find it and jump there.
605 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
606 return x.StackSlotLabel == StackSlotLabel;
607 });
608 // If we found the label so pop from there.
609 if (I != Stack.rend()) {
610 CurrentValue = I->Value;
611 CurrentPragmaLocation = I->PragmaLocation;
612 Stack.erase(std::prev(I.base()), Stack.end());
613 }
614 } else if (!Stack.empty()) {
615 // We do not have a label, just pop the last entry.
616 CurrentValue = Stack.back().Value;
617 CurrentPragmaLocation = Stack.back().PragmaLocation;
618 Stack.pop_back();
619 }
620 }
621 if (Action & PSK_Set) {
622 CurrentValue = Value;
623 CurrentPragmaLocation = PragmaLocation;
624 }
625 }
626
627 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
628 // method body to restore the stacks on exit, so it works like this:
629 //
630 // struct S {
631 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
632 // void Method {}
633 // #pragma <name>(pop, InternalPragmaSlot)
634 // };
635 //
636 // It works even with #pragma vtordisp, although MSVC doesn't support
637 // #pragma vtordisp(push [, id], n)
638 // syntax.
639 //
640 // Push / pop a named sentinel slot.
641 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
642 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 643, __PRETTY_FUNCTION__))
643 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 643, __PRETTY_FUNCTION__))
;
644 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
645 }
646
647 // Constructors.
648 explicit PragmaStack(const ValueType &Default)
649 : DefaultValue(Default), CurrentValue(Default) {}
650
651 bool hasValue() const { return CurrentValue != DefaultValue; }
652
653 SmallVector<Slot, 2> Stack;
654 ValueType DefaultValue; // Value used for PSK_Reset action.
655 ValueType CurrentValue;
656 SourceLocation CurrentPragmaLocation;
657 };
658 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
659 // we shouldn't do so if they're in a module).
660
661 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
662 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
663 ///
664 /// 0: Suppress all vtordisps
665 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
666 /// structors
667 /// 2: Always insert vtordisps to support RTTI on partially constructed
668 /// objects
669 PragmaStack<MSVtorDispMode> VtorDispStack;
670 PragmaStack<AlignPackInfo> AlignPackStack;
671 // The current #pragma align/pack values and locations at each #include.
672 struct AlignPackIncludeState {
673 AlignPackInfo CurrentValue;
674 SourceLocation CurrentPragmaLocation;
675 bool HasNonDefaultValue, ShouldWarnOnInclude;
676 };
677 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
678 // Segment #pragmas.
679 PragmaStack<StringLiteral *> DataSegStack;
680 PragmaStack<StringLiteral *> BSSSegStack;
681 PragmaStack<StringLiteral *> ConstSegStack;
682 PragmaStack<StringLiteral *> CodeSegStack;
683
684 // This stack tracks the current state of Sema.CurFPFeatures.
685 PragmaStack<FPOptionsOverride> FpPragmaStack;
686 FPOptionsOverride CurFPFeatureOverrides() {
687 FPOptionsOverride result;
688 if (!FpPragmaStack.hasValue()) {
689 result = FPOptionsOverride();
690 } else {
691 result = FpPragmaStack.CurrentValue;
692 }
693 return result;
694 }
695
696 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
697 // Actions should be performed only if we enter / exit a C++ method body.
698 class PragmaStackSentinelRAII {
699 public:
700 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
701 ~PragmaStackSentinelRAII();
702
703 private:
704 Sema &S;
705 StringRef SlotLabel;
706 bool ShouldAct;
707 };
708
709 /// A mapping that describes the nullability we've seen in each header file.
710 FileNullabilityMap NullabilityMap;
711
712 /// Last section used with #pragma init_seg.
713 StringLiteral *CurInitSeg;
714 SourceLocation CurInitSegLoc;
715
716 /// VisContext - Manages the stack for \#pragma GCC visibility.
717 void *VisContext; // Really a "PragmaVisStack*"
718
719 /// This an attribute introduced by \#pragma clang attribute.
720 struct PragmaAttributeEntry {
721 SourceLocation Loc;
722 ParsedAttr *Attribute;
723 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
724 bool IsUsed;
725 };
726
727 /// A push'd group of PragmaAttributeEntries.
728 struct PragmaAttributeGroup {
729 /// The location of the push attribute.
730 SourceLocation Loc;
731 /// The namespace of this push group.
732 const IdentifierInfo *Namespace;
733 SmallVector<PragmaAttributeEntry, 2> Entries;
734 };
735
736 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
737
738 /// The declaration that is currently receiving an attribute from the
739 /// #pragma attribute stack.
740 const Decl *PragmaAttributeCurrentTargetDecl;
741
742 /// This represents the last location of a "#pragma clang optimize off"
743 /// directive if such a directive has not been closed by an "on" yet. If
744 /// optimizations are currently "on", this is set to an invalid location.
745 SourceLocation OptimizeOffPragmaLocation;
746
747 /// Flag indicating if Sema is building a recovery call expression.
748 ///
749 /// This flag is used to avoid building recovery call expressions
750 /// if Sema is already doing so, which would cause infinite recursions.
751 bool IsBuildingRecoveryCallExpr;
752
753 /// Used to control the generation of ExprWithCleanups.
754 CleanupInfo Cleanup;
755
756 /// ExprCleanupObjects - This is the stack of objects requiring
757 /// cleanup that are created by the current full expression.
758 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
759
760 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
761 /// to a variable (constant) that may or may not be odr-used in this Expr, and
762 /// we won't know until all lvalue-to-rvalue and discarded value conversions
763 /// have been applied to all subexpressions of the enclosing full expression.
764 /// This is cleared at the end of each full expression.
765 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
766 llvm::SmallPtrSet<Expr *, 4>>;
767 MaybeODRUseExprSet MaybeODRUseExprs;
768
769 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
770
771 /// Stack containing information about each of the nested
772 /// function, block, and method scopes that are currently active.
773 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
774
775 /// The index of the first FunctionScope that corresponds to the current
776 /// context.
777 unsigned FunctionScopesStart = 0;
778
779 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
780 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
781 FunctionScopes.end());
782 }
783
784 /// Stack containing information needed when in C++2a an 'auto' is encountered
785 /// in a function declaration parameter type specifier in order to invent a
786 /// corresponding template parameter in the enclosing abbreviated function
787 /// template. This information is also present in LambdaScopeInfo, stored in
788 /// the FunctionScopes stack.
789 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
790
791 /// The index of the first InventedParameterInfo that refers to the current
792 /// context.
793 unsigned InventedParameterInfosStart = 0;
794
795 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
796 return llvm::makeArrayRef(InventedParameterInfos.begin() +
797 InventedParameterInfosStart,
798 InventedParameterInfos.end());
799 }
800
801 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
802 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
803 ExtVectorDeclsType;
804
805 /// ExtVectorDecls - This is a list all the extended vector types. This allows
806 /// us to associate a raw vector type with one of the ext_vector type names.
807 /// This is only necessary for issuing pretty diagnostics.
808 ExtVectorDeclsType ExtVectorDecls;
809
810 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
811 std::unique_ptr<CXXFieldCollector> FieldCollector;
812
813 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
814
815 /// Set containing all declared private fields that are not used.
816 NamedDeclSetType UnusedPrivateFields;
817
818 /// Set containing all typedefs that are likely unused.
819 llvm::SmallSetVector<const TypedefNameDecl *, 4>
820 UnusedLocalTypedefNameCandidates;
821
822 /// Delete-expressions to be analyzed at the end of translation unit
823 ///
824 /// This list contains class members, and locations of delete-expressions
825 /// that could not be proven as to whether they mismatch with new-expression
826 /// used in initializer of the field.
827 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
828 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
829 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
830
831 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
832
833 /// PureVirtualClassDiagSet - a set of class declarations which we have
834 /// emitted a list of pure virtual functions. Used to prevent emitting the
835 /// same list more than once.
836 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
837
838 /// ParsingInitForAutoVars - a set of declarations with auto types for which
839 /// we are currently parsing the initializer.
840 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
841
842 /// Look for a locally scoped extern "C" declaration by the given name.
843 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
844
845 typedef LazyVector<VarDecl *, ExternalSemaSource,
846 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
847 TentativeDefinitionsType;
848
849 /// All the tentative definitions encountered in the TU.
850 TentativeDefinitionsType TentativeDefinitions;
851
852 /// All the external declarations encoutered and used in the TU.
853 SmallVector<VarDecl *, 4> ExternalDeclarations;
854
855 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
856 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
857 UnusedFileScopedDeclsType;
858
859 /// The set of file scoped decls seen so far that have not been used
860 /// and must warn if not used. Only contains the first declaration.
861 UnusedFileScopedDeclsType UnusedFileScopedDecls;
862
863 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
864 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
865 DelegatingCtorDeclsType;
866
867 /// All the delegating constructors seen so far in the file, used for
868 /// cycle detection at the end of the TU.
869 DelegatingCtorDeclsType DelegatingCtorDecls;
870
871 /// All the overriding functions seen during a class definition
872 /// that had their exception spec checks delayed, plus the overridden
873 /// function.
874 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
875 DelayedOverridingExceptionSpecChecks;
876
877 /// All the function redeclarations seen during a class definition that had
878 /// their exception spec checks delayed, plus the prior declaration they
879 /// should be checked against. Except during error recovery, the new decl
880 /// should always be a friend declaration, as that's the only valid way to
881 /// redeclare a special member before its class is complete.
882 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
883 DelayedEquivalentExceptionSpecChecks;
884
885 typedef llvm::MapVector<const FunctionDecl *,
886 std::unique_ptr<LateParsedTemplate>>
887 LateParsedTemplateMapT;
888 LateParsedTemplateMapT LateParsedTemplateMap;
889
890 /// Callback to the parser to parse templated functions when needed.
891 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
892 typedef void LateTemplateParserCleanupCB(void *P);
893 LateTemplateParserCB *LateTemplateParser;
894 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
895 void *OpaqueParser;
896
897 void SetLateTemplateParser(LateTemplateParserCB *LTP,
898 LateTemplateParserCleanupCB *LTPCleanup,
899 void *P) {
900 LateTemplateParser = LTP;
901 LateTemplateParserCleanup = LTPCleanup;
902 OpaqueParser = P;
903 }
904
905 class DelayedDiagnostics;
906
907 class DelayedDiagnosticsState {
908 sema::DelayedDiagnosticPool *SavedPool;
909 friend class Sema::DelayedDiagnostics;
910 };
911 typedef DelayedDiagnosticsState ParsingDeclState;
912 typedef DelayedDiagnosticsState ProcessingContextState;
913
914 /// A class which encapsulates the logic for delaying diagnostics
915 /// during parsing and other processing.
916 class DelayedDiagnostics {
917 /// The current pool of diagnostics into which delayed
918 /// diagnostics should go.
919 sema::DelayedDiagnosticPool *CurPool;
920
921 public:
922 DelayedDiagnostics() : CurPool(nullptr) {}
923
924 /// Adds a delayed diagnostic.
925 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
926
927 /// Determines whether diagnostics should be delayed.
928 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
929
930 /// Returns the current delayed-diagnostics pool.
931 sema::DelayedDiagnosticPool *getCurrentPool() const {
932 return CurPool;
933 }
934
935 /// Enter a new scope. Access and deprecation diagnostics will be
936 /// collected in this pool.
937 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
938 DelayedDiagnosticsState state;
939 state.SavedPool = CurPool;
940 CurPool = &pool;
941 return state;
942 }
943
944 /// Leave a delayed-diagnostic state that was previously pushed.
945 /// Do not emit any of the diagnostics. This is performed as part
946 /// of the bookkeeping of popping a pool "properly".
947 void popWithoutEmitting(DelayedDiagnosticsState state) {
948 CurPool = state.SavedPool;
949 }
950
951 /// Enter a new scope where access and deprecation diagnostics are
952 /// not delayed.
953 DelayedDiagnosticsState pushUndelayed() {
954 DelayedDiagnosticsState state;
955 state.SavedPool = CurPool;
956 CurPool = nullptr;
957 return state;
958 }
959
960 /// Undo a previous pushUndelayed().
961 void popUndelayed(DelayedDiagnosticsState state) {
962 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 962, __PRETTY_FUNCTION__))
;
963 CurPool = state.SavedPool;
964 }
965 } DelayedDiagnostics;
966
967 /// A RAII object to temporarily push a declaration context.
968 class ContextRAII {
969 private:
970 Sema &S;
971 DeclContext *SavedContext;
972 ProcessingContextState SavedContextState;
973 QualType SavedCXXThisTypeOverride;
974 unsigned SavedFunctionScopesStart;
975 unsigned SavedInventedParameterInfosStart;
976
977 public:
978 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
979 : S(S), SavedContext(S.CurContext),
980 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
981 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
982 SavedFunctionScopesStart(S.FunctionScopesStart),
983 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
984 {
985 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 985, __PRETTY_FUNCTION__))
;
986 S.CurContext = ContextToPush;
987 if (NewThisContext)
988 S.CXXThisTypeOverride = QualType();
989 // Any saved FunctionScopes do not refer to this context.
990 S.FunctionScopesStart = S.FunctionScopes.size();
991 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
992 }
993
994 void pop() {
995 if (!SavedContext) return;
996 S.CurContext = SavedContext;
997 S.DelayedDiagnostics.popUndelayed(SavedContextState);
998 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
999 S.FunctionScopesStart = SavedFunctionScopesStart;
1000 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1001 SavedContext = nullptr;
1002 }
1003
1004 ~ContextRAII() {
1005 pop();
1006 }
1007 };
1008
1009 /// Whether the AST is currently being rebuilt to correct immediate
1010 /// invocations. Immediate invocation candidates and references to consteval
1011 /// functions aren't tracked when this is set.
1012 bool RebuildingImmediateInvocation = false;
1013
1014 /// Used to change context to isConstantEvaluated without pushing a heavy
1015 /// ExpressionEvaluationContextRecord object.
1016 bool isConstantEvaluatedOverride;
1017
1018 bool isConstantEvaluated() {
1019 return ExprEvalContexts.back().isConstantEvaluated() ||
1020 isConstantEvaluatedOverride;
1021 }
1022
1023 /// RAII object to handle the state changes required to synthesize
1024 /// a function body.
1025 class SynthesizedFunctionScope {
1026 Sema &S;
1027 Sema::ContextRAII SavedContext;
1028 bool PushedCodeSynthesisContext = false;
1029
1030 public:
1031 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1032 : S(S), SavedContext(S, DC) {
1033 S.PushFunctionScope();
1034 S.PushExpressionEvaluationContext(
1035 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1036 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1037 FD->setWillHaveBody(true);
1038 else
1039 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 1039, __PRETTY_FUNCTION__))
;
1040 }
1041
1042 void addContextNote(SourceLocation UseLoc) {
1043 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 1043, __PRETTY_FUNCTION__))
;
1044
1045 Sema::CodeSynthesisContext Ctx;
1046 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1047 Ctx.PointOfInstantiation = UseLoc;
1048 Ctx.Entity = cast<Decl>(S.CurContext);
1049 S.pushCodeSynthesisContext(Ctx);
1050
1051 PushedCodeSynthesisContext = true;
1052 }
1053
1054 ~SynthesizedFunctionScope() {
1055 if (PushedCodeSynthesisContext)
1056 S.popCodeSynthesisContext();
1057 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1058 FD->setWillHaveBody(false);
1059 S.PopExpressionEvaluationContext();
1060 S.PopFunctionScopeInfo();
1061 }
1062 };
1063
1064 /// WeakUndeclaredIdentifiers - Identifiers contained in
1065 /// \#pragma weak before declared. rare. may alias another
1066 /// identifier, declared or undeclared
1067 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
1068
1069 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1070 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1071 /// to define functions that occur in multiple standards to call the version
1072 /// in the currently selected standard.
1073 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1074
1075
1076 /// Load weak undeclared identifiers from the external source.
1077 void LoadExternalWeakUndeclaredIdentifiers();
1078
1079 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1080 /// \#pragma weak during processing of other Decls.
1081 /// I couldn't figure out a clean way to generate these in-line, so
1082 /// we store them here and handle separately -- which is a hack.
1083 /// It would be best to refactor this.
1084 SmallVector<Decl*,2> WeakTopLevelDecl;
1085
1086 IdentifierResolver IdResolver;
1087
1088 /// Translation Unit Scope - useful to Objective-C actions that need
1089 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1090 /// For example, user-defined classes, built-in "id" type, etc.
1091 Scope *TUScope;
1092
1093 /// The C++ "std" namespace, where the standard library resides.
1094 LazyDeclPtr StdNamespace;
1095
1096 /// The C++ "std::bad_alloc" class, which is defined by the C++
1097 /// standard library.
1098 LazyDeclPtr StdBadAlloc;
1099
1100 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1101 /// standard library.
1102 LazyDeclPtr StdAlignValT;
1103
1104 /// The C++ "std::experimental" namespace, where the experimental parts
1105 /// of the standard library resides.
1106 NamespaceDecl *StdExperimentalNamespaceCache;
1107
1108 /// The C++ "std::initializer_list" template, which is defined in
1109 /// \<initializer_list>.
1110 ClassTemplateDecl *StdInitializerList;
1111
1112 /// The C++ "std::coroutine_traits" template, which is defined in
1113 /// \<coroutine_traits>
1114 ClassTemplateDecl *StdCoroutineTraitsCache;
1115
1116 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1117 RecordDecl *CXXTypeInfoDecl;
1118
1119 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1120 RecordDecl *MSVCGuidDecl;
1121
1122 /// Caches identifiers/selectors for NSFoundation APIs.
1123 std::unique_ptr<NSAPI> NSAPIObj;
1124
1125 /// The declaration of the Objective-C NSNumber class.
1126 ObjCInterfaceDecl *NSNumberDecl;
1127
1128 /// The declaration of the Objective-C NSValue class.
1129 ObjCInterfaceDecl *NSValueDecl;
1130
1131 /// Pointer to NSNumber type (NSNumber *).
1132 QualType NSNumberPointer;
1133
1134 /// Pointer to NSValue type (NSValue *).
1135 QualType NSValuePointer;
1136
1137 /// The Objective-C NSNumber methods used to create NSNumber literals.
1138 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1139
1140 /// The declaration of the Objective-C NSString class.
1141 ObjCInterfaceDecl *NSStringDecl;
1142
1143 /// Pointer to NSString type (NSString *).
1144 QualType NSStringPointer;
1145
1146 /// The declaration of the stringWithUTF8String: method.
1147 ObjCMethodDecl *StringWithUTF8StringMethod;
1148
1149 /// The declaration of the valueWithBytes:objCType: method.
1150 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1151
1152 /// The declaration of the Objective-C NSArray class.
1153 ObjCInterfaceDecl *NSArrayDecl;
1154
1155 /// The declaration of the arrayWithObjects:count: method.
1156 ObjCMethodDecl *ArrayWithObjectsMethod;
1157
1158 /// The declaration of the Objective-C NSDictionary class.
1159 ObjCInterfaceDecl *NSDictionaryDecl;
1160
1161 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1162 ObjCMethodDecl *DictionaryWithObjectsMethod;
1163
1164 /// id<NSCopying> type.
1165 QualType QIDNSCopying;
1166
1167 /// will hold 'respondsToSelector:'
1168 Selector RespondsToSelectorSel;
1169
1170 /// A flag to remember whether the implicit forms of operator new and delete
1171 /// have been declared.
1172 bool GlobalNewDeleteDeclared;
1173
1174 /// Describes how the expressions currently being parsed are
1175 /// evaluated at run-time, if at all.
1176 enum class ExpressionEvaluationContext {
1177 /// The current expression and its subexpressions occur within an
1178 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1179 /// \c sizeof, where the type of the expression may be significant but
1180 /// no code will be generated to evaluate the value of the expression at
1181 /// run time.
1182 Unevaluated,
1183
1184 /// The current expression occurs within a braced-init-list within
1185 /// an unevaluated operand. This is mostly like a regular unevaluated
1186 /// context, except that we still instantiate constexpr functions that are
1187 /// referenced here so that we can perform narrowing checks correctly.
1188 UnevaluatedList,
1189
1190 /// The current expression occurs within a discarded statement.
1191 /// This behaves largely similarly to an unevaluated operand in preventing
1192 /// definitions from being required, but not in other ways.
1193 DiscardedStatement,
1194
1195 /// The current expression occurs within an unevaluated
1196 /// operand that unconditionally permits abstract references to
1197 /// fields, such as a SIZE operator in MS-style inline assembly.
1198 UnevaluatedAbstract,
1199
1200 /// The current context is "potentially evaluated" in C++11 terms,
1201 /// but the expression is evaluated at compile-time (like the values of
1202 /// cases in a switch statement).
1203 ConstantEvaluated,
1204
1205 /// The current expression is potentially evaluated at run time,
1206 /// which means that code may be generated to evaluate the value of the
1207 /// expression at run time.
1208 PotentiallyEvaluated,
1209
1210 /// The current expression is potentially evaluated, but any
1211 /// declarations referenced inside that expression are only used if
1212 /// in fact the current expression is used.
1213 ///
1214 /// This value is used when parsing default function arguments, for which
1215 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1216 /// through varargs) but do not want to mark declarations as "referenced"
1217 /// until the default argument is used.
1218 PotentiallyEvaluatedIfUsed
1219 };
1220
1221 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1222
1223 /// Data structure used to record current or nested
1224 /// expression evaluation contexts.
1225 struct ExpressionEvaluationContextRecord {
1226 /// The expression evaluation context.
1227 ExpressionEvaluationContext Context;
1228
1229 /// Whether the enclosing context needed a cleanup.
1230 CleanupInfo ParentCleanup;
1231
1232 /// The number of active cleanup objects when we entered
1233 /// this expression evaluation context.
1234 unsigned NumCleanupObjects;
1235
1236 /// The number of typos encountered during this expression evaluation
1237 /// context (i.e. the number of TypoExprs created).
1238 unsigned NumTypos;
1239
1240 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1241
1242 /// The lambdas that are present within this context, if it
1243 /// is indeed an unevaluated context.
1244 SmallVector<LambdaExpr *, 2> Lambdas;
1245
1246 /// The declaration that provides context for lambda expressions
1247 /// and block literals if the normal declaration context does not
1248 /// suffice, e.g., in a default function argument.
1249 Decl *ManglingContextDecl;
1250
1251 /// If we are processing a decltype type, a set of call expressions
1252 /// for which we have deferred checking the completeness of the return type.
1253 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1254
1255 /// If we are processing a decltype type, a set of temporary binding
1256 /// expressions for which we have deferred checking the destructor.
1257 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1258
1259 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1260
1261 /// Expressions appearing as the LHS of a volatile assignment in this
1262 /// context. We produce a warning for these when popping the context if
1263 /// they are not discarded-value expressions nor unevaluated operands.
1264 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1265
1266 /// Set of candidates for starting an immediate invocation.
1267 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1268
1269 /// Set of DeclRefExprs referencing a consteval function when used in a
1270 /// context not already known to be immediately invoked.
1271 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1272
1273 /// \brief Describes whether we are in an expression constext which we have
1274 /// to handle differently.
1275 enum ExpressionKind {
1276 EK_Decltype, EK_TemplateArgument, EK_Other
1277 } ExprContext;
1278
1279 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1280 unsigned NumCleanupObjects,
1281 CleanupInfo ParentCleanup,
1282 Decl *ManglingContextDecl,
1283 ExpressionKind ExprContext)
1284 : Context(Context), ParentCleanup(ParentCleanup),
1285 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1286 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1287
1288 bool isUnevaluated() const {
1289 return Context == ExpressionEvaluationContext::Unevaluated ||
1290 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1291 Context == ExpressionEvaluationContext::UnevaluatedList;
1292 }
1293 bool isConstantEvaluated() const {
1294 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1295 }
1296 };
1297
1298 /// A stack of expression evaluation contexts.
1299 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1300
1301 /// Emit a warning for all pending noderef expressions that we recorded.
1302 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1303
1304 /// Compute the mangling number context for a lambda expression or
1305 /// block literal. Also return the extra mangling decl if any.
1306 ///
1307 /// \param DC - The DeclContext containing the lambda expression or
1308 /// block literal.
1309 std::tuple<MangleNumberingContext *, Decl *>
1310 getCurrentMangleNumberContext(const DeclContext *DC);
1311
1312
1313 /// SpecialMemberOverloadResult - The overloading result for a special member
1314 /// function.
1315 ///
1316 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1317 /// integer are used to determine whether overload resolution succeeded.
1318 class SpecialMemberOverloadResult {
1319 public:
1320 enum Kind {
1321 NoMemberOrDeleted,
1322 Ambiguous,
1323 Success
1324 };
1325
1326 private:
1327 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1328
1329 public:
1330 SpecialMemberOverloadResult() : Pair() {}
1331 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1332 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1333
1334 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1335 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1336
1337 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1338 void setKind(Kind K) { Pair.setInt(K); }
1339 };
1340
1341 class SpecialMemberOverloadResultEntry
1342 : public llvm::FastFoldingSetNode,
1343 public SpecialMemberOverloadResult {
1344 public:
1345 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1346 : FastFoldingSetNode(ID)
1347 {}
1348 };
1349
1350 /// A cache of special member function overload resolution results
1351 /// for C++ records.
1352 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1353
1354 /// A cache of the flags available in enumerations with the flag_bits
1355 /// attribute.
1356 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1357
1358 /// The kind of translation unit we are processing.
1359 ///
1360 /// When we're processing a complete translation unit, Sema will perform
1361 /// end-of-translation-unit semantic tasks (such as creating
1362 /// initializers for tentative definitions in C) once parsing has
1363 /// completed. Modules and precompiled headers perform different kinds of
1364 /// checks.
1365 TranslationUnitKind TUKind;
1366
1367 llvm::BumpPtrAllocator BumpAlloc;
1368
1369 /// The number of SFINAE diagnostics that have been trapped.
1370 unsigned NumSFINAEErrors;
1371
1372 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1373 UnparsedDefaultArgInstantiationsMap;
1374
1375 /// A mapping from parameters with unparsed default arguments to the
1376 /// set of instantiations of each parameter.
1377 ///
1378 /// This mapping is a temporary data structure used when parsing
1379 /// nested class templates or nested classes of class templates,
1380 /// where we might end up instantiating an inner class before the
1381 /// default arguments of its methods have been parsed.
1382 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1383
1384 // Contains the locations of the beginning of unparsed default
1385 // argument locations.
1386 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1387
1388 /// UndefinedInternals - all the used, undefined objects which require a
1389 /// definition in this translation unit.
1390 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1391
1392 /// Determine if VD, which must be a variable or function, is an external
1393 /// symbol that nonetheless can't be referenced from outside this translation
1394 /// unit because its type has no linkage and it's not extern "C".
1395 bool isExternalWithNoLinkageType(ValueDecl *VD);
1396
1397 /// Obtain a sorted list of functions that are undefined but ODR-used.
1398 void getUndefinedButUsed(
1399 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1400
1401 /// Retrieves list of suspicious delete-expressions that will be checked at
1402 /// the end of translation unit.
1403 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1404 getMismatchingDeleteExpressions() const;
1405
1406 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1407 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1408
1409 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1410 /// We need to maintain a list, since selectors can have differing signatures
1411 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1412 /// of selectors are "overloaded").
1413 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1414 /// methods inside categories with a particular selector.
1415 GlobalMethodPool MethodPool;
1416
1417 /// Method selectors used in a \@selector expression. Used for implementation
1418 /// of -Wselector.
1419 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1420
1421 /// List of SourceLocations where 'self' is implicitly retained inside a
1422 /// block.
1423 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1424 ImplicitlyRetainedSelfLocs;
1425
1426 /// Kinds of C++ special members.
1427 enum CXXSpecialMember {
1428 CXXDefaultConstructor,
1429 CXXCopyConstructor,
1430 CXXMoveConstructor,
1431 CXXCopyAssignment,
1432 CXXMoveAssignment,
1433 CXXDestructor,
1434 CXXInvalid
1435 };
1436
1437 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1438 SpecialMemberDecl;
1439
1440 /// The C++ special members which we are currently in the process of
1441 /// declaring. If this process recursively triggers the declaration of the
1442 /// same special member, we should act as if it is not yet declared.
1443 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1444
1445 /// Kinds of defaulted comparison operator functions.
1446 enum class DefaultedComparisonKind : unsigned char {
1447 /// This is not a defaultable comparison operator.
1448 None,
1449 /// This is an operator== that should be implemented as a series of
1450 /// subobject comparisons.
1451 Equal,
1452 /// This is an operator<=> that should be implemented as a series of
1453 /// subobject comparisons.
1454 ThreeWay,
1455 /// This is an operator!= that should be implemented as a rewrite in terms
1456 /// of a == comparison.
1457 NotEqual,
1458 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1459 /// terms of a <=> comparison.
1460 Relational,
1461 };
1462
1463 /// The function definitions which were renamed as part of typo-correction
1464 /// to match their respective declarations. We want to keep track of them
1465 /// to ensure that we don't emit a "redefinition" error if we encounter a
1466 /// correctly named definition after the renamed definition.
1467 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1468
1469 /// Stack of types that correspond to the parameter entities that are
1470 /// currently being copy-initialized. Can be empty.
1471 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1472
1473 void ReadMethodPool(Selector Sel);
1474 void updateOutOfDateSelector(Selector Sel);
1475
1476 /// Private Helper predicate to check for 'self'.
1477 bool isSelfExpr(Expr *RExpr);
1478 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1479
1480 /// Cause the active diagnostic on the DiagosticsEngine to be
1481 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1482 /// should not be used elsewhere.
1483 void EmitCurrentDiagnostic(unsigned DiagID);
1484
1485 /// Records and restores the CurFPFeatures state on entry/exit of compound
1486 /// statements.
1487 class FPFeaturesStateRAII {
1488 public:
1489 FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1490 OldOverrides = S.FpPragmaStack.CurrentValue;
1491 }
1492 ~FPFeaturesStateRAII() {
1493 S.CurFPFeatures = OldFPFeaturesState;
1494 S.FpPragmaStack.CurrentValue = OldOverrides;
1495 }
1496 FPOptionsOverride getOverrides() { return OldOverrides; }
1497
1498 private:
1499 Sema& S;
1500 FPOptions OldFPFeaturesState;
1501 FPOptionsOverride OldOverrides;
1502 };
1503
1504 void addImplicitTypedef(StringRef Name, QualType T);
1505
1506 bool WarnedStackExhausted = false;
1507
1508public:
1509 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1510 TranslationUnitKind TUKind = TU_Complete,
1511 CodeCompleteConsumer *CompletionConsumer = nullptr);
1512 ~Sema();
1513
1514 /// Perform initialization that occurs after the parser has been
1515 /// initialized but before it parses anything.
1516 void Initialize();
1517
1518 const LangOptions &getLangOpts() const { return LangOpts; }
1519 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1520 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1521
1522 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1523 SourceManager &getSourceManager() const { return SourceMgr; }
1524 Preprocessor &getPreprocessor() const { return PP; }
1525 ASTContext &getASTContext() const { return Context; }
1526 ASTConsumer &getASTConsumer() const { return Consumer; }
1527 ASTMutationListener *getASTMutationListener() const;
1528 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1529
1530 ///Registers an external source. If an external source already exists,
1531 /// creates a multiplex external source and appends to it.
1532 ///
1533 ///\param[in] E - A non-null external sema source.
1534 ///
1535 void addExternalSource(ExternalSemaSource *E);
1536
1537 void PrintStats() const;
1538
1539 /// Warn that the stack is nearly exhausted.
1540 void warnStackExhausted(SourceLocation Loc);
1541
1542 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1543 /// guaranteed). Produces a warning if we're low on stack space and allocates
1544 /// more in that case. Use this in code that may recurse deeply (for example,
1545 /// in template instantiation) to avoid stack overflow.
1546 void runWithSufficientStackSpace(SourceLocation Loc,
1547 llvm::function_ref<void()> Fn);
1548
1549 /// Helper class that creates diagnostics with optional
1550 /// template instantiation stacks.
1551 ///
1552 /// This class provides a wrapper around the basic DiagnosticBuilder
1553 /// class that emits diagnostics. ImmediateDiagBuilder is
1554 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1555 /// does) and, if the diagnostic comes from inside a template
1556 /// instantiation, printing the template instantiation stack as
1557 /// well.
1558 class ImmediateDiagBuilder : public DiagnosticBuilder {
1559 Sema &SemaRef;
1560 unsigned DiagID;
1561
1562 public:
1563 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1564 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1565 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1566 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1567
1568 // This is a cunning lie. DiagnosticBuilder actually performs move
1569 // construction in its copy constructor (but due to varied uses, it's not
1570 // possible to conveniently express this as actual move construction). So
1571 // the default copy ctor here is fine, because the base class disables the
1572 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1573 // in that case anwyay.
1574 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1575
1576 ~ImmediateDiagBuilder() {
1577 // If we aren't active, there is nothing to do.
1578 if (!isActive()) return;
1579
1580 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1581 // builder itself so it won't emit the diagnostic in its own destructor.
1582 //
1583 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1584 // do its own needless checks to see if the diagnostic needs to be
1585 // emitted. However, because we take care to ensure that the builder
1586 // objects never escape, a sufficiently smart compiler will be able to
1587 // eliminate that code.
1588 Clear();
1589
1590 // Dispatch to Sema to emit the diagnostic.
1591 SemaRef.EmitCurrentDiagnostic(DiagID);
1592 }
1593
1594 /// Teach operator<< to produce an object of the correct type.
1595 template <typename T>
1596 friend const ImmediateDiagBuilder &
1597 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1598 const DiagnosticBuilder &BaseDiag = Diag;
1599 BaseDiag << Value;
1600 return Diag;
1601 }
1602
1603 // It is necessary to limit this to rvalue reference to avoid calling this
1604 // function with a bitfield lvalue argument since non-const reference to
1605 // bitfield is not allowed.
1606 template <typename T, typename = typename std::enable_if<
1607 !std::is_lvalue_reference<T>::value>::type>
1608 const ImmediateDiagBuilder &operator<<(T &&V) const {
1609 const DiagnosticBuilder &BaseDiag = *this;
1610 BaseDiag << std::move(V);
1611 return *this;
1612 }
1613 };
1614
1615 /// A generic diagnostic builder for errors which may or may not be deferred.
1616 ///
1617 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1618 /// which are not allowed to appear inside __device__ functions and are
1619 /// allowed to appear in __host__ __device__ functions only if the host+device
1620 /// function is never codegen'ed.
1621 ///
1622 /// To handle this, we use the notion of "deferred diagnostics", where we
1623 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1624 ///
1625 /// This class lets you emit either a regular diagnostic, a deferred
1626 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1627 /// its constructor, thus simplifying the process of creating these "maybe
1628 /// deferred" diagnostics.
1629 class SemaDiagnosticBuilder {
1630 public:
1631 enum Kind {
1632 /// Emit no diagnostics.
1633 K_Nop,
1634 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1635 K_Immediate,
1636 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1637 /// emit a call stack showing how this function can be reached by an a
1638 /// priori known-emitted function.
1639 K_ImmediateWithCallStack,
1640 /// Create a deferred diagnostic, which is emitted only if the function
1641 /// it's attached to is codegen'ed. Also emit a call stack as with
1642 /// K_ImmediateWithCallStack.
1643 K_Deferred
1644 };
1645
1646 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1647 FunctionDecl *Fn, Sema &S);
1648 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1649 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1650 ~SemaDiagnosticBuilder();
1651
1652 bool isImmediate() const { return ImmediateDiag.hasValue(); }
1653
1654 /// Convertible to bool: True if we immediately emitted an error, false if
1655 /// we didn't emit an error or we created a deferred error.
1656 ///
1657 /// Example usage:
1658 ///
1659 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1660 /// return ExprError();
1661 ///
1662 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1663 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1664 operator bool() const { return isImmediate(); }
1665
1666 template <typename T>
1667 friend const SemaDiagnosticBuilder &
1668 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1669 if (Diag.ImmediateDiag.hasValue())
1670 *Diag.ImmediateDiag << Value;
1671 else if (Diag.PartialDiagId.hasValue())
1672 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1673 << Value;
1674 return Diag;
1675 }
1676
1677 // It is necessary to limit this to rvalue reference to avoid calling this
1678 // function with a bitfield lvalue argument since non-const reference to
1679 // bitfield is not allowed.
1680 template <typename T, typename = typename std::enable_if<
1681 !std::is_lvalue_reference<T>::value>::type>
1682 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1683 if (ImmediateDiag.hasValue())
1684 *ImmediateDiag << std::move(V);
1685 else if (PartialDiagId.hasValue())
1686 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1687 return *this;
1688 }
1689
1690 friend const SemaDiagnosticBuilder &
1691 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1692 if (Diag.ImmediateDiag.hasValue())
1693 PD.Emit(*Diag.ImmediateDiag);
1694 else if (Diag.PartialDiagId.hasValue())
1695 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1696 return Diag;
1697 }
1698
1699 void AddFixItHint(const FixItHint &Hint) const {
1700 if (ImmediateDiag.hasValue())
1701 ImmediateDiag->AddFixItHint(Hint);
1702 else if (PartialDiagId.hasValue())
1703 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1704 }
1705
1706 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1707 return ExprError();
1708 }
1709 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1710 return StmtError();
1711 }
1712 operator ExprResult() const { return ExprError(); }
1713 operator StmtResult() const { return StmtError(); }
1714 operator TypeResult() const { return TypeError(); }
1715 operator DeclResult() const { return DeclResult(true); }
1716 operator MemInitResult() const { return MemInitResult(true); }
1717
1718 private:
1719 Sema &S;
1720 SourceLocation Loc;
1721 unsigned DiagID;
1722 FunctionDecl *Fn;
1723 bool ShowCallStack;
1724
1725 // Invariant: At most one of these Optionals has a value.
1726 // FIXME: Switch these to a Variant once that exists.
1727 llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1728 llvm::Optional<unsigned> PartialDiagId;
1729 };
1730
1731 /// Is the last error level diagnostic immediate. This is used to determined
1732 /// whether the next info diagnostic should be immediate.
1733 bool IsLastErrorImmediate = true;
1734
1735 /// Emit a diagnostic.
1736 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1737 bool DeferHint = false);
1738
1739 /// Emit a partial diagnostic.
1740 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1741 bool DeferHint = false);
1742
1743 /// Build a partial diagnostic.
1744 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1745
1746 /// Whether uncompilable error has occurred. This includes error happens
1747 /// in deferred diagnostics.
1748 bool hasUncompilableErrorOccurred() const;
1749
1750 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1751
1752 /// Get a string to suggest for zero-initialization of a type.
1753 std::string
1754 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1755 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1756
1757 /// Calls \c Lexer::getLocForEndOfToken()
1758 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1759
1760 /// Retrieve the module loader associated with the preprocessor.
1761 ModuleLoader &getModuleLoader() const;
1762
1763 /// Invent a new identifier for parameters of abbreviated templates.
1764 IdentifierInfo *
1765 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1766 unsigned Index);
1767
1768 void emitAndClearUnusedLocalTypedefWarnings();
1769
1770 private:
1771 /// Function or variable declarations to be checked for whether the deferred
1772 /// diagnostics should be emitted.
1773 SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1774
1775 public:
1776 // Emit all deferred diagnostics.
1777 void emitDeferredDiags();
1778
1779 enum TUFragmentKind {
1780 /// The global module fragment, between 'module;' and a module-declaration.
1781 Global,
1782 /// A normal translation unit fragment. For a non-module unit, this is the
1783 /// entire translation unit. Otherwise, it runs from the module-declaration
1784 /// to the private-module-fragment (if any) or the end of the TU (if not).
1785 Normal,
1786 /// The private module fragment, between 'module :private;' and the end of
1787 /// the translation unit.
1788 Private
1789 };
1790
1791 void ActOnStartOfTranslationUnit();
1792 void ActOnEndOfTranslationUnit();
1793 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1794
1795 void CheckDelegatingCtorCycles();
1796
1797 Scope *getScopeForContext(DeclContext *Ctx);
1798
1799 void PushFunctionScope();
1800 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1801 sema::LambdaScopeInfo *PushLambdaScope();
1802
1803 /// This is used to inform Sema what the current TemplateParameterDepth
1804 /// is during Parsing. Currently it is used to pass on the depth
1805 /// when parsing generic lambda 'auto' parameters.
1806 void RecordParsingTemplateParameterDepth(unsigned Depth);
1807
1808 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1809 RecordDecl *RD, CapturedRegionKind K,
1810 unsigned OpenMPCaptureLevel = 0);
1811
1812 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1813 /// time after they've been popped.
1814 class PoppedFunctionScopeDeleter {
1815 Sema *Self;
1816
1817 public:
1818 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1819 void operator()(sema::FunctionScopeInfo *Scope) const;
1820 };
1821
1822 using PoppedFunctionScopePtr =
1823 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1824
1825 PoppedFunctionScopePtr
1826 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1827 const Decl *D = nullptr,
1828 QualType BlockType = QualType());
1829
1830 sema::FunctionScopeInfo *getCurFunction() const {
1831 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1832 }
1833
1834 sema::FunctionScopeInfo *getEnclosingFunction() const;
1835
1836 void setFunctionHasBranchIntoScope();
1837 void setFunctionHasBranchProtectedScope();
1838 void setFunctionHasIndirectGoto();
1839
1840 void PushCompoundScope(bool IsStmtExpr);
1841 void PopCompoundScope();
1842
1843 sema::CompoundScopeInfo &getCurCompoundScope() const;
1844
1845 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1846
1847 /// Retrieve the current block, if any.
1848 sema::BlockScopeInfo *getCurBlock();
1849
1850 /// Get the innermost lambda enclosing the current location, if any. This
1851 /// looks through intervening non-lambda scopes such as local functions and
1852 /// blocks.
1853 sema::LambdaScopeInfo *getEnclosingLambda() const;
1854
1855 /// Retrieve the current lambda scope info, if any.
1856 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1857 /// lambda scope info ignoring all inner capturing scopes that are not
1858 /// lambda scopes.
1859 sema::LambdaScopeInfo *
1860 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1861
1862 /// Retrieve the current generic lambda info, if any.
1863 sema::LambdaScopeInfo *getCurGenericLambda();
1864
1865 /// Retrieve the current captured region, if any.
1866 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1867
1868 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1869 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1870
1871 /// Called before parsing a function declarator belonging to a function
1872 /// declaration.
1873 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1874 unsigned TemplateParameterDepth);
1875
1876 /// Called after parsing a function declarator belonging to a function
1877 /// declaration.
1878 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1879
1880 void ActOnComment(SourceRange Comment);
1881
1882 //===--------------------------------------------------------------------===//
1883 // Type Analysis / Processing: SemaType.cpp.
1884 //
1885
1886 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1887 const DeclSpec *DS = nullptr);
1888 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1889 const DeclSpec *DS = nullptr);
1890 QualType BuildPointerType(QualType T,
1891 SourceLocation Loc, DeclarationName Entity);
1892 QualType BuildReferenceType(QualType T, bool LValueRef,
1893 SourceLocation Loc, DeclarationName Entity);
1894 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1895 Expr *ArraySize, unsigned Quals,
1896 SourceRange Brackets, DeclarationName Entity);
1897 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1898 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1899 SourceLocation AttrLoc);
1900 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
1901 SourceLocation AttrLoc);
1902
1903 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1904 SourceLocation AttrLoc);
1905
1906 /// Same as above, but constructs the AddressSpace index if not provided.
1907 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1908 SourceLocation AttrLoc);
1909
1910 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1911
1912 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1913
1914 /// Build a function type.
1915 ///
1916 /// This routine checks the function type according to C++ rules and
1917 /// under the assumption that the result type and parameter types have
1918 /// just been instantiated from a template. It therefore duplicates
1919 /// some of the behavior of GetTypeForDeclarator, but in a much
1920 /// simpler form that is only suitable for this narrow use case.
1921 ///
1922 /// \param T The return type of the function.
1923 ///
1924 /// \param ParamTypes The parameter types of the function. This array
1925 /// will be modified to account for adjustments to the types of the
1926 /// function parameters.
1927 ///
1928 /// \param Loc The location of the entity whose type involves this
1929 /// function type or, if there is no such entity, the location of the
1930 /// type that will have function type.
1931 ///
1932 /// \param Entity The name of the entity that involves the function
1933 /// type, if known.
1934 ///
1935 /// \param EPI Extra information about the function type. Usually this will
1936 /// be taken from an existing function with the same prototype.
1937 ///
1938 /// \returns A suitable function type, if there are no errors. The
1939 /// unqualified type will always be a FunctionProtoType.
1940 /// Otherwise, returns a NULL type.
1941 QualType BuildFunctionType(QualType T,
1942 MutableArrayRef<QualType> ParamTypes,
1943 SourceLocation Loc, DeclarationName Entity,
1944 const FunctionProtoType::ExtProtoInfo &EPI);
1945
1946 QualType BuildMemberPointerType(QualType T, QualType Class,
1947 SourceLocation Loc,
1948 DeclarationName Entity);
1949 QualType BuildBlockPointerType(QualType T,
1950 SourceLocation Loc, DeclarationName Entity);
1951 QualType BuildParenType(QualType T);
1952 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1953 QualType BuildReadPipeType(QualType T,
1954 SourceLocation Loc);
1955 QualType BuildWritePipeType(QualType T,
1956 SourceLocation Loc);
1957 QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
1958
1959 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1960 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1961
1962 /// Package the given type and TSI into a ParsedType.
1963 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1964 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1965 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1966 static QualType GetTypeFromParser(ParsedType Ty,
1967 TypeSourceInfo **TInfo = nullptr);
1968 CanThrowResult canThrow(const Stmt *E);
1969 /// Determine whether the callee of a particular function call can throw.
1970 /// E, D and Loc are all optional.
1971 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
1972 SourceLocation Loc = SourceLocation());
1973 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1974 const FunctionProtoType *FPT);
1975 void UpdateExceptionSpec(FunctionDecl *FD,
1976 const FunctionProtoType::ExceptionSpecInfo &ESI);
1977 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1978 bool CheckDistantExceptionSpec(QualType T);
1979 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1980 bool CheckEquivalentExceptionSpec(
1981 const FunctionProtoType *Old, SourceLocation OldLoc,
1982 const FunctionProtoType *New, SourceLocation NewLoc);
1983 bool CheckEquivalentExceptionSpec(
1984 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1985 const FunctionProtoType *Old, SourceLocation OldLoc,
1986 const FunctionProtoType *New, SourceLocation NewLoc);
1987 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1988 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1989 const PartialDiagnostic &NestedDiagID,
1990 const PartialDiagnostic &NoteID,
1991 const PartialDiagnostic &NoThrowDiagID,
1992 const FunctionProtoType *Superset,
1993 SourceLocation SuperLoc,
1994 const FunctionProtoType *Subset,
1995 SourceLocation SubLoc);
1996 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1997 const PartialDiagnostic &NoteID,
1998 const FunctionProtoType *Target,
1999 SourceLocation TargetLoc,
2000 const FunctionProtoType *Source,
2001 SourceLocation SourceLoc);
2002
2003 TypeResult ActOnTypeName(Scope *S, Declarator &D);
2004
2005 /// The parser has parsed the context-sensitive type 'instancetype'
2006 /// in an Objective-C message declaration. Return the appropriate type.
2007 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2008
2009 /// Abstract class used to diagnose incomplete types.
2010 struct TypeDiagnoser {
2011 TypeDiagnoser() {}
2012
2013 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2014 virtual ~TypeDiagnoser() {}
2015 };
2016
2017 static int getPrintable(int I) { return I; }
2018 static unsigned getPrintable(unsigned I) { return I; }
2019 static bool getPrintable(bool B) { return B; }
2020 static const char * getPrintable(const char *S) { return S; }
2021 static StringRef getPrintable(StringRef S) { return S; }
2022 static const std::string &getPrintable(const std::string &S) { return S; }
2023 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2024 return II;
2025 }
2026 static DeclarationName getPrintable(DeclarationName N) { return N; }
2027 static QualType getPrintable(QualType T) { return T; }
2028 static SourceRange getPrintable(SourceRange R) { return R; }
2029 static SourceRange getPrintable(SourceLocation L) { return L; }
2030 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2031 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2032
2033 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2034 protected:
2035 unsigned DiagID;
2036 std::tuple<const Ts &...> Args;
2037
2038 template <std::size_t... Is>
2039 void emit(const SemaDiagnosticBuilder &DB,
2040 std::index_sequence<Is...>) const {
2041 // Apply all tuple elements to the builder in order.
2042 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2043 (void)Dummy;
2044 }
2045
2046 public:
2047 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2048 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2049 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 2049, __PRETTY_FUNCTION__))
;
2050 }
2051
2052 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2053 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2054 emit(DB, std::index_sequence_for<Ts...>());
2055 DB << T;
2056 }
2057 };
2058
2059 /// Do a check to make sure \p Name looks like a legal argument for the
2060 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2061 /// is invalid for the given declaration.
2062 ///
2063 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2064 ///
2065 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2066 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2067 const ParsedAttr &AL, bool IsAsync);
2068
2069 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2070 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2071 /// For example, a diagnostic with no other parameters would generally have
2072 /// the form "...%select{incomplete|sizeless}0 type %1...".
2073 template <typename... Ts>
2074 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2075 public:
2076 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2077 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2078
2079 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2080 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2081 this->emit(DB, std::index_sequence_for<Ts...>());
2082 DB << T->isSizelessType() << T;
2083 }
2084 };
2085
2086 enum class CompleteTypeKind {
2087 /// Apply the normal rules for complete types. In particular,
2088 /// treat all sizeless types as incomplete.
2089 Normal,
2090
2091 /// Relax the normal rules for complete types so that they include
2092 /// sizeless built-in types.
2093 AcceptSizeless,
2094
2095 // FIXME: Eventually we should flip the default to Normal and opt in
2096 // to AcceptSizeless rather than opt out of it.
2097 Default = AcceptSizeless
2098 };
2099
2100private:
2101 /// Methods for marking which expressions involve dereferencing a pointer
2102 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2103 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2104 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2105 /// `*p`, but need to check that `address of` is called on it. This requires
2106 /// keeping a container of all pending expressions and checking if the address
2107 /// of them are eventually taken.
2108 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2109 void CheckAddressOfNoDeref(const Expr *E);
2110 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2111
2112 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2113 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2114
2115 struct ModuleScope {
2116 SourceLocation BeginLoc;
2117 clang::Module *Module = nullptr;
2118 bool ModuleInterface = false;
2119 bool ImplicitGlobalModuleFragment = false;
2120 VisibleModuleSet OuterVisibleModules;
2121 };
2122 /// The modules we're currently parsing.
2123 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2124
2125 /// Namespace definitions that we will export when they finish.
2126 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2127
2128 /// Get the module whose scope we are currently within.
2129 Module *getCurrentModule() const {
2130 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2131 }
2132
2133 VisibleModuleSet VisibleModules;
2134
2135public:
2136 /// Get the module owning an entity.
2137 Module *getOwningModule(const Decl *Entity) {
2138 return Entity->getOwningModule();
21
Called C++ object pointer is null
2139 }
2140
2141 /// Make a merged definition of an existing hidden definition \p ND
2142 /// visible at the specified location.
2143 void makeMergedDefinitionVisible(NamedDecl *ND);
2144
2145 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2146
2147 // When loading a non-modular PCH files, this is used to restore module
2148 // visibility.
2149 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2150 VisibleModules.setVisible(Mod, ImportLoc);
2151 }
2152
2153 /// Determine whether a declaration is visible to name lookup.
2154 bool isVisible(const NamedDecl *D) {
2155 return D->isUnconditionallyVisible() || isVisibleSlow(D);
2156 }
2157
2158 /// Determine whether any declaration of an entity is visible.
2159 bool
2160 hasVisibleDeclaration(const NamedDecl *D,
2161 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2162 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2163 }
2164 bool hasVisibleDeclarationSlow(const NamedDecl *D,
2165 llvm::SmallVectorImpl<Module *> *Modules);
2166
2167 bool hasVisibleMergedDefinition(NamedDecl *Def);
2168 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2169
2170 /// Determine if \p D and \p Suggested have a structurally compatible
2171 /// layout as described in C11 6.2.7/1.
2172 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2173
2174 /// Determine if \p D has a visible definition. If not, suggest a declaration
2175 /// that should be made visible to expose the definition.
2176 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2177 bool OnlyNeedComplete = false);
2178 bool hasVisibleDefinition(const NamedDecl *D) {
2179 NamedDecl *Hidden;
2180 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2181 }
2182
2183 /// Determine if the template parameter \p D has a visible default argument.
2184 bool
2185 hasVisibleDefaultArgument(const NamedDecl *D,
2186 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2187
2188 /// Determine if there is a visible declaration of \p D that is an explicit
2189 /// specialization declaration for a specialization of a template. (For a
2190 /// member specialization, use hasVisibleMemberSpecialization.)
2191 bool hasVisibleExplicitSpecialization(
2192 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2193
2194 /// Determine if there is a visible declaration of \p D that is a member
2195 /// specialization declaration (as opposed to an instantiated declaration).
2196 bool hasVisibleMemberSpecialization(
2197 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2198
2199 /// Determine if \p A and \p B are equivalent internal linkage declarations
2200 /// from different modules, and thus an ambiguity error can be downgraded to
2201 /// an extension warning.
2202 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2203 const NamedDecl *B);
2204 void diagnoseEquivalentInternalLinkageDeclarations(
2205 SourceLocation Loc, const NamedDecl *D,
2206 ArrayRef<const NamedDecl *> Equiv);
2207
2208 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2209
2210 bool isCompleteType(SourceLocation Loc, QualType T,
2211 CompleteTypeKind Kind = CompleteTypeKind::Default) {
2212 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2213 }
2214 bool RequireCompleteType(SourceLocation Loc, QualType T,
2215 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2216 bool RequireCompleteType(SourceLocation Loc, QualType T,
2217 CompleteTypeKind Kind, unsigned DiagID);
2218
2219 bool RequireCompleteType(SourceLocation Loc, QualType T,
2220 TypeDiagnoser &Diagnoser) {
2221 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2222 }
2223 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2224 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2225 }
2226
2227 template <typename... Ts>
2228 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2229 const Ts &...Args) {
2230 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2231 return RequireCompleteType(Loc, T, Diagnoser);
2232 }
2233
2234 template <typename... Ts>
2235 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2236 const Ts &... Args) {
2237 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2238 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2239 }
2240
2241 /// Get the type of expression E, triggering instantiation to complete the
2242 /// type if necessary -- that is, if the expression refers to a templated
2243 /// static data member of incomplete array type.
2244 ///
2245 /// May still return an incomplete type if instantiation was not possible or
2246 /// if the type is incomplete for a different reason. Use
2247 /// RequireCompleteExprType instead if a diagnostic is expected for an
2248 /// incomplete expression type.
2249 QualType getCompletedType(Expr *E);
2250
2251 void completeExprArrayBound(Expr *E);
2252 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2253 TypeDiagnoser &Diagnoser);
2254 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2255
2256 template <typename... Ts>
2257 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2258 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2259 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2260 }
2261
2262 template <typename... Ts>
2263 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2264 const Ts &... Args) {
2265 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2266 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2267 }
2268
2269 bool RequireLiteralType(SourceLocation Loc, QualType T,
2270 TypeDiagnoser &Diagnoser);
2271 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2272
2273 template <typename... Ts>
2274 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2275 const Ts &...Args) {
2276 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2277 return RequireLiteralType(Loc, T, Diagnoser);
2278 }
2279
2280 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2281 const CXXScopeSpec &SS, QualType T,
2282 TagDecl *OwnedTagDecl = nullptr);
2283
2284 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
2285 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2286 /// context, such as when building a type for decltype(auto).
2287 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
2288 bool AsUnevaluated = true);
2289 QualType BuildUnaryTransformType(QualType BaseType,
2290 UnaryTransformType::UTTKind UKind,
2291 SourceLocation Loc);
2292
2293 //===--------------------------------------------------------------------===//
2294 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2295 //
2296
2297 struct SkipBodyInfo {
2298 SkipBodyInfo()
2299 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2300 New(nullptr) {}
2301 bool ShouldSkip;
2302 bool CheckSameAsPrevious;
2303 NamedDecl *Previous;
2304 NamedDecl *New;
2305 };
2306
2307 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2308
2309 void DiagnoseUseOfUnimplementedSelectors();
2310
2311 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2312
2313 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2314 Scope *S, CXXScopeSpec *SS = nullptr,
2315 bool isClassName = false, bool HasTrailingDot = false,
2316 ParsedType ObjectType = nullptr,
2317 bool IsCtorOrDtorName = false,
2318 bool WantNontrivialTypeSourceInfo = false,
2319 bool IsClassTemplateDeductionContext = true,
2320 IdentifierInfo **CorrectedII = nullptr);
2321 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2322 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2323 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2324 SourceLocation IILoc,
2325 Scope *S,
2326 CXXScopeSpec *SS,
2327 ParsedType &SuggestedType,
2328 bool IsTemplateName = false);
2329
2330 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2331 /// type name has failed in a dependent context. In these situations, we
2332 /// automatically form a DependentTypeName that will retry lookup in a related
2333 /// scope during instantiation.
2334 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2335 SourceLocation NameLoc,
2336 bool IsTemplateTypeArg);
2337
2338 /// Describes the result of the name lookup and resolution performed
2339 /// by \c ClassifyName().
2340 enum NameClassificationKind {
2341 /// This name is not a type or template in this context, but might be
2342 /// something else.
2343 NC_Unknown,
2344 /// Classification failed; an error has been produced.
2345 NC_Error,
2346 /// The name has been typo-corrected to a keyword.
2347 NC_Keyword,
2348 /// The name was classified as a type.
2349 NC_Type,
2350 /// The name was classified as a specific non-type, non-template
2351 /// declaration. ActOnNameClassifiedAsNonType should be called to
2352 /// convert the declaration to an expression.
2353 NC_NonType,
2354 /// The name was classified as an ADL-only function name.
2355 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2356 /// result to an expression.
2357 NC_UndeclaredNonType,
2358 /// The name denotes a member of a dependent type that could not be
2359 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2360 /// convert the result to an expression.
2361 NC_DependentNonType,
2362 /// The name was classified as an overload set, and an expression
2363 /// representing that overload set has been formed.
2364 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2365 /// expression referencing the overload set.
2366 NC_OverloadSet,
2367 /// The name was classified as a template whose specializations are types.
2368 NC_TypeTemplate,
2369 /// The name was classified as a variable template name.
2370 NC_VarTemplate,
2371 /// The name was classified as a function template name.
2372 NC_FunctionTemplate,
2373 /// The name was classified as an ADL-only function template name.
2374 NC_UndeclaredTemplate,
2375 /// The name was classified as a concept name.
2376 NC_Concept,
2377 };
2378
2379 class NameClassification {
2380 NameClassificationKind Kind;
2381 union {
2382 ExprResult Expr;
2383 NamedDecl *NonTypeDecl;
2384 TemplateName Template;
2385 ParsedType Type;
2386 };
2387
2388 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2389
2390 public:
2391 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2392
2393 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2394
2395 static NameClassification Error() {
2396 return NameClassification(NC_Error);
2397 }
2398
2399 static NameClassification Unknown() {
2400 return NameClassification(NC_Unknown);
2401 }
2402
2403 static NameClassification OverloadSet(ExprResult E) {
2404 NameClassification Result(NC_OverloadSet);
2405 Result.Expr = E;
2406 return Result;
2407 }
2408
2409 static NameClassification NonType(NamedDecl *D) {
2410 NameClassification Result(NC_NonType);
2411 Result.NonTypeDecl = D;
2412 return Result;
2413 }
2414
2415 static NameClassification UndeclaredNonType() {
2416 return NameClassification(NC_UndeclaredNonType);
2417 }
2418
2419 static NameClassification DependentNonType() {
2420 return NameClassification(NC_DependentNonType);
2421 }
2422
2423 static NameClassification TypeTemplate(TemplateName Name) {
2424 NameClassification Result(NC_TypeTemplate);
2425 Result.Template = Name;
2426 return Result;
2427 }
2428
2429 static NameClassification VarTemplate(TemplateName Name) {
2430 NameClassification Result(NC_VarTemplate);
2431 Result.Template = Name;
2432 return Result;
2433 }
2434
2435 static NameClassification FunctionTemplate(TemplateName Name) {
2436 NameClassification Result(NC_FunctionTemplate);
2437 Result.Template = Name;
2438 return Result;
2439 }
2440
2441 static NameClassification Concept(TemplateName Name) {
2442 NameClassification Result(NC_Concept);
2443 Result.Template = Name;
2444 return Result;
2445 }
2446
2447 static NameClassification UndeclaredTemplate(TemplateName Name) {
2448 NameClassification Result(NC_UndeclaredTemplate);
2449 Result.Template = Name;
2450 return Result;
2451 }
2452
2453 NameClassificationKind getKind() const { return Kind; }
2454
2455 ExprResult getExpression() const {
2456 assert(Kind == NC_OverloadSet)((Kind == NC_OverloadSet) ? static_cast<void> (0) : __assert_fail
("Kind == NC_OverloadSet", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 2456, __PRETTY_FUNCTION__))
;
2457 return Expr;
2458 }
2459
2460 ParsedType getType() const {
2461 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 2461, __PRETTY_FUNCTION__))
;
2462 return Type;
2463 }
2464
2465 NamedDecl *getNonTypeDecl() const {
2466 assert(Kind == NC_NonType)((Kind == NC_NonType) ? static_cast<void> (0) : __assert_fail
("Kind == NC_NonType", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 2466, __PRETTY_FUNCTION__))
;
2467 return NonTypeDecl;
2468 }
2469
2470 TemplateName getTemplateName() const {
2471 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate
) ? static_cast<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 2473, __PRETTY_FUNCTION__))
2472 Kind == NC_VarTemplate || Kind == NC_Concept ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate
) ? static_cast<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 2473, __PRETTY_FUNCTION__))
2473 Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate
) ? static_cast<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 2473, __PRETTY_FUNCTION__))
;
2474 return Template;
2475 }
2476
2477 TemplateNameKind getTemplateNameKind() const {
2478 switch (Kind) {
2479 case NC_TypeTemplate:
2480 return TNK_Type_template;
2481 case NC_FunctionTemplate:
2482 return TNK_Function_template;
2483 case NC_VarTemplate:
2484 return TNK_Var_template;
2485 case NC_Concept:
2486 return TNK_Concept_template;
2487 case NC_UndeclaredTemplate:
2488 return TNK_Undeclared_template;
2489 default:
2490 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 2490)
;
2491 }
2492 }
2493 };
2494
2495 /// Perform name lookup on the given name, classifying it based on
2496 /// the results of name lookup and the following token.
2497 ///
2498 /// This routine is used by the parser to resolve identifiers and help direct
2499 /// parsing. When the identifier cannot be found, this routine will attempt
2500 /// to correct the typo and classify based on the resulting name.
2501 ///
2502 /// \param S The scope in which we're performing name lookup.
2503 ///
2504 /// \param SS The nested-name-specifier that precedes the name.
2505 ///
2506 /// \param Name The identifier. If typo correction finds an alternative name,
2507 /// this pointer parameter will be updated accordingly.
2508 ///
2509 /// \param NameLoc The location of the identifier.
2510 ///
2511 /// \param NextToken The token following the identifier. Used to help
2512 /// disambiguate the name.
2513 ///
2514 /// \param CCC The correction callback, if typo correction is desired.
2515 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2516 IdentifierInfo *&Name, SourceLocation NameLoc,
2517 const Token &NextToken,
2518 CorrectionCandidateCallback *CCC = nullptr);
2519
2520 /// Act on the result of classifying a name as an undeclared (ADL-only)
2521 /// non-type declaration.
2522 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2523 SourceLocation NameLoc);
2524 /// Act on the result of classifying a name as an undeclared member of a
2525 /// dependent base class.
2526 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2527 IdentifierInfo *Name,
2528 SourceLocation NameLoc,
2529 bool IsAddressOfOperand);
2530 /// Act on the result of classifying a name as a specific non-type
2531 /// declaration.
2532 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2533 NamedDecl *Found,
2534 SourceLocation NameLoc,
2535 const Token &NextToken);
2536 /// Act on the result of classifying a name as an overload set.
2537 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2538
2539 /// Describes the detailed kind of a template name. Used in diagnostics.
2540 enum class TemplateNameKindForDiagnostics {
2541 ClassTemplate,
2542 FunctionTemplate,
2543 VarTemplate,
2544 AliasTemplate,
2545 TemplateTemplateParam,
2546 Concept,
2547 DependentTemplate
2548 };
2549 TemplateNameKindForDiagnostics
2550 getTemplateNameKindForDiagnostics(TemplateName Name);
2551
2552 /// Determine whether it's plausible that E was intended to be a
2553 /// template-name.
2554 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2555 if (!getLangOpts().CPlusPlus || E.isInvalid())
2556 return false;
2557 Dependent = false;
2558 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2559 return !DRE->hasExplicitTemplateArgs();
2560 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2561 return !ME->hasExplicitTemplateArgs();
2562 Dependent = true;
2563 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2564 return !DSDRE->hasExplicitTemplateArgs();
2565 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2566 return !DSME->hasExplicitTemplateArgs();
2567 // Any additional cases recognized here should also be handled by
2568 // diagnoseExprIntendedAsTemplateName.
2569 return false;
2570 }
2571 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2572 SourceLocation Less,
2573 SourceLocation Greater);
2574
2575 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2576
2577 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2578 MultiTemplateParamsArg TemplateParameterLists);
2579 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2580 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2581 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2582 DeclarationName Name, SourceLocation Loc,
2583 bool IsTemplateId);
2584 void
2585 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2586 SourceLocation FallbackLoc,
2587 SourceLocation ConstQualLoc = SourceLocation(),
2588 SourceLocation VolatileQualLoc = SourceLocation(),
2589 SourceLocation RestrictQualLoc = SourceLocation(),
2590 SourceLocation AtomicQualLoc = SourceLocation(),
2591 SourceLocation UnalignedQualLoc = SourceLocation());
2592
2593 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2594 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2595 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2596 const LookupResult &R);
2597 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2598 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2599 const LookupResult &R);
2600 void CheckShadow(Scope *S, VarDecl *D);
2601
2602 /// Warn if 'E', which is an expression that is about to be modified, refers
2603 /// to a shadowing declaration.
2604 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2605
2606 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2607
2608private:
2609 /// Map of current shadowing declarations to shadowed declarations. Warn if
2610 /// it looks like the user is trying to modify the shadowing declaration.
2611 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2612
2613public:
2614 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2615 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2616 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2617 TypedefNameDecl *NewTD);
2618 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2619 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2620 TypeSourceInfo *TInfo,
2621 LookupResult &Previous);
2622 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2623 LookupResult &Previous, bool &Redeclaration);
2624 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2625 TypeSourceInfo *TInfo,
2626 LookupResult &Previous,
2627 MultiTemplateParamsArg TemplateParamLists,
2628 bool &AddToScope,
2629 ArrayRef<BindingDecl *> Bindings = None);
2630 NamedDecl *
2631 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2632 MultiTemplateParamsArg TemplateParamLists);
2633 // Returns true if the variable declaration is a redeclaration
2634 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2635 void CheckVariableDeclarationType(VarDecl *NewVD);
2636 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2637 Expr *Init);
2638 void CheckCompleteVariableDeclaration(VarDecl *VD);
2639 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2640 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2641
2642 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2643 TypeSourceInfo *TInfo,
2644 LookupResult &Previous,
2645 MultiTemplateParamsArg TemplateParamLists,
2646 bool &AddToScope);
2647 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2648
2649 enum class CheckConstexprKind {
2650 /// Diagnose issues that are non-constant or that are extensions.
2651 Diagnose,
2652 /// Identify whether this function satisfies the formal rules for constexpr
2653 /// functions in the current lanugage mode (with no extensions).
2654 CheckValid
2655 };
2656
2657 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2658 CheckConstexprKind Kind);
2659
2660 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2661 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2662 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2663 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2664 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2665 // Returns true if the function declaration is a redeclaration
2666 bool CheckFunctionDeclaration(Scope *S,
2667 FunctionDecl *NewFD, LookupResult &Previous,
2668 bool IsMemberSpecialization);
2669 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2670 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2671 QualType NewT, QualType OldT);
2672 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2673 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2674 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2675 bool IsDefinition);
2676 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2677 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2678 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2679 SourceLocation Loc,
2680 QualType T);
2681 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2682 SourceLocation NameLoc, IdentifierInfo *Name,
2683 QualType T, TypeSourceInfo *TSInfo,
2684 StorageClass SC);
2685 void ActOnParamDefaultArgument(Decl *param,
2686 SourceLocation EqualLoc,
2687 Expr *defarg);
2688 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2689 SourceLocation ArgLoc);
2690 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2691 ExprResult ConvertParamDefaultArgument(const ParmVarDecl *Param,
2692 Expr *DefaultArg,
2693 SourceLocation EqualLoc);
2694 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2695 SourceLocation EqualLoc);
2696
2697 // Contexts where using non-trivial C union types can be disallowed. This is
2698 // passed to err_non_trivial_c_union_in_invalid_context.
2699 enum NonTrivialCUnionContext {
2700 // Function parameter.
2701 NTCUC_FunctionParam,
2702 // Function return.
2703 NTCUC_FunctionReturn,
2704 // Default-initialized object.
2705 NTCUC_DefaultInitializedObject,
2706 // Variable with automatic storage duration.
2707 NTCUC_AutoVar,
2708 // Initializer expression that might copy from another object.
2709 NTCUC_CopyInit,
2710 // Assignment.
2711 NTCUC_Assignment,
2712 // Compound literal.
2713 NTCUC_CompoundLiteral,
2714 // Block capture.
2715 NTCUC_BlockCapture,
2716 // lvalue-to-rvalue conversion of volatile type.
2717 NTCUC_LValueToRValueVolatile,
2718 };
2719
2720 /// Emit diagnostics if the initializer or any of its explicit or
2721 /// implicitly-generated subexpressions require copying or
2722 /// default-initializing a type that is or contains a C union type that is
2723 /// non-trivial to copy or default-initialize.
2724 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2725
2726 // These flags are passed to checkNonTrivialCUnion.
2727 enum NonTrivialCUnionKind {
2728 NTCUK_Init = 0x1,
2729 NTCUK_Destruct = 0x2,
2730 NTCUK_Copy = 0x4,
2731 };
2732
2733 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2734 /// a non-trivial C union is used in an invalid context.
2735 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2736 NonTrivialCUnionContext UseContext,
2737 unsigned NonTrivialKind);
2738
2739 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2740 void ActOnUninitializedDecl(Decl *dcl);
2741 void ActOnInitializerError(Decl *Dcl);
2742
2743 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2744 void ActOnCXXForRangeDecl(Decl *D);
2745 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2746 IdentifierInfo *Ident,
2747 ParsedAttributes &Attrs,
2748 SourceLocation AttrEnd);
2749 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2750 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2751 void CheckStaticLocalForDllExport(VarDecl *VD);
2752 void FinalizeDeclaration(Decl *D);
2753 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2754 ArrayRef<Decl *> Group);
2755 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2756
2757 /// Should be called on all declarations that might have attached
2758 /// documentation comments.
2759 void ActOnDocumentableDecl(Decl *D);
2760 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2761
2762 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2763 SourceLocation LocAfterDecls);
2764 void CheckForFunctionRedefinition(
2765 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2766 SkipBodyInfo *SkipBody = nullptr);
2767 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2768 MultiTemplateParamsArg TemplateParamLists,
2769 SkipBodyInfo *SkipBody = nullptr);
2770 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2771 SkipBodyInfo *SkipBody = nullptr);
2772 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2773 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2774 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
2775 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2776 bool isObjCMethodDecl(Decl *D) {
2777 return D && isa<ObjCMethodDecl>(D);
2778 }
2779
2780 /// Determine whether we can delay parsing the body of a function or
2781 /// function template until it is used, assuming we don't care about emitting
2782 /// code for that function.
2783 ///
2784 /// This will be \c false if we may need the body of the function in the
2785 /// middle of parsing an expression (where it's impractical to switch to
2786 /// parsing a different function), for instance, if it's constexpr in C++11
2787 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2788 bool canDelayFunctionBody(const Declarator &D);
2789
2790 /// Determine whether we can skip parsing the body of a function
2791 /// definition, assuming we don't care about analyzing its body or emitting
2792 /// code for that function.
2793 ///
2794 /// This will be \c false only if we may need the body of the function in
2795 /// order to parse the rest of the program (for instance, if it is
2796 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2797 bool canSkipFunctionBody(Decl *D);
2798
2799 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2800 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2801 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2802 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2803 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2804
2805 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2806 /// attribute for which parsing is delayed.
2807 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2808
2809 /// Diagnose any unused parameters in the given sequence of
2810 /// ParmVarDecl pointers.
2811 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2812
2813 /// Diagnose whether the size of parameters or return value of a
2814 /// function or obj-c method definition is pass-by-value and larger than a
2815 /// specified threshold.
2816 void
2817 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2818 QualType ReturnTy, NamedDecl *D);
2819
2820 void DiagnoseInvalidJumps(Stmt *Body);
2821 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2822 SourceLocation AsmLoc,
2823 SourceLocation RParenLoc);
2824
2825 /// Handle a C++11 empty-declaration and attribute-declaration.
2826 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2827 SourceLocation SemiLoc);
2828
2829 enum class ModuleDeclKind {
2830 Interface, ///< 'export module X;'
2831 Implementation, ///< 'module X;'
2832 };
2833
2834 /// The parser has processed a module-declaration that begins the definition
2835 /// of a module interface or implementation.
2836 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2837 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2838 ModuleIdPath Path, bool IsFirstDecl);
2839
2840 /// The parser has processed a global-module-fragment declaration that begins
2841 /// the definition of the global module fragment of the current module unit.
2842 /// \param ModuleLoc The location of the 'module' keyword.
2843 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2844
2845 /// The parser has processed a private-module-fragment declaration that begins
2846 /// the definition of the private module fragment of the current module unit.
2847 /// \param ModuleLoc The location of the 'module' keyword.
2848 /// \param PrivateLoc The location of the 'private' keyword.
2849 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2850 SourceLocation PrivateLoc);
2851
2852 /// The parser has processed a module import declaration.
2853 ///
2854 /// \param StartLoc The location of the first token in the declaration. This
2855 /// could be the location of an '@', 'export', or 'import'.
2856 /// \param ExportLoc The location of the 'export' keyword, if any.
2857 /// \param ImportLoc The location of the 'import' keyword.
2858 /// \param Path The module access path.
2859 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2860 SourceLocation ExportLoc,
2861 SourceLocation ImportLoc, ModuleIdPath Path);
2862 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2863 SourceLocation ExportLoc,
2864 SourceLocation ImportLoc, Module *M,
2865 ModuleIdPath Path = {});
2866
2867 /// The parser has processed a module import translated from a
2868 /// #include or similar preprocessing directive.
2869 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2870 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2871
2872 /// The parsed has entered a submodule.
2873 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2874 /// The parser has left a submodule.
2875 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2876
2877 /// Create an implicit import of the given module at the given
2878 /// source location, for error recovery, if possible.
2879 ///
2880 /// This routine is typically used when an entity found by name lookup
2881 /// is actually hidden within a module that we know about but the user
2882 /// has forgotten to import.
2883 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2884 Module *Mod);
2885
2886 /// Kinds of missing import. Note, the values of these enumerators correspond
2887 /// to %select values in diagnostics.
2888 enum class MissingImportKind {
2889 Declaration,
2890 Definition,
2891 DefaultArgument,
2892 ExplicitSpecialization,
2893 PartialSpecialization
2894 };
2895
2896 /// Diagnose that the specified declaration needs to be visible but
2897 /// isn't, and suggest a module import that would resolve the problem.
2898 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2899 MissingImportKind MIK, bool Recover = true);
2900 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2901 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2902 MissingImportKind MIK, bool Recover);
2903
2904 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2905 SourceLocation LBraceLoc);
2906 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2907 SourceLocation RBraceLoc);
2908
2909 /// We've found a use of a templated declaration that would trigger an
2910 /// implicit instantiation. Check that any relevant explicit specializations
2911 /// and partial specializations are visible, and diagnose if not.
2912 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2913
2914 /// Retrieve a suitable printing policy for diagnostics.
2915 PrintingPolicy getPrintingPolicy() const {
2916 return getPrintingPolicy(Context, PP);
2917 }
2918
2919 /// Retrieve a suitable printing policy for diagnostics.
2920 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2921 const Preprocessor &PP);
2922
2923 /// Scope actions.
2924 void ActOnPopScope(SourceLocation Loc, Scope *S);
2925 void ActOnTranslationUnitScope(Scope *S);
2926
2927 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2928 RecordDecl *&AnonRecord);
2929 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2930 MultiTemplateParamsArg TemplateParams,
2931 bool IsExplicitInstantiation,
2932 RecordDecl *&AnonRecord);
2933
2934 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2935 AccessSpecifier AS,
2936 RecordDecl *Record,
2937 const PrintingPolicy &Policy);
2938
2939 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2940 RecordDecl *Record);
2941
2942 /// Common ways to introduce type names without a tag for use in diagnostics.
2943 /// Keep in sync with err_tag_reference_non_tag.
2944 enum NonTagKind {
2945 NTK_NonStruct,
2946 NTK_NonClass,
2947 NTK_NonUnion,
2948 NTK_NonEnum,
2949 NTK_Typedef,
2950 NTK_TypeAlias,
2951 NTK_Template,
2952 NTK_TypeAliasTemplate,
2953 NTK_TemplateTemplateArgument,
2954 };
2955
2956 /// Given a non-tag type declaration, returns an enum useful for indicating
2957 /// what kind of non-tag type this is.
2958 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2959
2960 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2961 TagTypeKind NewTag, bool isDefinition,
2962 SourceLocation NewTagLoc,
2963 const IdentifierInfo *Name);
2964
2965 enum TagUseKind {
2966 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2967 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2968 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2969 TUK_Friend // Friend declaration: 'friend struct foo;'
2970 };
2971
2972 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2973 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2974 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2975 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2976 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2977 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2978 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2979 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2980 SkipBodyInfo *SkipBody = nullptr);
2981
2982 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2983 unsigned TagSpec, SourceLocation TagLoc,
2984 CXXScopeSpec &SS, IdentifierInfo *Name,
2985 SourceLocation NameLoc,
2986 const ParsedAttributesView &Attr,
2987 MultiTemplateParamsArg TempParamLists);
2988
2989 TypeResult ActOnDependentTag(Scope *S,
2990 unsigned TagSpec,
2991 TagUseKind TUK,
2992 const CXXScopeSpec &SS,
2993 IdentifierInfo *Name,
2994 SourceLocation TagLoc,
2995 SourceLocation NameLoc);
2996
2997 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2998 IdentifierInfo *ClassName,
2999 SmallVectorImpl<Decl *> &Decls);
3000 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3001 Declarator &D, Expr *BitfieldWidth);
3002
3003 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3004 Declarator &D, Expr *BitfieldWidth,
3005 InClassInitStyle InitStyle,
3006 AccessSpecifier AS);
3007 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3008 SourceLocation DeclStart, Declarator &D,
3009 Expr *BitfieldWidth,
3010 InClassInitStyle InitStyle,
3011 AccessSpecifier AS,
3012 const ParsedAttr &MSPropertyAttr);
3013
3014 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3015 TypeSourceInfo *TInfo,
3016 RecordDecl *Record, SourceLocation Loc,
3017 bool Mutable, Expr *BitfieldWidth,
3018 InClassInitStyle InitStyle,
3019 SourceLocation TSSL,
3020 AccessSpecifier AS, NamedDecl *PrevDecl,
3021 Declarator *D = nullptr);
3022
3023 bool CheckNontrivialField(FieldDecl *FD);
3024 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3025
3026 enum TrivialABIHandling {
3027 /// The triviality of a method unaffected by "trivial_abi".
3028 TAH_IgnoreTrivialABI,
3029
3030 /// The triviality of a method affected by "trivial_abi".
3031 TAH_ConsiderTrivialABI
3032 };
3033
3034 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3035 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3036 bool Diagnose = false);
3037
3038 /// For a defaulted function, the kind of defaulted function that it is.
3039 class DefaultedFunctionKind {
3040 CXXSpecialMember SpecialMember : 8;
3041 DefaultedComparisonKind Comparison : 8;
3042
3043 public:
3044 DefaultedFunctionKind()
3045 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3046 }
3047 DefaultedFunctionKind(CXXSpecialMember CSM)
3048 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3049 DefaultedFunctionKind(DefaultedComparisonKind Comp)
3050 : SpecialMember(CXXInvalid), Comparison(Comp) {}
3051
3052 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3053 bool isComparison() const {
3054 return Comparison != DefaultedComparisonKind::None;
3055 }
3056
3057 explicit operator bool() const {
3058 return isSpecialMember() || isComparison();
3059 }
3060
3061 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3062 DefaultedComparisonKind asComparison() const { return Comparison; }
3063
3064 /// Get the index of this function kind for use in diagnostics.
3065 unsigned getDiagnosticIndex() const {
3066 static_assert(CXXInvalid > CXXDestructor,
3067 "invalid should have highest index");
3068 static_assert((unsigned)DefaultedComparisonKind::None == 0,
3069 "none should be equal to zero");
3070 return SpecialMember + (unsigned)Comparison;
3071 }
3072 };
3073
3074 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3075
3076 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3077 return getDefaultedFunctionKind(MD).asSpecialMember();
3078 }
3079 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3080 return getDefaultedFunctionKind(FD).asComparison();
3081 }
3082
3083 void ActOnLastBitfield(SourceLocation DeclStart,
3084 SmallVectorImpl<Decl *> &AllIvarDecls);
3085 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3086 Declarator &D, Expr *BitfieldWidth,
3087 tok::ObjCKeywordKind visibility);
3088
3089 // This is used for both record definitions and ObjC interface declarations.
3090 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3091 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3092 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3093
3094 /// ActOnTagStartDefinition - Invoked when we have entered the
3095 /// scope of a tag's definition (e.g., for an enumeration, class,
3096 /// struct, or union).
3097 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3098
3099 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3100 /// Differently from C++, actually parse the body and reject / error out
3101 /// in case of a structural mismatch.
3102 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
3103 SkipBodyInfo &SkipBody);
3104
3105 typedef void *SkippedDefinitionContext;
3106
3107 /// Invoked when we enter a tag definition that we're skipping.
3108 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3109
3110 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
3111
3112 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3113 /// C++ record definition's base-specifiers clause and are starting its
3114 /// member declarations.
3115 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3116 SourceLocation FinalLoc,
3117 bool IsFinalSpelledSealed,
3118 SourceLocation LBraceLoc);
3119
3120 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3121 /// the definition of a tag (enumeration, class, struct, or union).
3122 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3123 SourceRange BraceRange);
3124
3125 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3126
3127 void ActOnObjCContainerFinishDefinition();
3128
3129 /// Invoked when we must temporarily exit the objective-c container
3130 /// scope for parsing/looking-up C constructs.
3131 ///
3132 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3133 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
3134 void ActOnObjCReenterContainerContext(DeclContext *DC);
3135
3136 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3137 /// error parsing the definition of a tag.
3138 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3139
3140 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3141 EnumConstantDecl *LastEnumConst,
3142 SourceLocation IdLoc,
3143 IdentifierInfo *Id,
3144 Expr *val);
3145 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3146 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3147 QualType EnumUnderlyingTy, bool IsFixed,
3148 const EnumDecl *Prev);
3149
3150 /// Determine whether the body of an anonymous enumeration should be skipped.
3151 /// \param II The name of the first enumerator.
3152 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3153 SourceLocation IILoc);
3154
3155 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3156 SourceLocation IdLoc, IdentifierInfo *Id,
3157 const ParsedAttributesView &Attrs,
3158 SourceLocation EqualLoc, Expr *Val);
3159 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3160 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3161 const ParsedAttributesView &Attr);
3162
3163 /// Set the current declaration context until it gets popped.
3164 void PushDeclContext(Scope *S, DeclContext *DC);
3165 void PopDeclContext();
3166
3167 /// EnterDeclaratorContext - Used when we must lookup names in the context
3168 /// of a declarator's nested name specifier.
3169 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3170 void ExitDeclaratorContext(Scope *S);
3171
3172 /// Enter a template parameter scope, after it's been associated with a particular
3173 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3174 /// in the correct order.
3175 void EnterTemplatedContext(Scope *S, DeclContext *DC);
3176
3177 /// Push the parameters of D, which must be a function, into scope.
3178 void ActOnReenterFunctionContext(Scope* S, Decl* D);
3179 void ActOnExitFunctionContext();
3180
3181 DeclContext *getFunctionLevelDeclContext();
3182
3183 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
3184 /// to the function decl for the function being parsed. If we're currently
3185 /// in a 'block', this returns the containing context.
3186 FunctionDecl *getCurFunctionDecl();
3187
3188 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3189 /// the method decl for the method being parsed. If we're currently
3190 /// in a 'block', this returns the containing context.
3191 ObjCMethodDecl *getCurMethodDecl();
3192
3193 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3194 /// or C function we're in, otherwise return null. If we're currently
3195 /// in a 'block', this returns the containing context.
3196 NamedDecl *getCurFunctionOrMethodDecl();
3197
3198 /// Add this decl to the scope shadowed decl chains.
3199 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3200
3201 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3202 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3203 /// true if 'D' belongs to the given declaration context.
3204 ///
3205 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3206 /// enclosing namespace set of the context, rather than contained
3207 /// directly within it.
3208 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3209 bool AllowInlineNamespace = false);
3210
3211 /// Finds the scope corresponding to the given decl context, if it
3212 /// happens to be an enclosing scope. Otherwise return NULL.
3213 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3214
3215 /// Subroutines of ActOnDeclarator().
3216 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3217 TypeSourceInfo *TInfo);
3218 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3219
3220 /// Describes the kind of merge to perform for availability
3221 /// attributes (including "deprecated", "unavailable", and "availability").
3222 enum AvailabilityMergeKind {
3223 /// Don't merge availability attributes at all.
3224 AMK_None,
3225 /// Merge availability attributes for a redeclaration, which requires
3226 /// an exact match.
3227 AMK_Redeclaration,
3228 /// Merge availability attributes for an override, which requires
3229 /// an exact match or a weakening of constraints.
3230 AMK_Override,
3231 /// Merge availability attributes for an implementation of
3232 /// a protocol requirement.
3233 AMK_ProtocolImplementation,
3234 };
3235
3236 /// Describes the kind of priority given to an availability attribute.
3237 ///
3238 /// The sum of priorities deteremines the final priority of the attribute.
3239 /// The final priority determines how the attribute will be merged.
3240 /// An attribute with a lower priority will always remove higher priority
3241 /// attributes for the specified platform when it is being applied. An
3242 /// attribute with a higher priority will not be applied if the declaration
3243 /// already has an availability attribute with a lower priority for the
3244 /// specified platform. The final prirority values are not expected to match
3245 /// the values in this enumeration, but instead should be treated as a plain
3246 /// integer value. This enumeration just names the priority weights that are
3247 /// used to calculate that final vaue.
3248 enum AvailabilityPriority : int {
3249 /// The availability attribute was specified explicitly next to the
3250 /// declaration.
3251 AP_Explicit = 0,
3252
3253 /// The availability attribute was applied using '#pragma clang attribute'.
3254 AP_PragmaClangAttribute = 1,
3255
3256 /// The availability attribute for a specific platform was inferred from
3257 /// an availability attribute for another platform.
3258 AP_InferredFromOtherPlatform = 2
3259 };
3260
3261 /// Attribute merging methods. Return true if a new attribute was added.
3262 AvailabilityAttr *
3263 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3264 IdentifierInfo *Platform, bool Implicit,
3265 VersionTuple Introduced, VersionTuple Deprecated,
3266 VersionTuple Obsoleted, bool IsUnavailable,
3267 StringRef Message, bool IsStrict, StringRef Replacement,
3268 AvailabilityMergeKind AMK, int Priority);
3269 TypeVisibilityAttr *
3270 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3271 TypeVisibilityAttr::VisibilityType Vis);
3272 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3273 VisibilityAttr::VisibilityType Vis);
3274 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3275 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3276 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3277 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3278 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3279 const AttributeCommonInfo &CI,
3280 bool BestCase,
3281 MSInheritanceModel Model);
3282 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3283 IdentifierInfo *Format, int FormatIdx,
3284 int FirstArg);
3285 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3286 StringRef Name);
3287 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3288 StringRef Name);
3289 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3290 const AttributeCommonInfo &CI,
3291 const IdentifierInfo *Ident);
3292 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3293 NoSpeculativeLoadHardeningAttr *
3294 mergeNoSpeculativeLoadHardeningAttr(Decl *D,
3295 const NoSpeculativeLoadHardeningAttr &AL);
3296 SpeculativeLoadHardeningAttr *
3297 mergeSpeculativeLoadHardeningAttr(Decl *D,
3298 const SpeculativeLoadHardeningAttr &AL);
3299 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3300 StringRef Name);
3301 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3302 const AttributeCommonInfo &CI);
3303 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3304 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3305 const InternalLinkageAttr &AL);
3306 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
3307 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
3308 WebAssemblyImportNameAttr *mergeImportNameAttr(
3309 Decl *D, const WebAssemblyImportNameAttr &AL);
3310 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3311 Decl *D, const WebAssemblyImportModuleAttr &AL);
3312 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3313 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3314 const EnforceTCBLeafAttr &AL);
3315
3316 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3317 AvailabilityMergeKind AMK = AMK_Redeclaration);
3318 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3319 LookupResult &OldDecls);
3320 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3321 bool MergeTypeWithOld);
3322 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3323 Scope *S, bool MergeTypeWithOld);
3324 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3325 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3326 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3327 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3328 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3329 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3330 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3331
3332 // AssignmentAction - This is used by all the assignment diagnostic functions
3333 // to represent what is actually causing the operation
3334 enum AssignmentAction {
3335 AA_Assigning,
3336 AA_Passing,
3337 AA_Returning,
3338 AA_Converting,
3339 AA_Initializing,
3340 AA_Sending,
3341 AA_Casting,
3342 AA_Passing_CFAudited
3343 };
3344
3345 /// C++ Overloading.
3346 enum OverloadKind {
3347 /// This is a legitimate overload: the existing declarations are
3348 /// functions or function templates with different signatures.
3349 Ovl_Overload,
3350
3351 /// This is not an overload because the signature exactly matches
3352 /// an existing declaration.
3353 Ovl_Match,
3354
3355 /// This is not an overload because the lookup results contain a
3356 /// non-function.
3357 Ovl_NonFunction
3358 };
3359 OverloadKind CheckOverload(Scope *S,
3360 FunctionDecl *New,
3361 const LookupResult &OldDecls,
3362 NamedDecl *&OldDecl,
3363 bool IsForUsingDecl);
3364 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3365 bool ConsiderCudaAttrs = true,
3366 bool ConsiderRequiresClauses = true);
3367
3368 enum class AllowedExplicit {
3369 /// Allow no explicit functions to be used.
3370 None,
3371 /// Allow explicit conversion functions but not explicit constructors.
3372 Conversions,
3373 /// Allow both explicit conversion functions and explicit constructors.
3374 All
3375 };
3376
3377 ImplicitConversionSequence
3378 TryImplicitConversion(Expr *From, QualType ToType,
3379 bool SuppressUserConversions,
3380 AllowedExplicit AllowExplicit,
3381 bool InOverloadResolution,
3382 bool CStyle,
3383 bool AllowObjCWritebackConversion);
3384
3385 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3386 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3387 bool IsComplexPromotion(QualType FromType, QualType ToType);
3388 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3389 bool InOverloadResolution,
3390 QualType& ConvertedType, bool &IncompatibleObjC);
3391 bool isObjCPointerConversion(QualType FromType, QualType ToType,
3392 QualType& ConvertedType, bool &IncompatibleObjC);
3393 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3394 QualType &ConvertedType);
3395 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3396 QualType& ConvertedType);
3397 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3398 const FunctionProtoType *NewType,
3399 unsigned *ArgPos = nullptr);
3400 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3401 QualType FromType, QualType ToType);
3402
3403 void maybeExtendBlockObject(ExprResult &E);
3404 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3405 bool CheckPointerConversion(Expr *From, QualType ToType,
3406 CastKind &Kind,
3407 CXXCastPath& BasePath,
3408 bool IgnoreBaseAccess,
3409 bool Diagnose = true);
3410 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3411 bool InOverloadResolution,
3412 QualType &ConvertedType);
3413 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3414 CastKind &Kind,
3415 CXXCastPath &BasePath,
3416 bool IgnoreBaseAccess);
3417 bool IsQualificationConversion(QualType FromType, QualType ToType,
3418 bool CStyle, bool &ObjCLifetimeConversion);
3419 bool IsFunctionConversion(QualType FromType, QualType ToType,
3420 QualType &ResultTy);
3421 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3422 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
3423
3424 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3425 const VarDecl *NRVOCandidate,
3426 QualType ResultType,
3427 Expr *Value,
3428 bool AllowNRVO = true);
3429
3430 bool CanPerformAggregateInitializationForOverloadResolution(
3431 const InitializedEntity &Entity, InitListExpr *From);
3432
3433 bool IsStringInit(Expr *Init, const ArrayType *AT);
3434
3435 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3436 ExprResult Init);
3437 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3438 SourceLocation EqualLoc,
3439 ExprResult Init,
3440 bool TopLevelOfInitList = false,
3441 bool AllowExplicit = false);
3442 ExprResult PerformObjectArgumentInitialization(Expr *From,
3443 NestedNameSpecifier *Qualifier,
3444 NamedDecl *FoundDecl,
3445 CXXMethodDecl *Method);
3446
3447 /// Check that the lifetime of the initializer (and its subobjects) is
3448 /// sufficient for initializing the entity, and perform lifetime extension
3449 /// (when permitted) if not.
3450 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3451
3452 ExprResult PerformContextuallyConvertToBool(Expr *From);
3453 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3454
3455 /// Contexts in which a converted constant expression is required.
3456 enum CCEKind {
3457 CCEK_CaseValue, ///< Expression in a case label.
3458 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3459 CCEK_TemplateArg, ///< Value of a non-type template parameter.
3460 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3461 CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
3462 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
3463 };
3464 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3465 llvm::APSInt &Value, CCEKind CCE);
3466 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3467 APValue &Value, CCEKind CCE,
3468 NamedDecl *Dest = nullptr);
3469
3470 /// Abstract base class used to perform a contextual implicit
3471 /// conversion from an expression to any type passing a filter.
3472 class ContextualImplicitConverter {
3473 public:
3474 bool Suppress;
3475 bool SuppressConversion;
3476
3477 ContextualImplicitConverter(bool Suppress = false,
3478 bool SuppressConversion = false)
3479 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3480
3481 /// Determine whether the specified type is a valid destination type
3482 /// for this conversion.
3483 virtual bool match(QualType T) = 0;
3484
3485 /// Emits a diagnostic complaining that the expression does not have
3486 /// integral or enumeration type.
3487 virtual SemaDiagnosticBuilder
3488 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3489
3490 /// Emits a diagnostic when the expression has incomplete class type.
3491 virtual SemaDiagnosticBuilder
3492 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3493
3494 /// Emits a diagnostic when the only matching conversion function
3495 /// is explicit.
3496 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3497 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3498
3499 /// Emits a note for the explicit conversion function.
3500 virtual SemaDiagnosticBuilder
3501 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3502
3503 /// Emits a diagnostic when there are multiple possible conversion
3504 /// functions.
3505 virtual SemaDiagnosticBuilder
3506 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3507
3508 /// Emits a note for one of the candidate conversions.
3509 virtual SemaDiagnosticBuilder
3510 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3511
3512 /// Emits a diagnostic when we picked a conversion function
3513 /// (for cases when we are not allowed to pick a conversion function).
3514 virtual SemaDiagnosticBuilder diagnoseConversion(
3515 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3516
3517 virtual ~ContextualImplicitConverter() {}
3518 };
3519
3520 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3521 bool AllowScopedEnumerations;
3522
3523 public:
3524 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3525 bool Suppress, bool SuppressConversion)
3526 : ContextualImplicitConverter(Suppress, SuppressConversion),
3527 AllowScopedEnumerations(AllowScopedEnumerations) {}
3528
3529 /// Match an integral or (possibly scoped) enumeration type.
3530 bool match(QualType T) override;
3531
3532 SemaDiagnosticBuilder
3533 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3534 return diagnoseNotInt(S, Loc, T);
3535 }
3536
3537 /// Emits a diagnostic complaining that the expression does not have
3538 /// integral or enumeration type.
3539 virtual SemaDiagnosticBuilder
3540 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3541 };
3542
3543 /// Perform a contextual implicit conversion.
3544 ExprResult PerformContextualImplicitConversion(
3545 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3546
3547
3548 enum ObjCSubscriptKind {
3549 OS_Array,
3550 OS_Dictionary,
3551 OS_Error
3552 };
3553 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3554
3555 // Note that LK_String is intentionally after the other literals, as
3556 // this is used for diagnostics logic.
3557 enum ObjCLiteralKind {
3558 LK_Array,
3559 LK_Dictionary,
3560 LK_Numeric,
3561 LK_Boxed,
3562 LK_String,
3563 LK_Block,
3564 LK_None
3565 };
3566 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3567
3568 ExprResult PerformObjectMemberConversion(Expr *From,
3569 NestedNameSpecifier *Qualifier,
3570 NamedDecl *FoundDecl,
3571 NamedDecl *Member);
3572
3573 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3574 // TODO: make this is a typesafe union.
3575 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3576 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3577
3578 using ADLCallKind = CallExpr::ADLCallKind;
3579
3580 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3581 ArrayRef<Expr *> Args,
3582 OverloadCandidateSet &CandidateSet,
3583 bool SuppressUserConversions = false,
3584 bool PartialOverloading = false,
3585 bool AllowExplicit = true,
3586 bool AllowExplicitConversion = false,
3587 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3588 ConversionSequenceList EarlyConversions = None,
3589 OverloadCandidateParamOrder PO = {});
3590 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3591 ArrayRef<Expr *> Args,
3592 OverloadCandidateSet &CandidateSet,
3593 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3594 bool SuppressUserConversions = false,
3595 bool PartialOverloading = false,
3596 bool FirstArgumentIsBase = false);
3597 void AddMethodCandidate(DeclAccessPair FoundDecl,
3598 QualType ObjectType,
3599 Expr::Classification ObjectClassification,
3600 ArrayRef<Expr *> Args,
3601 OverloadCandidateSet& CandidateSet,
3602 bool SuppressUserConversion = false,
3603 OverloadCandidateParamOrder PO = {});
3604 void AddMethodCandidate(CXXMethodDecl *Method,
3605 DeclAccessPair FoundDecl,
3606 CXXRecordDecl *ActingContext, QualType ObjectType,
3607 Expr::Classification ObjectClassification,
3608 ArrayRef<Expr *> Args,
3609 OverloadCandidateSet& CandidateSet,
3610 bool SuppressUserConversions = false,
3611 bool PartialOverloading = false,
3612 ConversionSequenceList EarlyConversions = None,
3613 OverloadCandidateParamOrder PO = {});
3614 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3615 DeclAccessPair FoundDecl,
3616 CXXRecordDecl *ActingContext,
3617 TemplateArgumentListInfo *ExplicitTemplateArgs,
3618 QualType ObjectType,
3619 Expr::Classification ObjectClassification,
3620 ArrayRef<Expr *> Args,
3621 OverloadCandidateSet& CandidateSet,
3622 bool SuppressUserConversions = false,
3623 bool PartialOverloading = false,
3624 OverloadCandidateParamOrder PO = {});
3625 void AddTemplateOverloadCandidate(
3626 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3627 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3628 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3629 bool PartialOverloading = false, bool AllowExplicit = true,
3630 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3631 OverloadCandidateParamOrder PO = {});
3632 bool CheckNonDependentConversions(
3633 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3634 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3635 ConversionSequenceList &Conversions, bool SuppressUserConversions,
3636 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3637 Expr::Classification ObjectClassification = {},
3638 OverloadCandidateParamOrder PO = {});
3639 void AddConversionCandidate(
3640 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3641 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3642 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3643 bool AllowExplicit, bool AllowResultConversion = true);
3644 void AddTemplateConversionCandidate(
3645 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3646 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3647 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3648 bool AllowExplicit, bool AllowResultConversion = true);
3649 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3650 DeclAccessPair FoundDecl,
3651 CXXRecordDecl *ActingContext,
3652 const FunctionProtoType *Proto,
3653 Expr *Object, ArrayRef<Expr *> Args,
3654 OverloadCandidateSet& CandidateSet);
3655 void AddNonMemberOperatorCandidates(
3656 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3657 OverloadCandidateSet &CandidateSet,
3658 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3659 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3660 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3661 OverloadCandidateSet &CandidateSet,
3662 OverloadCandidateParamOrder PO = {});
3663 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3664 OverloadCandidateSet& CandidateSet,
3665 bool IsAssignmentOperator = false,
3666 unsigned NumContextualBoolArguments = 0);
3667 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3668 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3669 OverloadCandidateSet& CandidateSet);
3670 void AddArgumentDependentLookupCandidates(DeclarationName Name,
3671 SourceLocation Loc,
3672 ArrayRef<Expr *> Args,
3673 TemplateArgumentListInfo *ExplicitTemplateArgs,
3674 OverloadCandidateSet& CandidateSet,
3675 bool PartialOverloading = false);
3676
3677 // Emit as a 'note' the specific overload candidate
3678 void NoteOverloadCandidate(
3679 NamedDecl *Found, FunctionDecl *Fn,
3680 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3681 QualType DestType = QualType(), bool TakingAddress = false);
3682
3683 // Emit as a series of 'note's all template and non-templates identified by
3684 // the expression Expr
3685 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3686 bool TakingAddress = false);
3687
3688 /// Check the enable_if expressions on the given function. Returns the first
3689 /// failing attribute, or NULL if they were all successful.
3690 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3691 ArrayRef<Expr *> Args,
3692 bool MissingImplicitThis = false);
3693
3694 /// Find the failed Boolean condition within a given Boolean
3695 /// constant expression, and describe it with a string.
3696 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3697
3698 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3699 /// non-ArgDependent DiagnoseIfAttrs.
3700 ///
3701 /// Argument-dependent diagnose_if attributes should be checked each time a
3702 /// function is used as a direct callee of a function call.
3703 ///
3704 /// Returns true if any errors were emitted.
3705 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3706 const Expr *ThisArg,
3707 ArrayRef<const Expr *> Args,
3708 SourceLocation Loc);
3709
3710 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3711 /// ArgDependent DiagnoseIfAttrs.
3712 ///
3713 /// Argument-independent diagnose_if attributes should be checked on every use
3714 /// of a function.
3715 ///
3716 /// Returns true if any errors were emitted.
3717 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3718 SourceLocation Loc);
3719
3720 /// Returns whether the given function's address can be taken or not,
3721 /// optionally emitting a diagnostic if the address can't be taken.
3722 ///
3723 /// Returns false if taking the address of the function is illegal.
3724 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3725 bool Complain = false,
3726 SourceLocation Loc = SourceLocation());
3727
3728 // [PossiblyAFunctionType] --> [Return]
3729 // NonFunctionType --> NonFunctionType
3730 // R (A) --> R(A)
3731 // R (*)(A) --> R (A)
3732 // R (&)(A) --> R (A)
3733 // R (S::*)(A) --> R (A)
3734 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3735
3736 FunctionDecl *
3737 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3738 QualType TargetType,
3739 bool Complain,
3740 DeclAccessPair &Found,
3741 bool *pHadMultipleCandidates = nullptr);
3742
3743 FunctionDecl *
3744 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3745
3746 bool resolveAndFixAddressOfSingleOverloadCandidate(
3747 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3748
3749 FunctionDecl *
3750 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3751 bool Complain = false,
3752 DeclAccessPair *Found = nullptr);
3753
3754 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3755 ExprResult &SrcExpr,
3756 bool DoFunctionPointerConverion = false,
3757 bool Complain = false,
3758 SourceRange OpRangeForComplaining = SourceRange(),
3759 QualType DestTypeForComplaining = QualType(),
3760 unsigned DiagIDForComplaining = 0);
3761
3762
3763 Expr *FixOverloadedFunctionReference(Expr *E,
3764 DeclAccessPair FoundDecl,
3765 FunctionDecl *Fn);
3766 ExprResult FixOverloadedFunctionReference(ExprResult,
3767 DeclAccessPair FoundDecl,
3768 FunctionDecl *Fn);
3769
3770 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3771 ArrayRef<Expr *> Args,
3772 OverloadCandidateSet &CandidateSet,
3773 bool PartialOverloading = false);
3774 void AddOverloadedCallCandidates(
3775 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
3776 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
3777
3778 // An enum used to represent the different possible results of building a
3779 // range-based for loop.
3780 enum ForRangeStatus {
3781 FRS_Success,
3782 FRS_NoViableFunction,
3783 FRS_DiagnosticIssued
3784 };
3785
3786 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3787 SourceLocation RangeLoc,
3788 const DeclarationNameInfo &NameInfo,
3789 LookupResult &MemberLookup,
3790 OverloadCandidateSet *CandidateSet,
3791 Expr *Range, ExprResult *CallExpr);
3792
3793 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3794 UnresolvedLookupExpr *ULE,
3795 SourceLocation LParenLoc,
3796 MultiExprArg Args,
3797 SourceLocation RParenLoc,
3798 Expr *ExecConfig,
3799 bool AllowTypoCorrection=true,
3800 bool CalleesAddressIsTaken=false);
3801
3802 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3803 MultiExprArg Args, SourceLocation RParenLoc,
3804 OverloadCandidateSet *CandidateSet,
3805 ExprResult *Result);
3806
3807 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
3808 NestedNameSpecifierLoc NNSLoc,
3809 DeclarationNameInfo DNI,
3810 const UnresolvedSetImpl &Fns,
3811 bool PerformADL = true);
3812
3813 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3814 UnaryOperatorKind Opc,
3815 const UnresolvedSetImpl &Fns,
3816 Expr *input, bool RequiresADL = true);
3817
3818 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3819 OverloadedOperatorKind Op,
3820 const UnresolvedSetImpl &Fns,
3821 ArrayRef<Expr *> Args, bool RequiresADL = true);
3822 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3823 BinaryOperatorKind Opc,
3824 const UnresolvedSetImpl &Fns,
3825 Expr *LHS, Expr *RHS,
3826 bool RequiresADL = true,
3827 bool AllowRewrittenCandidates = true,
3828 FunctionDecl *DefaultedFn = nullptr);
3829 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
3830 const UnresolvedSetImpl &Fns,
3831 Expr *LHS, Expr *RHS,
3832 FunctionDecl *DefaultedFn);
3833
3834 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3835 SourceLocation RLoc,
3836 Expr *Base,Expr *Idx);
3837
3838 ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3839 SourceLocation LParenLoc,
3840 MultiExprArg Args,
3841 SourceLocation RParenLoc,
3842 bool AllowRecovery = false);
3843 ExprResult
3844 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3845 MultiExprArg Args,
3846 SourceLocation RParenLoc);
3847
3848 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3849 SourceLocation OpLoc,
3850 bool *NoArrowOperatorFound = nullptr);
3851
3852 /// CheckCallReturnType - Checks that a call expression's return type is
3853 /// complete. Returns true on failure. The location passed in is the location
3854 /// that best represents the call.
3855 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3856 CallExpr *CE, FunctionDecl *FD);
3857
3858 /// Helpers for dealing with blocks and functions.
3859 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3860 bool CheckParameterNames);
3861 void CheckCXXDefaultArguments(FunctionDecl *FD);
3862 void CheckExtraCXXDefaultArguments(Declarator &D);
3863 Scope *getNonFieldDeclScope(Scope *S);
3864
3865 /// \name Name lookup
3866 ///
3867 /// These routines provide name lookup that is used during semantic
3868 /// analysis to resolve the various kinds of names (identifiers,
3869 /// overloaded operator names, constructor names, etc.) into zero or
3870 /// more declarations within a particular scope. The major entry
3871 /// points are LookupName, which performs unqualified name lookup,
3872 /// and LookupQualifiedName, which performs qualified name lookup.
3873 ///
3874 /// All name lookup is performed based on some specific criteria,
3875 /// which specify what names will be visible to name lookup and how
3876 /// far name lookup should work. These criteria are important both
3877 /// for capturing language semantics (certain lookups will ignore
3878 /// certain names, for example) and for performance, since name
3879 /// lookup is often a bottleneck in the compilation of C++. Name
3880 /// lookup criteria is specified via the LookupCriteria enumeration.
3881 ///
3882 /// The results of name lookup can vary based on the kind of name
3883 /// lookup performed, the current language, and the translation
3884 /// unit. In C, for example, name lookup will either return nothing
3885 /// (no entity found) or a single declaration. In C++, name lookup
3886 /// can additionally refer to a set of overloaded functions or
3887 /// result in an ambiguity. All of the possible results of name
3888 /// lookup are captured by the LookupResult class, which provides
3889 /// the ability to distinguish among them.
3890 //@{
3891
3892 /// Describes the kind of name lookup to perform.
3893 enum LookupNameKind {
3894 /// Ordinary name lookup, which finds ordinary names (functions,
3895 /// variables, typedefs, etc.) in C and most kinds of names
3896 /// (functions, variables, members, types, etc.) in C++.
3897 LookupOrdinaryName = 0,
3898 /// Tag name lookup, which finds the names of enums, classes,
3899 /// structs, and unions.
3900 LookupTagName,
3901 /// Label name lookup.
3902 LookupLabel,
3903 /// Member name lookup, which finds the names of
3904 /// class/struct/union members.
3905 LookupMemberName,
3906 /// Look up of an operator name (e.g., operator+) for use with
3907 /// operator overloading. This lookup is similar to ordinary name
3908 /// lookup, but will ignore any declarations that are class members.
3909 LookupOperatorName,
3910 /// Look up a name following ~ in a destructor name. This is an ordinary
3911 /// lookup, but prefers tags to typedefs.
3912 LookupDestructorName,
3913 /// Look up of a name that precedes the '::' scope resolution
3914 /// operator in C++. This lookup completely ignores operator, object,
3915 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3916 LookupNestedNameSpecifierName,
3917 /// Look up a namespace name within a C++ using directive or
3918 /// namespace alias definition, ignoring non-namespace names (C++
3919 /// [basic.lookup.udir]p1).
3920 LookupNamespaceName,
3921 /// Look up all declarations in a scope with the given name,
3922 /// including resolved using declarations. This is appropriate
3923 /// for checking redeclarations for a using declaration.
3924 LookupUsingDeclName,
3925 /// Look up an ordinary name that is going to be redeclared as a
3926 /// name with linkage. This lookup ignores any declarations that
3927 /// are outside of the current scope unless they have linkage. See
3928 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3929 LookupRedeclarationWithLinkage,
3930 /// Look up a friend of a local class. This lookup does not look
3931 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3932 LookupLocalFriendName,
3933 /// Look up the name of an Objective-C protocol.
3934 LookupObjCProtocolName,
3935 /// Look up implicit 'self' parameter of an objective-c method.
3936 LookupObjCImplicitSelfParam,
3937 /// Look up the name of an OpenMP user-defined reduction operation.
3938 LookupOMPReductionName,
3939 /// Look up the name of an OpenMP user-defined mapper.
3940 LookupOMPMapperName,
3941 /// Look up any declaration with any name.
3942 LookupAnyName
3943 };
3944
3945 /// Specifies whether (or how) name lookup is being performed for a
3946 /// redeclaration (vs. a reference).
3947 enum RedeclarationKind {
3948 /// The lookup is a reference to this name that is not for the
3949 /// purpose of redeclaring the name.
3950 NotForRedeclaration = 0,
3951 /// The lookup results will be used for redeclaration of a name,
3952 /// if an entity by that name already exists and is visible.
3953 ForVisibleRedeclaration,
3954 /// The lookup results will be used for redeclaration of a name
3955 /// with external linkage; non-visible lookup results with external linkage
3956 /// may also be found.
3957 ForExternalRedeclaration
3958 };
3959
3960 RedeclarationKind forRedeclarationInCurContext() {
3961 // A declaration with an owning module for linkage can never link against
3962 // anything that is not visible. We don't need to check linkage here; if
3963 // the context has internal linkage, redeclaration lookup won't find things
3964 // from other TUs, and we can't safely compute linkage yet in general.
3965 if (cast<Decl>(CurContext)
3966 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3967 return ForVisibleRedeclaration;
3968 return ForExternalRedeclaration;
3969 }
3970
3971 /// The possible outcomes of name lookup for a literal operator.
3972 enum LiteralOperatorLookupResult {
3973 /// The lookup resulted in an error.
3974 LOLR_Error,
3975 /// The lookup found no match but no diagnostic was issued.
3976 LOLR_ErrorNoDiagnostic,
3977 /// The lookup found a single 'cooked' literal operator, which
3978 /// expects a normal literal to be built and passed to it.
3979 LOLR_Cooked,
3980 /// The lookup found a single 'raw' literal operator, which expects
3981 /// a string literal containing the spelling of the literal token.
3982 LOLR_Raw,
3983 /// The lookup found an overload set of literal operator templates,
3984 /// which expect the characters of the spelling of the literal token to be
3985 /// passed as a non-type template argument pack.
3986 LOLR_Template,
3987 /// The lookup found an overload set of literal operator templates,
3988 /// which expect the character type and characters of the spelling of the
3989 /// string literal token to be passed as template arguments.
3990 LOLR_StringTemplatePack,
3991 };
3992
3993 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3994 CXXSpecialMember SM,
3995 bool ConstArg,
3996 bool VolatileArg,
3997 bool RValueThis,
3998 bool ConstThis,
3999 bool VolatileThis);
4000
4001 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4002 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4003 TypoRecoveryCallback;
4004
4005private:
4006 bool CppLookupName(LookupResult &R, Scope *S);
4007
4008 struct TypoExprState {
4009 std::unique_ptr<TypoCorrectionConsumer> Consumer;
4010 TypoDiagnosticGenerator DiagHandler;
4011 TypoRecoveryCallback RecoveryHandler;
4012 TypoExprState();
4013 TypoExprState(TypoExprState &&other) noexcept;
4014 TypoExprState &operator=(TypoExprState &&other) noexcept;
4015 };
4016
4017 /// The set of unhandled TypoExprs and their associated state.
4018 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4019
4020 /// Creates a new TypoExpr AST node.
4021 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4022 TypoDiagnosticGenerator TDG,
4023 TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4024
4025 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4026 //
4027 // The boolean value will be true to indicate that the namespace was loaded
4028 // from an AST/PCH file, or false otherwise.
4029 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4030
4031 /// Whether we have already loaded known namespaces from an extenal
4032 /// source.
4033 bool LoadedExternalKnownNamespaces;
4034
4035 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4036 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4037 /// should be skipped entirely.
4038 std::unique_ptr<TypoCorrectionConsumer>
4039 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4040 Sema::LookupNameKind LookupKind, Scope *S,
4041 CXXScopeSpec *SS,
4042 CorrectionCandidateCallback &CCC,
4043 DeclContext *MemberContext, bool EnteringContext,
4044 const ObjCObjectPointerType *OPT,
4045 bool ErrorRecovery);
4046
4047public:
4048 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4049
4050 /// Clears the state of the given TypoExpr.
4051 void clearDelayedTypo(TypoExpr *TE);
4052
4053 /// Look up a name, looking for a single declaration. Return
4054 /// null if the results were absent, ambiguous, or overloaded.
4055 ///
4056 /// It is preferable to use the elaborated form and explicitly handle
4057 /// ambiguity and overloaded.
4058 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
4059 SourceLocation Loc,
4060 LookupNameKind NameKind,
4061 RedeclarationKind Redecl
4062 = NotForRedeclaration);
4063 bool LookupBuiltin(LookupResult &R);
4064 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4065 bool LookupName(LookupResult &R, Scope *S,
4066 bool AllowBuiltinCreation = false);
4067 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4068 bool InUnqualifiedLookup = false);
4069 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4070 CXXScopeSpec &SS);
4071 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
4072 bool AllowBuiltinCreation = false,
4073 bool EnteringContext = false);
4074 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
4075 RedeclarationKind Redecl
4076 = NotForRedeclaration);
4077 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4078
4079 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
4080 UnresolvedSetImpl &Functions);
4081
4082 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
4083 SourceLocation GnuLabelLoc = SourceLocation());
4084
4085 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
4086 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
4087 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
4088 unsigned Quals);
4089 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4090 bool RValueThis, unsigned ThisQuals);
4091 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
4092 unsigned Quals);
4093 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4094 bool RValueThis, unsigned ThisQuals);
4095 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
4096
4097 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
4098 LiteralOperatorLookupResult
4099 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4100 bool AllowRaw, bool AllowTemplate,
4101 bool AllowStringTemplate, bool DiagnoseMissing,
4102 StringLiteral *StringLit = nullptr);
4103 bool isKnownName(StringRef name);
4104
4105 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4106 enum class FunctionEmissionStatus {
4107 Emitted,
4108 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4109 OMPDiscarded, // Discarded due to OpenMP hostness
4110 TemplateDiscarded, // Discarded due to uninstantiated templates
4111 Unknown,
4112 };
4113 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
4114 bool Final = false);
4115
4116 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4117 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4118
4119 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4120 ArrayRef<Expr *> Args, ADLResult &Functions);
4121
4122 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4123 VisibleDeclConsumer &Consumer,
4124 bool IncludeGlobalScope = true,
4125 bool LoadExternal = true);
4126 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4127 VisibleDeclConsumer &Consumer,
4128 bool IncludeGlobalScope = true,
4129 bool IncludeDependentBases = false,
4130 bool LoadExternal = true);
4131
4132 enum CorrectTypoKind {
4133 CTK_NonError, // CorrectTypo used in a non error recovery situation.
4134 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4135 };
4136
4137 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4138 Sema::LookupNameKind LookupKind,
4139 Scope *S, CXXScopeSpec *SS,
4140 CorrectionCandidateCallback &CCC,
4141 CorrectTypoKind Mode,
4142 DeclContext *MemberContext = nullptr,
4143 bool EnteringContext = false,
4144 const ObjCObjectPointerType *OPT = nullptr,
4145 bool RecordFailure = true);
4146
4147 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4148 Sema::LookupNameKind LookupKind, Scope *S,
4149 CXXScopeSpec *SS,
4150 CorrectionCandidateCallback &CCC,
4151 TypoDiagnosticGenerator TDG,
4152 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4153 DeclContext *MemberContext = nullptr,
4154 bool EnteringContext = false,
4155 const ObjCObjectPointerType *OPT = nullptr);
4156
4157 /// Process any TypoExprs in the given Expr and its children,
4158 /// generating diagnostics as appropriate and returning a new Expr if there
4159 /// were typos that were all successfully corrected and ExprError if one or
4160 /// more typos could not be corrected.
4161 ///
4162 /// \param E The Expr to check for TypoExprs.
4163 ///
4164 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4165 /// initializer.
4166 ///
4167 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4168 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4169 ///
4170 /// \param Filter A function applied to a newly rebuilt Expr to determine if
4171 /// it is an acceptable/usable result from a single combination of typo
4172 /// corrections. As long as the filter returns ExprError, different
4173 /// combinations of corrections will be tried until all are exhausted.
4174 ExprResult CorrectDelayedTyposInExpr(
4175 Expr *E, VarDecl *InitDecl = nullptr,
4176 bool RecoverUncorrectedTypos = false,
4177 llvm::function_ref<ExprResult(Expr *)> Filter =
4178 [](Expr *E) -> ExprResult { return E; });
4179
4180 ExprResult CorrectDelayedTyposInExpr(
4181 ExprResult ER, VarDecl *InitDecl = nullptr,
4182 bool RecoverUncorrectedTypos = false,
4183 llvm::function_ref<ExprResult(Expr *)> Filter =
4184 [](Expr *E) -> ExprResult { return E; }) {
4185 return ER.isInvalid()
4186 ? ER
4187 : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4188 RecoverUncorrectedTypos, Filter);
4189 }
4190
4191 void diagnoseTypo(const TypoCorrection &Correction,
4192 const PartialDiagnostic &TypoDiag,
4193 bool ErrorRecovery = true);
4194
4195 void diagnoseTypo(const TypoCorrection &Correction,
4196 const PartialDiagnostic &TypoDiag,
4197 const PartialDiagnostic &PrevNote,
4198 bool ErrorRecovery = true);
4199
4200 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4201
4202 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4203 ArrayRef<Expr *> Args,
4204 AssociatedNamespaceSet &AssociatedNamespaces,
4205 AssociatedClassSet &AssociatedClasses);
4206
4207 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4208 bool ConsiderLinkage, bool AllowInlineNamespace);
4209
4210 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4211
4212 void DiagnoseAmbiguousLookup(LookupResult &Result);
4213 //@}
4214
4215 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4216 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4217 ArrayRef<Expr *> SubExprs,
4218 QualType T = QualType());
4219
4220 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4221 SourceLocation IdLoc,
4222 bool TypoCorrection = false);
4223 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4224 SourceLocation Loc);
4225 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4226 Scope *S, bool ForRedeclaration,
4227 SourceLocation Loc);
4228 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4229 Scope *S);
4230 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4231 FunctionDecl *FD);
4232 void AddKnownFunctionAttributes(FunctionDecl *FD);
4233
4234 // More parsing and symbol table subroutines.
4235
4236 void ProcessPragmaWeak(Scope *S, Decl *D);
4237 // Decl attributes - this routine is the top level dispatcher.
4238 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4239 // Helper for delayed processing of attributes.
4240 void ProcessDeclAttributeDelayed(Decl *D,
4241 const ParsedAttributesView &AttrList);
4242 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
4243 bool IncludeCXX11Attributes = true);
4244 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4245 const ParsedAttributesView &AttrList);
4246
4247 void checkUnusedDeclAttributes(Declarator &D);
4248
4249 /// Determine if type T is a valid subject for a nonnull and similar
4250 /// attributes. By default, we look through references (the behavior used by
4251 /// nonnull), but if the second parameter is true, then we treat a reference
4252 /// type as valid.
4253 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4254
4255 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4256 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4257 const FunctionDecl *FD = nullptr);
4258 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4259 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4260 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4261 StringRef &Str,
4262 SourceLocation *ArgLocation = nullptr);
4263 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4264 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4265 bool checkMSInheritanceAttrOnDefinition(
4266 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4267 MSInheritanceModel SemanticSpelling);
4268
4269 void CheckAlignasUnderalignment(Decl *D);
4270
4271 /// Adjust the calling convention of a method to be the ABI default if it
4272 /// wasn't specified explicitly. This handles method types formed from
4273 /// function type typedefs and typename template arguments.
4274 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4275 SourceLocation Loc);
4276
4277 // Check if there is an explicit attribute, but only look through parens.
4278 // The intent is to look for an attribute on the current declarator, but not
4279 // one that came from a typedef.
4280 bool hasExplicitCallingConv(QualType T);
4281
4282 /// Get the outermost AttributedType node that sets a calling convention.
4283 /// Valid types should not have multiple attributes with different CCs.
4284 const AttributedType *getCallingConvAttributedType(QualType T) const;
4285
4286 /// Stmt attributes - this routine is the top level dispatcher.
4287 StmtResult ProcessStmtAttributes(Stmt *Stmt,
4288 const ParsedAttributesView &Attrs,
4289 SourceRange Range);
4290
4291 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4292 ObjCMethodDecl *MethodDecl,
4293 bool IsProtocolMethodDecl);
4294
4295 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4296 ObjCMethodDecl *Overridden,
4297 bool IsProtocolMethodDecl);
4298
4299 /// WarnExactTypedMethods - This routine issues a warning if method
4300 /// implementation declaration matches exactly that of its declaration.
4301 void WarnExactTypedMethods(ObjCMethodDecl *Method,
4302 ObjCMethodDecl *MethodDecl,
4303 bool IsProtocolMethodDecl);
4304
4305 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4306
4307 /// CheckImplementationIvars - This routine checks if the instance variables
4308 /// listed in the implelementation match those listed in the interface.
4309 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4310 ObjCIvarDecl **Fields, unsigned nIvars,
4311 SourceLocation Loc);
4312
4313 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4314 /// remains unimplemented in the class or category \@implementation.
4315 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4316 ObjCContainerDecl* IDecl,
4317 bool IncompleteImpl = false);
4318
4319 /// DiagnoseUnimplementedProperties - This routine warns on those properties
4320 /// which must be implemented by this implementation.
4321 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4322 ObjCContainerDecl *CDecl,
4323 bool SynthesizeProperties);
4324
4325 /// Diagnose any null-resettable synthesized setters.
4326 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4327
4328 /// DefaultSynthesizeProperties - This routine default synthesizes all
4329 /// properties which must be synthesized in the class's \@implementation.
4330 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4331 ObjCInterfaceDecl *IDecl,
4332 SourceLocation AtEnd);
4333 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4334
4335 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4336 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4337 /// declared in class 'IFace'.
4338 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4339 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4340
4341 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4342 /// backs the property is not used in the property's accessor.
4343 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4344 const ObjCImplementationDecl *ImplD);
4345
4346 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4347 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4348 /// It also returns ivar's property on success.
4349 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4350 const ObjCPropertyDecl *&PDecl) const;
4351
4352 /// Called by ActOnProperty to handle \@property declarations in
4353 /// class extensions.
4354 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4355 SourceLocation AtLoc,
4356 SourceLocation LParenLoc,
4357 FieldDeclarator &FD,
4358 Selector GetterSel,
4359 SourceLocation GetterNameLoc,
4360 Selector SetterSel,
4361 SourceLocation SetterNameLoc,
4362 const bool isReadWrite,
4363 unsigned &Attributes,
4364 const unsigned AttributesAsWritten,
4365 QualType T,
4366 TypeSourceInfo *TSI,
4367 tok::ObjCKeywordKind MethodImplKind);
4368
4369 /// Called by ActOnProperty and HandlePropertyInClassExtension to
4370 /// handle creating the ObjcPropertyDecl for a category or \@interface.
4371 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4372 ObjCContainerDecl *CDecl,
4373 SourceLocation AtLoc,
4374 SourceLocation LParenLoc,
4375 FieldDeclarator &FD,
4376 Selector GetterSel,
4377 SourceLocation GetterNameLoc,
4378 Selector SetterSel,
4379 SourceLocation SetterNameLoc,
4380 const bool isReadWrite,
4381 const unsigned Attributes,
4382 const unsigned AttributesAsWritten,
4383 QualType T,
4384 TypeSourceInfo *TSI,
4385 tok::ObjCKeywordKind MethodImplKind,
4386 DeclContext *lexicalDC = nullptr);
4387
4388 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4389 /// warning) when atomic property has one but not the other user-declared
4390 /// setter or getter.
4391 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4392 ObjCInterfaceDecl* IDecl);
4393
4394 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4395
4396 void DiagnoseMissingDesignatedInitOverrides(
4397 const ObjCImplementationDecl *ImplD,
4398 const ObjCInterfaceDecl *IFD);
4399
4400 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4401
4402 enum MethodMatchStrategy {
4403 MMS_loose,
4404 MMS_strict
4405 };
4406
4407 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4408 /// true, or false, accordingly.
4409 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4410 const ObjCMethodDecl *PrevMethod,
4411 MethodMatchStrategy strategy = MMS_strict);
4412
4413 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4414 /// or protocol against those declared in their implementations.
4415 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4416 const SelectorSet &ClsMap,
4417 SelectorSet &InsMapSeen,
4418 SelectorSet &ClsMapSeen,
4419 ObjCImplDecl* IMPDecl,
4420 ObjCContainerDecl* IDecl,
4421 bool &IncompleteImpl,
4422 bool ImmediateClass,
4423 bool WarnCategoryMethodImpl=false);
4424
4425 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4426 /// category matches with those implemented in its primary class and
4427 /// warns each time an exact match is found.
4428 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4429
4430 /// Add the given method to the list of globally-known methods.
4431 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4432
4433 /// Returns default addr space for method qualifiers.
4434 LangAS getDefaultCXXMethodAddrSpace() const;
4435
4436private:
4437 /// AddMethodToGlobalPool - Add an instance or factory method to the global
4438 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4439 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4440
4441 /// LookupMethodInGlobalPool - Returns the instance or factory method and
4442 /// optionally warns if there are multiple signatures.
4443 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4444 bool receiverIdOrClass,
4445 bool instance);
4446
4447public:
4448 /// - Returns instance or factory methods in global method pool for
4449 /// given selector. It checks the desired kind first, if none is found, and
4450 /// parameter checkTheOther is set, it then checks the other kind. If no such
4451 /// method or only one method is found, function returns false; otherwise, it
4452 /// returns true.
4453 bool
4454 CollectMultipleMethodsInGlobalPool(Selector Sel,
4455 SmallVectorImpl<ObjCMethodDecl*>& Methods,
4456 bool InstanceFirst, bool CheckTheOther,
4457 const ObjCObjectType *TypeBound = nullptr);
4458
4459 bool
4460 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4461 SourceRange R, bool receiverIdOrClass,
4462 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4463
4464 void
4465 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4466 Selector Sel, SourceRange R,
4467 bool receiverIdOrClass);
4468
4469private:
4470 /// - Returns a selector which best matches given argument list or
4471 /// nullptr if none could be found
4472 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4473 bool IsInstance,
4474 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4475
4476
4477 /// Record the typo correction failure and return an empty correction.
4478 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4479 bool RecordFailure = true) {
4480 if (RecordFailure)
4481 TypoCorrectionFailures[Typo].insert(TypoLoc);
4482 return TypoCorrection();
4483 }
4484
4485public:
4486 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4487 /// unit are added to a global pool. This allows us to efficiently associate
4488 /// a selector with a method declaraation for purposes of typechecking
4489 /// messages sent to "id" (where the class of the object is unknown).
4490 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4491 AddMethodToGlobalPool(Method, impl, /*instance*/true);
4492 }
4493
4494 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4495 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4496 AddMethodToGlobalPool(Method, impl, /*instance*/false);
4497 }
4498
4499 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4500 /// pool.
4501 void AddAnyMethodToGlobalPool(Decl *D);
4502
4503 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4504 /// there are multiple signatures.
4505 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4506 bool receiverIdOrClass=false) {
4507 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4508 /*instance*/true);
4509 }
4510
4511 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4512 /// there are multiple signatures.
4513 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4514 bool receiverIdOrClass=false) {
4515 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4516 /*instance*/false);
4517 }
4518
4519 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4520 QualType ObjectType=QualType());
4521 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4522 /// implementation.
4523 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4524
4525 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4526 /// initialization.
4527 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4528 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4529
4530 //===--------------------------------------------------------------------===//
4531 // Statement Parsing Callbacks: SemaStmt.cpp.
4532public:
4533 class FullExprArg {
4534 public:
4535 FullExprArg() : E(nullptr) { }
4536 FullExprArg(Sema &actions) : E(nullptr) { }
4537
4538 ExprResult release() {
4539 return E;
4540 }
4541
4542 Expr *get() const { return E; }
4543
4544 Expr *operator->() {
4545 return E;
4546 }
4547
4548 private:
4549 // FIXME: No need to make the entire Sema class a friend when it's just
4550 // Sema::MakeFullExpr that needs access to the constructor below.
4551 friend class Sema;
4552
4553 explicit FullExprArg(Expr *expr) : E(expr) {}
4554
4555 Expr *E;
4556 };
4557
4558 FullExprArg MakeFullExpr(Expr *Arg) {
4559 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4560 }
4561 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4562 return FullExprArg(
4563 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4564 }
4565 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4566 ExprResult FE =
4567 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4568 /*DiscardedValue*/ true);
4569 return FullExprArg(FE.get());
4570 }
4571
4572 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4573 StmtResult ActOnExprStmtError();
4574
4575 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4576 bool HasLeadingEmptyMacro = false);
4577
4578 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4579 void ActOnAfterCompoundStatementLeadingPragmas();
4580 void ActOnFinishOfCompoundStmt();
4581 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4582 ArrayRef<Stmt *> Elts, bool isStmtExpr);
4583
4584 /// A RAII object to enter scope of a compound statement.
4585 class CompoundScopeRAII {
4586 public:
4587 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4588 S.ActOnStartOfCompoundStmt(IsStmtExpr);
4589 }
4590
4591 ~CompoundScopeRAII() {
4592 S.ActOnFinishOfCompoundStmt();
4593 }
4594
4595 private:
4596 Sema &S;
4597 };
4598
4599 /// An RAII helper that pops function a function scope on exit.
4600 struct FunctionScopeRAII {
4601 Sema &S;
4602 bool Active;
4603 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4604 ~FunctionScopeRAII() {
4605 if (Active)
4606 S.PopFunctionScopeInfo();
4607 }
4608 void disable() { Active = false; }
4609 };
4610
4611 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4612 SourceLocation StartLoc,
4613 SourceLocation EndLoc);
4614 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4615 StmtResult ActOnForEachLValueExpr(Expr *E);
4616 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4617 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4618 SourceLocation DotDotDotLoc, ExprResult RHS,
4619 SourceLocation ColonLoc);
4620 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4621
4622 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4623 SourceLocation ColonLoc,
4624 Stmt *SubStmt, Scope *CurScope);
4625 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4626 SourceLocation ColonLoc, Stmt *SubStmt);
4627
4628 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4629 ArrayRef<const Attr*> Attrs,
4630 Stmt *SubStmt);
4631
4632 class ConditionResult;
4633 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4634 SourceLocation LParenLoc, Stmt *InitStmt,
4635 ConditionResult Cond, SourceLocation RParenLoc,
4636 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4637 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4638 SourceLocation LParenLoc, Stmt *InitStmt,
4639 ConditionResult Cond, SourceLocation RParenLoc,
4640 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4641 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4642 SourceLocation LParenLoc, Stmt *InitStmt,
4643 ConditionResult Cond,
4644 SourceLocation RParenLoc);
4645 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4646 Stmt *Switch, Stmt *Body);
4647 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
4648 ConditionResult Cond, SourceLocation RParenLoc,
4649 Stmt *Body);
4650 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4651 SourceLocation WhileLoc, SourceLocation CondLParen,
4652 Expr *Cond, SourceLocation CondRParen);
4653
4654 StmtResult ActOnForStmt(SourceLocation ForLoc,
4655 SourceLocation LParenLoc,
4656 Stmt *First,
4657 ConditionResult Second,
4658 FullExprArg Third,
4659 SourceLocation RParenLoc,
4660 Stmt *Body);
4661 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4662 Expr *collection);
4663 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4664 Stmt *First, Expr *collection,
4665 SourceLocation RParenLoc);
4666 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4667
4668 enum BuildForRangeKind {
4669 /// Initial building of a for-range statement.
4670 BFRK_Build,
4671 /// Instantiation or recovery rebuild of a for-range statement. Don't
4672 /// attempt any typo-correction.
4673 BFRK_Rebuild,
4674 /// Determining whether a for-range statement could be built. Avoid any
4675 /// unnecessary or irreversible actions.
4676 BFRK_Check
4677 };
4678
4679 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4680 SourceLocation CoawaitLoc,
4681 Stmt *InitStmt,
4682 Stmt *LoopVar,
4683 SourceLocation ColonLoc, Expr *Collection,
4684 SourceLocation RParenLoc,
4685 BuildForRangeKind Kind);
4686 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4687 SourceLocation CoawaitLoc,
4688 Stmt *InitStmt,
4689 SourceLocation ColonLoc,
4690 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4691 Expr *Cond, Expr *Inc,
4692 Stmt *LoopVarDecl,
4693 SourceLocation RParenLoc,
4694 BuildForRangeKind Kind);
4695 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4696
4697 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4698 SourceLocation LabelLoc,
4699 LabelDecl *TheDecl);
4700 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4701 SourceLocation StarLoc,
4702 Expr *DestExp);
4703 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4704 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4705
4706 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4707 CapturedRegionKind Kind, unsigned NumParams);
4708 typedef std::pair<StringRef, QualType> CapturedParamNameType;
4709 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4710 CapturedRegionKind Kind,
4711 ArrayRef<CapturedParamNameType> Params,
4712 unsigned OpenMPCaptureLevel = 0);
4713 StmtResult ActOnCapturedRegionEnd(Stmt *S);
4714 void ActOnCapturedRegionError();
4715 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4716 SourceLocation Loc,
4717 unsigned NumParams);
4718
4719 enum CopyElisionSemanticsKind {
4720 CES_Strict = 0,
4721 CES_AllowParameters = 1,
4722 CES_AllowDifferentTypes = 2,
4723 CES_AllowExceptionVariables = 4,
4724 CES_FormerDefault = (CES_AllowParameters),
4725 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4726 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4727 CES_AllowExceptionVariables),
4728 };
4729
4730 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4731 CopyElisionSemanticsKind CESK);
4732 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4733 CopyElisionSemanticsKind CESK);
4734
4735 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4736 Scope *CurScope);
4737 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4738 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4739
4740 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4741 bool IsVolatile, unsigned NumOutputs,
4742 unsigned NumInputs, IdentifierInfo **Names,
4743 MultiExprArg Constraints, MultiExprArg Exprs,
4744 Expr *AsmString, MultiExprArg Clobbers,
4745 unsigned NumLabels,
4746 SourceLocation RParenLoc);
4747
4748 void FillInlineAsmIdentifierInfo(Expr *Res,
4749 llvm::InlineAsmIdentifierInfo &Info);
4750 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4751 SourceLocation TemplateKWLoc,
4752 UnqualifiedId &Id,
4753 bool IsUnevaluatedContext);
4754 bool LookupInlineAsmField(StringRef Base, StringRef Member,
4755 unsigned &Offset, SourceLocation AsmLoc);
4756 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4757 SourceLocation AsmLoc);
4758 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4759 ArrayRef<Token> AsmToks,
4760 StringRef AsmString,
4761 unsigned NumOutputs, unsigned NumInputs,
4762 ArrayRef<StringRef> Constraints,
4763 ArrayRef<StringRef> Clobbers,
4764 ArrayRef<Expr*> Exprs,
4765 SourceLocation EndLoc);
4766 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4767 SourceLocation Location,
4768 bool AlwaysCreate);
4769
4770 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4771 SourceLocation StartLoc,
4772 SourceLocation IdLoc, IdentifierInfo *Id,
4773 bool Invalid = false);
4774
4775 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4776
4777 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4778 Decl *Parm, Stmt *Body);
4779
4780 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4781
4782 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4783 MultiStmtArg Catch, Stmt *Finally);
4784
4785 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4786 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4787 Scope *CurScope);
4788 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4789 Expr *operand);
4790 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4791 Expr *SynchExpr,
4792 Stmt *SynchBody);
4793
4794 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4795
4796 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4797 SourceLocation StartLoc,
4798 SourceLocation IdLoc,
4799 IdentifierInfo *Id);
4800
4801 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4802
4803 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4804 Decl *ExDecl, Stmt *HandlerBlock);
4805 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4806 ArrayRef<Stmt *> Handlers);
4807
4808 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4809 SourceLocation TryLoc, Stmt *TryBlock,
4810 Stmt *Handler);
4811 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4812 Expr *FilterExpr,
4813 Stmt *Block);
4814 void ActOnStartSEHFinallyBlock();
4815 void ActOnAbortSEHFinallyBlock();
4816 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4817 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4818
4819 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4820
4821 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4822
4823 /// If it's a file scoped decl that must warn if not used, keep track
4824 /// of it.
4825 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4826
4827 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4828 /// whose result is unused, warn.
4829 void DiagnoseUnusedExprResult(const Stmt *S);
4830 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4831 void DiagnoseUnusedDecl(const NamedDecl *ND);
4832
4833 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4834 /// statement as a \p Body, and it is located on the same line.
4835 ///
4836 /// This helps prevent bugs due to typos, such as:
4837 /// if (condition);
4838 /// do_stuff();
4839 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4840 const Stmt *Body,
4841 unsigned DiagID);
4842
4843 /// Warn if a for/while loop statement \p S, which is followed by
4844 /// \p PossibleBody, has a suspicious null statement as a body.
4845 void DiagnoseEmptyLoopBody(const Stmt *S,
4846 const Stmt *PossibleBody);
4847
4848 /// Warn if a value is moved to itself.
4849 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4850 SourceLocation OpLoc);
4851
4852 /// Warn if we're implicitly casting from a _Nullable pointer type to a
4853 /// _Nonnull one.
4854 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4855 SourceLocation Loc);
4856
4857 /// Warn when implicitly casting 0 to nullptr.
4858 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4859
4860 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4861 return DelayedDiagnostics.push(pool);
4862 }
4863 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4864
4865 typedef ProcessingContextState ParsingClassState;
4866 ParsingClassState PushParsingClass() {
4867 ParsingClassDepth++;
4868 return DelayedDiagnostics.pushUndelayed();
4869 }
4870 void PopParsingClass(ParsingClassState state) {
4871 ParsingClassDepth--;
4872 DelayedDiagnostics.popUndelayed(state);
4873 }
4874
4875 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4876
4877 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4878 const ObjCInterfaceDecl *UnknownObjCClass,
4879 bool ObjCPropertyAccess,
4880 bool AvoidPartialAvailabilityChecks = false,
4881 ObjCInterfaceDecl *ClassReceiver = nullptr);
4882
4883 bool makeUnavailableInSystemHeader(SourceLocation loc,
4884 UnavailableAttr::ImplicitReason reason);
4885
4886 /// Issue any -Wunguarded-availability warnings in \c FD
4887 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4888
4889 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4890
4891 //===--------------------------------------------------------------------===//
4892 // Expression Parsing Callbacks: SemaExpr.cpp.
4893
4894 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4895 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4896 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4897 bool ObjCPropertyAccess = false,
4898 bool AvoidPartialAvailabilityChecks = false,
4899 ObjCInterfaceDecl *ClassReciever = nullptr);
4900 void NoteDeletedFunction(FunctionDecl *FD);
4901 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4902 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4903 ObjCMethodDecl *Getter,
4904 SourceLocation Loc);
4905 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4906 ArrayRef<Expr *> Args);
4907
4908 void PushExpressionEvaluationContext(
4909 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4910 ExpressionEvaluationContextRecord::ExpressionKind Type =
4911 ExpressionEvaluationContextRecord::EK_Other);
4912 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4913 void PushExpressionEvaluationContext(
4914 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4915 ExpressionEvaluationContextRecord::ExpressionKind Type =
4916 ExpressionEvaluationContextRecord::EK_Other);
4917 void PopExpressionEvaluationContext();
4918
4919 void DiscardCleanupsInEvaluationContext();
4920
4921 ExprResult TransformToPotentiallyEvaluated(Expr *E);
4922 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4923
4924 ExprResult CheckUnevaluatedOperand(Expr *E);
4925 void CheckUnusedVolatileAssignment(Expr *E);
4926
4927 ExprResult ActOnConstantExpression(ExprResult Res);
4928
4929 // Functions for marking a declaration referenced. These functions also
4930 // contain the relevant logic for marking if a reference to a function or
4931 // variable is an odr-use (in the C++11 sense). There are separate variants
4932 // for expressions referring to a decl; these exist because odr-use marking
4933 // needs to be delayed for some constant variables when we build one of the
4934 // named expressions.
4935 //
4936 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4937 // should usually be true. This only needs to be set to false if the lack of
4938 // odr-use cannot be determined from the current context (for instance,
4939 // because the name denotes a virtual function and was written without an
4940 // explicit nested-name-specifier).
4941 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4942 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4943 bool MightBeOdrUse = true);
4944 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4945 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4946 void MarkMemberReferenced(MemberExpr *E);
4947 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4948 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4949 unsigned CapturingScopeIndex);
4950
4951 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4952 void CleanupVarDeclMarking();
4953
4954 enum TryCaptureKind {
4955 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4956 };
4957
4958 /// Try to capture the given variable.
4959 ///
4960 /// \param Var The variable to capture.
4961 ///
4962 /// \param Loc The location at which the capture occurs.
4963 ///
4964 /// \param Kind The kind of capture, which may be implicit (for either a
4965 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4966 ///
4967 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4968 /// an explicit lambda capture.
4969 ///
4970 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4971 /// captures or diagnose errors. If false, this routine merely check whether
4972 /// the capture can occur without performing the capture itself or complaining
4973 /// if the variable cannot be captured.
4974 ///
4975 /// \param CaptureType Will be set to the type of the field used to capture
4976 /// this variable in the innermost block or lambda. Only valid when the
4977 /// variable can be captured.
4978 ///
4979 /// \param DeclRefType Will be set to the type of a reference to the capture
4980 /// from within the current scope. Only valid when the variable can be
4981 /// captured.
4982 ///
4983 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4984 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4985 /// This is useful when enclosing lambdas must speculatively capture
4986 /// variables that may or may not be used in certain specializations of
4987 /// a nested generic lambda.
4988 ///
4989 /// \returns true if an error occurred (i.e., the variable cannot be
4990 /// captured) and false if the capture succeeded.
4991 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4992 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4993 QualType &CaptureType,
4994 QualType &DeclRefType,
4995 const unsigned *const FunctionScopeIndexToStopAt);
4996
4997 /// Try to capture the given variable.
4998 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4999 TryCaptureKind Kind = TryCapture_Implicit,
5000 SourceLocation EllipsisLoc = SourceLocation());
5001
5002 /// Checks if the variable must be captured.
5003 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
5004
5005 /// Given a variable, determine the type that a reference to that
5006 /// variable will have in the given scope.
5007 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
5008
5009 /// Mark all of the declarations referenced within a particular AST node as
5010 /// referenced. Used when template instantiation instantiates a non-dependent
5011 /// type -- entities referenced by the type are now referenced.
5012 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
5013 void MarkDeclarationsReferencedInExpr(Expr *E,
5014 bool SkipLocalVariables = false);
5015
5016 /// Try to recover by turning the given expression into a
5017 /// call. Returns true if recovery was attempted or an error was
5018 /// emitted; this may also leave the ExprResult invalid.
5019 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
5020 bool ForceComplain = false,
5021 bool (*IsPlausibleResult)(QualType) = nullptr);
5022
5023 /// Figure out if an expression could be turned into a call.
5024 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
5025 UnresolvedSetImpl &NonTemplateOverloads);
5026
5027 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
5028 /// conversion.
5029 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
5030
5031 /// Conditionally issue a diagnostic based on the current
5032 /// evaluation context.
5033 ///
5034 /// \param Statement If Statement is non-null, delay reporting the
5035 /// diagnostic until the function body is parsed, and then do a basic
5036 /// reachability analysis to determine if the statement is reachable.
5037 /// If it is unreachable, the diagnostic will not be emitted.
5038 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
5039 const PartialDiagnostic &PD);
5040 /// Similar, but diagnostic is only produced if all the specified statements
5041 /// are reachable.
5042 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
5043 const PartialDiagnostic &PD);
5044
5045 // Primary Expressions.
5046 SourceRange getExprRange(Expr *E) const;
5047
5048 ExprResult ActOnIdExpression(
5049 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5050 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
5051 CorrectionCandidateCallback *CCC = nullptr,
5052 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
5053
5054 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
5055 TemplateArgumentListInfo &Buffer,
5056 DeclarationNameInfo &NameInfo,
5057 const TemplateArgumentListInfo *&TemplateArgs);
5058
5059 bool DiagnoseDependentMemberLookup(LookupResult &R);
5060
5061 bool
5062 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
5063 CorrectionCandidateCallback &CCC,
5064 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
5065 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
5066
5067 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
5068 IdentifierInfo *II);
5069 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
5070
5071 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
5072 IdentifierInfo *II,
5073 bool AllowBuiltinCreation=false);
5074
5075 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
5076 SourceLocation TemplateKWLoc,
5077 const DeclarationNameInfo &NameInfo,
5078 bool isAddressOfOperand,
5079 const TemplateArgumentListInfo *TemplateArgs);
5080
5081 /// If \p D cannot be odr-used in the current expression evaluation context,
5082 /// return a reason explaining why. Otherwise, return NOUR_None.
5083 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
5084
5085 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5086 SourceLocation Loc,
5087 const CXXScopeSpec *SS = nullptr);
5088 DeclRefExpr *
5089 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5090 const DeclarationNameInfo &NameInfo,
5091 const CXXScopeSpec *SS = nullptr,
5092 NamedDecl *FoundD = nullptr,
5093 SourceLocation TemplateKWLoc = SourceLocation(),
5094 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5095 DeclRefExpr *
5096 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5097 const DeclarationNameInfo &NameInfo,
5098 NestedNameSpecifierLoc NNS,
5099 NamedDecl *FoundD = nullptr,
5100 SourceLocation TemplateKWLoc = SourceLocation(),
5101 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5102
5103 ExprResult
5104 BuildAnonymousStructUnionMemberReference(
5105 const CXXScopeSpec &SS,
5106 SourceLocation nameLoc,
5107 IndirectFieldDecl *indirectField,
5108 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5109 Expr *baseObjectExpr = nullptr,
5110 SourceLocation opLoc = SourceLocation());
5111
5112 ExprResult BuildPossibleImplicitMemberExpr(
5113 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5114 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5115 UnresolvedLookupExpr *AsULE = nullptr);
5116 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5117 SourceLocation TemplateKWLoc,
5118 LookupResult &R,
5119 const TemplateArgumentListInfo *TemplateArgs,
5120 bool IsDefiniteInstance,
5121 const Scope *S);
5122 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5123 const LookupResult &R,
5124 bool HasTrailingLParen);
5125
5126 ExprResult
5127 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5128 const DeclarationNameInfo &NameInfo,
5129 bool IsAddressOfOperand, const Scope *S,
5130 TypeSourceInfo **RecoveryTSI = nullptr);
5131
5132 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5133 SourceLocation TemplateKWLoc,
5134 const DeclarationNameInfo &NameInfo,
5135 const TemplateArgumentListInfo *TemplateArgs);
5136
5137 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5138 LookupResult &R,
5139 bool NeedsADL,
5140 bool AcceptInvalidDecl = false);
5141 ExprResult BuildDeclarationNameExpr(
5142 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5143 NamedDecl *FoundD = nullptr,
5144 const TemplateArgumentListInfo *TemplateArgs = nullptr,
5145 bool AcceptInvalidDecl = false);
5146
5147 ExprResult BuildLiteralOperatorCall(LookupResult &R,
5148 DeclarationNameInfo &SuffixInfo,
5149 ArrayRef<Expr *> Args,
5150 SourceLocation LitEndLoc,
5151 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5152
5153 ExprResult BuildPredefinedExpr(SourceLocation Loc,
5154 PredefinedExpr::IdentKind IK);
5155 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5156 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5157
5158 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5159
5160 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5161 ExprResult ActOnCharacterConstant(const Token &Tok,
5162 Scope *UDLScope = nullptr);
5163 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5164 ExprResult ActOnParenListExpr(SourceLocation L,
5165 SourceLocation R,
5166 MultiExprArg Val);
5167
5168 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5169 /// fragments (e.g. "foo" "bar" L"baz").
5170 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5171 Scope *UDLScope = nullptr);
5172
5173 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5174 SourceLocation DefaultLoc,
5175 SourceLocation RParenLoc,
5176 Expr *ControllingExpr,
5177 ArrayRef<ParsedType> ArgTypes,
5178 ArrayRef<Expr *> ArgExprs);
5179 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5180 SourceLocation DefaultLoc,
5181 SourceLocation RParenLoc,
5182 Expr *ControllingExpr,
5183 ArrayRef<TypeSourceInfo *> Types,
5184 ArrayRef<Expr *> Exprs);
5185
5186 // Binary/Unary Operators. 'Tok' is the token for the operator.
5187 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5188 Expr *InputExpr);
5189 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5190 UnaryOperatorKind Opc, Expr *Input);
5191 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5192 tok::TokenKind Op, Expr *Input);
5193
5194 bool isQualifiedMemberAccess(Expr *E);
5195 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5196
5197 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5198 SourceLocation OpLoc,
5199 UnaryExprOrTypeTrait ExprKind,
5200 SourceRange R);
5201 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5202 UnaryExprOrTypeTrait ExprKind);
5203 ExprResult
5204 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5205 UnaryExprOrTypeTrait ExprKind,
5206 bool IsType, void *TyOrEx,
5207 SourceRange ArgRange);
5208
5209 ExprResult CheckPlaceholderExpr(Expr *E);
5210 bool CheckVecStepExpr(Expr *E);
5211
5212 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5213 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5214 SourceRange ExprRange,
5215 UnaryExprOrTypeTrait ExprKind);
5216 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5217 SourceLocation OpLoc,
5218 IdentifierInfo &Name,
5219 SourceLocation NameLoc,
5220 SourceLocation RParenLoc);
5221 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5222 tok::TokenKind Kind, Expr *Input);
5223
5224 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5225 Expr *Idx, SourceLocation RLoc);
5226 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5227 Expr *Idx, SourceLocation RLoc);
5228
5229 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5230 Expr *ColumnIdx,
5231 SourceLocation RBLoc);
5232
5233 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5234 Expr *LowerBound,
5235 SourceLocation ColonLocFirst,
5236 SourceLocation ColonLocSecond,
5237 Expr *Length, Expr *Stride,
5238 SourceLocation RBLoc);
5239 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5240 SourceLocation RParenLoc,
5241 ArrayRef<Expr *> Dims,
5242 ArrayRef<SourceRange> Brackets);
5243
5244 /// Data structure for iterator expression.
5245 struct OMPIteratorData {
5246 IdentifierInfo *DeclIdent = nullptr;
5247 SourceLocation DeclIdentLoc;
5248 ParsedType Type;
5249 OMPIteratorExpr::IteratorRange Range;
5250 SourceLocation AssignLoc;
5251 SourceLocation ColonLoc;
5252 SourceLocation SecColonLoc;
5253 };
5254
5255 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5256 SourceLocation LLoc, SourceLocation RLoc,
5257 ArrayRef<OMPIteratorData> Data);
5258
5259 // This struct is for use by ActOnMemberAccess to allow
5260 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5261 // changing the access operator from a '.' to a '->' (to see if that is the
5262 // change needed to fix an error about an unknown member, e.g. when the class
5263 // defines a custom operator->).
5264 struct ActOnMemberAccessExtraArgs {
5265 Scope *S;
5266 UnqualifiedId &Id;
5267 Decl *ObjCImpDecl;
5268 };
5269
5270 ExprResult BuildMemberReferenceExpr(
5271 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5272 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5273 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5274 const TemplateArgumentListInfo *TemplateArgs,
5275 const Scope *S,
5276 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5277
5278 ExprResult
5279 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5280 bool IsArrow, const CXXScopeSpec &SS,
5281 SourceLocation TemplateKWLoc,
5282 NamedDecl *FirstQualifierInScope, LookupResult &R,
5283 const TemplateArgumentListInfo *TemplateArgs,
5284 const Scope *S,
5285 bool SuppressQualifierCheck = false,
5286 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5287
5288 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5289 SourceLocation OpLoc,
5290 const CXXScopeSpec &SS, FieldDecl *Field,
5291 DeclAccessPair FoundDecl,
5292 const DeclarationNameInfo &MemberNameInfo);
5293
5294 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5295
5296 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5297 const CXXScopeSpec &SS,
5298 const LookupResult &R);
5299
5300 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5301 bool IsArrow, SourceLocation OpLoc,
5302 const CXXScopeSpec &SS,
5303 SourceLocation TemplateKWLoc,
5304 NamedDecl *FirstQualifierInScope,
5305 const DeclarationNameInfo &NameInfo,
5306 const TemplateArgumentListInfo *TemplateArgs);
5307
5308 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5309 SourceLocation OpLoc,
5310 tok::TokenKind OpKind,
5311 CXXScopeSpec &SS,
5312 SourceLocation TemplateKWLoc,
5313 UnqualifiedId &Member,
5314 Decl *ObjCImpDecl);
5315
5316 MemberExpr *
5317 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5318 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5319 ValueDecl *Member, DeclAccessPair FoundDecl,
5320 bool HadMultipleCandidates,
5321 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5322 ExprValueKind VK, ExprObjectKind OK,
5323 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5324 MemberExpr *
5325 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5326 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5327 ValueDecl *Member, DeclAccessPair FoundDecl,
5328 bool HadMultipleCandidates,
5329 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5330 ExprValueKind VK, ExprObjectKind OK,
5331 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5332
5333 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5334 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5335 FunctionDecl *FDecl,
5336 const FunctionProtoType *Proto,
5337 ArrayRef<Expr *> Args,
5338 SourceLocation RParenLoc,
5339 bool ExecConfig = false);
5340 void CheckStaticArrayArgument(SourceLocation CallLoc,
5341 ParmVarDecl *Param,
5342 const Expr *ArgExpr);
5343
5344 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5345 /// This provides the location of the left/right parens and a list of comma
5346 /// locations.
5347 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5348 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5349 Expr *ExecConfig = nullptr);
5350 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5351 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5352 Expr *ExecConfig = nullptr,
5353 bool IsExecConfig = false,
5354 bool AllowRecovery = false);
5355 enum class AtomicArgumentOrder { API, AST };
5356 ExprResult
5357 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5358 SourceLocation RParenLoc, MultiExprArg Args,
5359 AtomicExpr::AtomicOp Op,
5360 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5361 ExprResult
5362 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5363 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5364 Expr *Config = nullptr, bool IsExecConfig = false,
5365 ADLCallKind UsesADL = ADLCallKind::NotADL);
5366
5367 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5368 MultiExprArg ExecConfig,
5369 SourceLocation GGGLoc);
5370
5371 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5372 Declarator &D, ParsedType &Ty,
5373 SourceLocation RParenLoc, Expr *CastExpr);
5374 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5375 TypeSourceInfo *Ty,
5376 SourceLocation RParenLoc,
5377 Expr *Op);
5378 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5379
5380 /// Build an altivec or OpenCL literal.
5381 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5382 SourceLocation RParenLoc, Expr *E,
5383 TypeSourceInfo *TInfo);
5384
5385 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5386
5387 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5388 ParsedType Ty,
5389 SourceLocation RParenLoc,
5390 Expr *InitExpr);
5391
5392 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5393 TypeSourceInfo *TInfo,
5394 SourceLocation RParenLoc,
5395 Expr *LiteralExpr);
5396
5397 ExprResult ActOnInitList(SourceLocation LBraceLoc,
5398 MultiExprArg InitArgList,
5399 SourceLocation RBraceLoc);
5400
5401 ExprResult BuildInitList(SourceLocation LBraceLoc,
5402 MultiExprArg InitArgList,
5403 SourceLocation RBraceLoc);
5404
5405 ExprResult ActOnDesignatedInitializer(Designation &Desig,
5406 SourceLocation EqualOrColonLoc,
5407 bool GNUSyntax,
5408 ExprResult Init);
5409
5410private:
5411 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5412
5413public:
5414 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5415 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5416 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5417 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5418 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5419 Expr *LHSExpr, Expr *RHSExpr);
5420 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
5421 UnresolvedSetImpl &Functions);
5422
5423 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5424
5425 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5426 /// in the case of a the GNU conditional expr extension.
5427 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5428 SourceLocation ColonLoc,
5429 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5430
5431 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5432 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5433 LabelDecl *TheDecl);
5434
5435 void ActOnStartStmtExpr();
5436 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5437 SourceLocation RPLoc);
5438 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5439 SourceLocation RPLoc, unsigned TemplateDepth);
5440 // Handle the final expression in a statement expression.
5441 ExprResult ActOnStmtExprResult(ExprResult E);
5442 void ActOnStmtExprError();
5443
5444 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5445 struct OffsetOfComponent {
5446 SourceLocation LocStart, LocEnd;
5447 bool isBrackets; // true if [expr], false if .ident
5448 union {
5449 IdentifierInfo *IdentInfo;
5450 Expr *E;
5451 } U;
5452 };
5453
5454 /// __builtin_offsetof(type, a.b[123][456].c)
5455 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5456 TypeSourceInfo *TInfo,
5457 ArrayRef<OffsetOfComponent> Components,
5458 SourceLocation RParenLoc);
5459 ExprResult ActOnBuiltinOffsetOf(Scope *S,
5460 SourceLocation BuiltinLoc,
5461 SourceLocation TypeLoc,
5462 ParsedType ParsedArgTy,
5463 ArrayRef<OffsetOfComponent> Components,
5464 SourceLocation RParenLoc);
5465
5466 // __builtin_choose_expr(constExpr, expr1, expr2)
5467 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5468 Expr *CondExpr, Expr *LHSExpr,
5469 Expr *RHSExpr, SourceLocation RPLoc);
5470
5471 // __builtin_va_arg(expr, type)
5472 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5473 SourceLocation RPLoc);
5474 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5475 TypeSourceInfo *TInfo, SourceLocation RPLoc);
5476
5477 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5478 // __builtin_COLUMN()
5479 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5480 SourceLocation BuiltinLoc,
5481 SourceLocation RPLoc);
5482
5483 // Build a potentially resolved SourceLocExpr.
5484 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5485 SourceLocation BuiltinLoc, SourceLocation RPLoc,
5486 DeclContext *ParentContext);
5487
5488 // __null
5489 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5490
5491 bool CheckCaseExpression(Expr *E);
5492
5493 /// Describes the result of an "if-exists" condition check.
5494 enum IfExistsResult {
5495 /// The symbol exists.
5496 IER_Exists,
5497
5498 /// The symbol does not exist.
5499 IER_DoesNotExist,
5500
5501 /// The name is a dependent name, so the results will differ
5502 /// from one instantiation to the next.
5503 IER_Dependent,
5504
5505 /// An error occurred.
5506 IER_Error
5507 };
5508
5509 IfExistsResult
5510 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5511 const DeclarationNameInfo &TargetNameInfo);
5512
5513 IfExistsResult
5514 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5515 bool IsIfExists, CXXScopeSpec &SS,
5516 UnqualifiedId &Name);
5517
5518 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5519 bool IsIfExists,
5520 NestedNameSpecifierLoc QualifierLoc,
5521 DeclarationNameInfo NameInfo,
5522 Stmt *Nested);
5523 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5524 bool IsIfExists,
5525 CXXScopeSpec &SS, UnqualifiedId &Name,
5526 Stmt *Nested);
5527
5528 //===------------------------- "Block" Extension ------------------------===//
5529
5530 /// ActOnBlockStart - This callback is invoked when a block literal is
5531 /// started.
5532 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5533
5534 /// ActOnBlockArguments - This callback allows processing of block arguments.
5535 /// If there are no arguments, this is still invoked.
5536 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5537 Scope *CurScope);
5538
5539 /// ActOnBlockError - If there is an error parsing a block, this callback
5540 /// is invoked to pop the information about the block from the action impl.
5541 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5542
5543 /// ActOnBlockStmtExpr - This is called when the body of a block statement
5544 /// literal was successfully completed. ^(int x){...}
5545 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5546 Scope *CurScope);
5547
5548 //===---------------------------- Clang Extensions ----------------------===//
5549
5550 /// __builtin_convertvector(...)
5551 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5552 SourceLocation BuiltinLoc,
5553 SourceLocation RParenLoc);
5554
5555 //===---------------------------- OpenCL Features -----------------------===//
5556
5557 /// __builtin_astype(...)
5558 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5559 SourceLocation BuiltinLoc,
5560 SourceLocation RParenLoc);
5561
5562 //===---------------------------- C++ Features --------------------------===//
5563
5564 // Act on C++ namespaces
5565 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5566 SourceLocation NamespaceLoc,
5567 SourceLocation IdentLoc, IdentifierInfo *Ident,
5568 SourceLocation LBrace,
5569 const ParsedAttributesView &AttrList,
5570 UsingDirectiveDecl *&UsingDecl);
5571 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5572
5573 NamespaceDecl *getStdNamespace() const;
5574 NamespaceDecl *getOrCreateStdNamespace();
5575
5576 NamespaceDecl *lookupStdExperimentalNamespace();
5577
5578 CXXRecordDecl *getStdBadAlloc() const;
5579 EnumDecl *getStdAlignValT() const;
5580
5581private:
5582 // A cache representing if we've fully checked the various comparison category
5583 // types stored in ASTContext. The bit-index corresponds to the integer value
5584 // of a ComparisonCategoryType enumerator.
5585 llvm::SmallBitVector FullyCheckedComparisonCategories;
5586
5587 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5588 CXXScopeSpec &SS,
5589 ParsedType TemplateTypeTy,
5590 IdentifierInfo *MemberOrBase);
5591
5592public:
5593 enum class ComparisonCategoryUsage {
5594 /// The '<=>' operator was used in an expression and a builtin operator
5595 /// was selected.
5596 OperatorInExpression,
5597 /// A defaulted 'operator<=>' needed the comparison category. This
5598 /// typically only applies to 'std::strong_ordering', due to the implicit
5599 /// fallback return value.
5600 DefaultedOperator,
5601 };
5602
5603 /// Lookup the specified comparison category types in the standard
5604 /// library, an check the VarDecls possibly returned by the operator<=>
5605 /// builtins for that type.
5606 ///
5607 /// \return The type of the comparison category type corresponding to the
5608 /// specified Kind, or a null type if an error occurs
5609 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5610 SourceLocation Loc,
5611 ComparisonCategoryUsage Usage);
5612
5613 /// Tests whether Ty is an instance of std::initializer_list and, if
5614 /// it is and Element is not NULL, assigns the element type to Element.
5615 bool isStdInitializerList(QualType Ty, QualType *Element);
5616
5617 /// Looks for the std::initializer_list template and instantiates it
5618 /// with Element, or emits an error if it's not found.
5619 ///
5620 /// \returns The instantiated template, or null on error.
5621 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5622
5623 /// Determine whether Ctor is an initializer-list constructor, as
5624 /// defined in [dcl.init.list]p2.
5625 bool isInitListConstructor(const FunctionDecl *Ctor);
5626
5627 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5628 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5629 SourceLocation IdentLoc,
5630 IdentifierInfo *NamespcName,
5631 const ParsedAttributesView &AttrList);
5632
5633 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5634
5635 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5636 SourceLocation NamespaceLoc,
5637 SourceLocation AliasLoc,
5638 IdentifierInfo *Alias,
5639 CXXScopeSpec &SS,
5640 SourceLocation IdentLoc,
5641 IdentifierInfo *Ident);
5642
5643 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5644 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
5645 const LookupResult &PreviousDecls,
5646 UsingShadowDecl *&PrevShadow);
5647 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5648 NamedDecl *Target,
5649 UsingShadowDecl *PrevDecl);
5650
5651 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5652 bool HasTypenameKeyword,
5653 const CXXScopeSpec &SS,
5654 SourceLocation NameLoc,
5655 const LookupResult &Previous);
5656 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5657 bool HasTypename,
5658 const CXXScopeSpec &SS,
5659 const DeclarationNameInfo &NameInfo,
5660 SourceLocation NameLoc);
5661
5662 NamedDecl *BuildUsingDeclaration(
5663 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5664 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5665 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5666 const ParsedAttributesView &AttrList, bool IsInstantiation);
5667 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5668 ArrayRef<NamedDecl *> Expansions);
5669
5670 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5671
5672 /// Given a derived-class using shadow declaration for a constructor and the
5673 /// correspnding base class constructor, find or create the implicit
5674 /// synthesized derived class constructor to use for this initialization.
5675 CXXConstructorDecl *
5676 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5677 ConstructorUsingShadowDecl *DerivedShadow);
5678
5679 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5680 SourceLocation UsingLoc,
5681 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5682 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5683 const ParsedAttributesView &AttrList);
5684 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5685 MultiTemplateParamsArg TemplateParams,
5686 SourceLocation UsingLoc, UnqualifiedId &Name,
5687 const ParsedAttributesView &AttrList,
5688 TypeResult Type, Decl *DeclFromDeclSpec);
5689
5690 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5691 /// including handling of its default argument expressions.
5692 ///
5693 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5694 ExprResult
5695 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5696 NamedDecl *FoundDecl,
5697 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5698 bool HadMultipleCandidates, bool IsListInitialization,
5699 bool IsStdInitListInitialization,
5700 bool RequiresZeroInit, unsigned ConstructKind,
5701 SourceRange ParenRange);
5702
5703 /// Build a CXXConstructExpr whose constructor has already been resolved if
5704 /// it denotes an inherited constructor.
5705 ExprResult
5706 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5707 CXXConstructorDecl *Constructor, bool Elidable,
5708 MultiExprArg Exprs,
5709 bool HadMultipleCandidates, bool IsListInitialization,
5710 bool IsStdInitListInitialization,
5711 bool RequiresZeroInit, unsigned ConstructKind,
5712 SourceRange ParenRange);
5713
5714 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5715 // the constructor can be elidable?
5716 ExprResult
5717 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5718 NamedDecl *FoundDecl,
5719 CXXConstructorDecl *Constructor, bool Elidable,
5720 MultiExprArg Exprs, bool HadMultipleCandidates,
5721 bool IsListInitialization,
5722 bool IsStdInitListInitialization, bool RequiresZeroInit,
5723 unsigned ConstructKind, SourceRange ParenRange);
5724
5725 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5726
5727
5728 /// Instantiate or parse a C++ default argument expression as necessary.
5729 /// Return true on error.
5730 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5731 ParmVarDecl *Param);
5732
5733 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5734 /// the default expr if needed.
5735 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5736 FunctionDecl *FD,
5737 ParmVarDecl *Param);
5738
5739 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5740 /// constructed variable.
5741 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5742
5743 /// Helper class that collects exception specifications for
5744 /// implicitly-declared special member functions.
5745 class ImplicitExceptionSpecification {
5746 // Pointer to allow copying
5747 Sema *Self;
5748 // We order exception specifications thus:
5749 // noexcept is the most restrictive, but is only used in C++11.
5750 // throw() comes next.
5751 // Then a throw(collected exceptions)
5752 // Finally no specification, which is expressed as noexcept(false).
5753 // throw(...) is used instead if any called function uses it.
5754 ExceptionSpecificationType ComputedEST;
5755 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5756 SmallVector<QualType, 4> Exceptions;
5757
5758 void ClearExceptions() {
5759 ExceptionsSeen.clear();
5760 Exceptions.clear();
5761 }
5762
5763 public:
5764 explicit ImplicitExceptionSpecification(Sema &Self)
5765 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5766 if (!Self.getLangOpts().CPlusPlus11)
5767 ComputedEST = EST_DynamicNone;
5768 }
5769
5770 /// Get the computed exception specification type.
5771 ExceptionSpecificationType getExceptionSpecType() const {
5772 assert(!isComputedNoexcept(ComputedEST) &&((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 5773, __PRETTY_FUNCTION__))
5773 "noexcept(expr) should not be a possible result")((!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 5773, __PRETTY_FUNCTION__))
;
5774 return ComputedEST;
5775 }
5776
5777 /// The number of exceptions in the exception specification.
5778 unsigned size() const { return Exceptions.size(); }
5779
5780 /// The set of exceptions in the exception specification.
5781 const QualType *data() const { return Exceptions.data(); }
5782
5783 /// Integrate another called method into the collected data.
5784 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5785
5786 /// Integrate an invoked expression into the collected data.
5787 void CalledExpr(Expr *E) { CalledStmt(E); }
5788
5789 /// Integrate an invoked statement into the collected data.
5790 void CalledStmt(Stmt *S);
5791
5792 /// Overwrite an EPI's exception specification with this
5793 /// computed exception specification.
5794 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5795 FunctionProtoType::ExceptionSpecInfo ESI;
5796 ESI.Type = getExceptionSpecType();
5797 if (ESI.Type == EST_Dynamic) {
5798 ESI.Exceptions = Exceptions;
5799 } else if (ESI.Type == EST_None) {
5800 /// C++11 [except.spec]p14:
5801 /// The exception-specification is noexcept(false) if the set of
5802 /// potential exceptions of the special member function contains "any"
5803 ESI.Type = EST_NoexceptFalse;
5804 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5805 tok::kw_false).get();
5806 }
5807 return ESI;
5808 }
5809 };
5810
5811 /// Evaluate the implicit exception specification for a defaulted
5812 /// special member function.
5813 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5814
5815 /// Check the given noexcept-specifier, convert its expression, and compute
5816 /// the appropriate ExceptionSpecificationType.
5817 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5818 ExceptionSpecificationType &EST);
5819
5820 /// Check the given exception-specification and update the
5821 /// exception specification information with the results.
5822 void checkExceptionSpecification(bool IsTopLevel,
5823 ExceptionSpecificationType EST,
5824 ArrayRef<ParsedType> DynamicExceptions,
5825 ArrayRef<SourceRange> DynamicExceptionRanges,
5826 Expr *NoexceptExpr,
5827 SmallVectorImpl<QualType> &Exceptions,
5828 FunctionProtoType::ExceptionSpecInfo &ESI);
5829
5830 /// Determine if we're in a case where we need to (incorrectly) eagerly
5831 /// parse an exception specification to work around a libstdc++ bug.
5832 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5833
5834 /// Add an exception-specification to the given member function
5835 /// (or member function template). The exception-specification was parsed
5836 /// after the method itself was declared.
5837 void actOnDelayedExceptionSpecification(Decl *Method,
5838 ExceptionSpecificationType EST,
5839 SourceRange SpecificationRange,
5840 ArrayRef<ParsedType> DynamicExceptions,
5841 ArrayRef<SourceRange> DynamicExceptionRanges,
5842 Expr *NoexceptExpr);
5843
5844 class InheritedConstructorInfo;
5845
5846 /// Determine if a special member function should have a deleted
5847 /// definition when it is defaulted.
5848 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5849 InheritedConstructorInfo *ICI = nullptr,
5850 bool Diagnose = false);
5851
5852 /// Produce notes explaining why a defaulted function was defined as deleted.
5853 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5854
5855 /// Declare the implicit default constructor for the given class.
5856 ///
5857 /// \param ClassDecl The class declaration into which the implicit
5858 /// default constructor will be added.
5859 ///
5860 /// \returns The implicitly-declared default constructor.
5861 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5862 CXXRecordDecl *ClassDecl);
5863
5864 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5865 /// defining this constructor as the default constructor.
5866 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5867 CXXConstructorDecl *Constructor);
5868
5869 /// Declare the implicit destructor for the given class.
5870 ///
5871 /// \param ClassDecl The class declaration into which the implicit
5872 /// destructor will be added.
5873 ///
5874 /// \returns The implicitly-declared destructor.
5875 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5876
5877 /// DefineImplicitDestructor - Checks for feasibility of
5878 /// defining this destructor as the default destructor.
5879 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5880 CXXDestructorDecl *Destructor);
5881
5882 /// Build an exception spec for destructors that don't have one.
5883 ///
5884 /// C++11 says that user-defined destructors with no exception spec get one
5885 /// that looks as if the destructor was implicitly declared.
5886 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5887
5888 /// Define the specified inheriting constructor.
5889 void DefineInheritingConstructor(SourceLocation UseLoc,
5890 CXXConstructorDecl *Constructor);
5891
5892 /// Declare the implicit copy constructor for the given class.
5893 ///
5894 /// \param ClassDecl The class declaration into which the implicit
5895 /// copy constructor will be added.
5896 ///
5897 /// \returns The implicitly-declared copy constructor.
5898 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5899
5900 /// DefineImplicitCopyConstructor - Checks for feasibility of
5901 /// defining this constructor as the copy constructor.
5902 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5903 CXXConstructorDecl *Constructor);
5904
5905 /// Declare the implicit move constructor for the given class.
5906 ///
5907 /// \param ClassDecl The Class declaration into which the implicit
5908 /// move constructor will be added.
5909 ///
5910 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5911 /// declared.
5912 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5913
5914 /// DefineImplicitMoveConstructor - Checks for feasibility of
5915 /// defining this constructor as the move constructor.
5916 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5917 CXXConstructorDecl *Constructor);
5918
5919 /// Declare the implicit copy assignment operator for the given class.
5920 ///
5921 /// \param ClassDecl The class declaration into which the implicit
5922 /// copy assignment operator will be added.
5923 ///
5924 /// \returns The implicitly-declared copy assignment operator.
5925 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5926
5927 /// Defines an implicitly-declared copy assignment operator.
5928 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5929 CXXMethodDecl *MethodDecl);
5930
5931 /// Declare the implicit move assignment operator for the given class.
5932 ///
5933 /// \param ClassDecl The Class declaration into which the implicit
5934 /// move assignment operator will be added.
5935 ///
5936 /// \returns The implicitly-declared move assignment operator, or NULL if it
5937 /// wasn't declared.
5938 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5939
5940 /// Defines an implicitly-declared move assignment operator.
5941 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5942 CXXMethodDecl *MethodDecl);
5943
5944 /// Force the declaration of any implicitly-declared members of this
5945 /// class.
5946 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
5947
5948 /// Check a completed declaration of an implicit special member.
5949 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5950
5951 /// Determine whether the given function is an implicitly-deleted
5952 /// special member function.
5953 bool isImplicitlyDeleted(FunctionDecl *FD);
5954
5955 /// Check whether 'this' shows up in the type of a static member
5956 /// function after the (naturally empty) cv-qualifier-seq would be.
5957 ///
5958 /// \returns true if an error occurred.
5959 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5960
5961 /// Whether this' shows up in the exception specification of a static
5962 /// member function.
5963 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5964
5965 /// Check whether 'this' shows up in the attributes of the given
5966 /// static member function.
5967 ///
5968 /// \returns true if an error occurred.
5969 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5970
5971 /// MaybeBindToTemporary - If the passed in expression has a record type with
5972 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
5973 /// it simply returns the passed in expression.
5974 ExprResult MaybeBindToTemporary(Expr *E);
5975
5976 /// Wrap the expression in a ConstantExpr if it is a potential immediate
5977 /// invocation.
5978 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
5979
5980 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5981 MultiExprArg ArgsPtr,
5982 SourceLocation Loc,
5983 SmallVectorImpl<Expr*> &ConvertedArgs,
5984 bool AllowExplicit = false,
5985 bool IsListInitialization = false);
5986
5987 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5988 SourceLocation NameLoc,
5989 IdentifierInfo &Name);
5990
5991 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5992 Scope *S, CXXScopeSpec &SS,
5993 bool EnteringContext);
5994 ParsedType getDestructorName(SourceLocation TildeLoc,
5995 IdentifierInfo &II, SourceLocation NameLoc,
5996 Scope *S, CXXScopeSpec &SS,
5997 ParsedType ObjectType,
5998 bool EnteringContext);
5999
6000 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
6001 ParsedType ObjectType);
6002
6003 // Checks that reinterpret casts don't have undefined behavior.
6004 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
6005 bool IsDereference, SourceRange Range);
6006
6007 /// ActOnCXXNamedCast - Parse
6008 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
6009 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
6010 tok::TokenKind Kind,
6011 SourceLocation LAngleBracketLoc,
6012 Declarator &D,
6013 SourceLocation RAngleBracketLoc,
6014 SourceLocation LParenLoc,
6015 Expr *E,
6016 SourceLocation RParenLoc);
6017
6018 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
6019 tok::TokenKind Kind,
6020 TypeSourceInfo *Ty,
6021 Expr *E,
6022 SourceRange AngleBrackets,
6023 SourceRange Parens);
6024
6025 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
6026 ExprResult Operand,
6027 SourceLocation RParenLoc);
6028
6029 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
6030 Expr *Operand, SourceLocation RParenLoc);
6031
6032 ExprResult BuildCXXTypeId(QualType TypeInfoType,
6033 SourceLocation TypeidLoc,
6034 TypeSourceInfo *Operand,
6035 SourceLocation RParenLoc);
6036 ExprResult BuildCXXTypeId(QualType TypeInfoType,
6037 SourceLocation TypeidLoc,
6038 Expr *Operand,
6039 SourceLocation RParenLoc);
6040
6041 /// ActOnCXXTypeid - Parse typeid( something ).
6042 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
6043 SourceLocation LParenLoc, bool isType,
6044 void *TyOrExpr,
6045 SourceLocation RParenLoc);
6046
6047 ExprResult BuildCXXUuidof(QualType TypeInfoType,
6048 SourceLocation TypeidLoc,
6049 TypeSourceInfo *Operand,
6050 SourceLocation RParenLoc);
6051 ExprResult BuildCXXUuidof(QualType TypeInfoType,
6052 SourceLocation TypeidLoc,
6053 Expr *Operand,
6054 SourceLocation RParenLoc);
6055
6056 /// ActOnCXXUuidof - Parse __uuidof( something ).
6057 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
6058 SourceLocation LParenLoc, bool isType,
6059 void *TyOrExpr,
6060 SourceLocation RParenLoc);
6061
6062 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6063 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6064 tok::TokenKind Operator,
6065 SourceLocation EllipsisLoc, Expr *RHS,
6066 SourceLocation RParenLoc);
6067 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6068 SourceLocation LParenLoc, Expr *LHS,
6069 BinaryOperatorKind Operator,
6070 SourceLocation EllipsisLoc, Expr *RHS,
6071 SourceLocation RParenLoc,
6072 Optional<unsigned> NumExpansions);
6073 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6074 BinaryOperatorKind Operator);
6075
6076 //// ActOnCXXThis - Parse 'this' pointer.
6077 ExprResult ActOnCXXThis(SourceLocation loc);
6078
6079 /// Build a CXXThisExpr and mark it referenced in the current context.
6080 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6081 void MarkThisReferenced(CXXThisExpr *This);
6082
6083 /// Try to retrieve the type of the 'this' pointer.
6084 ///
6085 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6086 QualType getCurrentThisType();
6087
6088 /// When non-NULL, the C++ 'this' expression is allowed despite the
6089 /// current context not being a non-static member function. In such cases,
6090 /// this provides the type used for 'this'.
6091 QualType CXXThisTypeOverride;
6092
6093 /// RAII object used to temporarily allow the C++ 'this' expression
6094 /// to be used, with the given qualifiers on the current class type.
6095 class CXXThisScopeRAII {
6096 Sema &S;
6097 QualType OldCXXThisTypeOverride;
6098 bool Enabled;
6099
6100 public:
6101 /// Introduce a new scope where 'this' may be allowed (when enabled),
6102 /// using the given declaration (which is either a class template or a
6103 /// class) along with the given qualifiers.
6104 /// along with the qualifiers placed on '*this'.
6105 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6106 bool Enabled = true);
6107
6108 ~CXXThisScopeRAII();
6109 };
6110
6111 /// Make sure the value of 'this' is actually available in the current
6112 /// context, if it is a potentially evaluated context.
6113 ///
6114 /// \param Loc The location at which the capture of 'this' occurs.
6115 ///
6116 /// \param Explicit Whether 'this' is explicitly captured in a lambda
6117 /// capture list.
6118 ///
6119 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6120 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6121 /// This is useful when enclosing lambdas must speculatively capture
6122 /// 'this' that may or may not be used in certain specializations of
6123 /// a nested generic lambda (depending on whether the name resolves to
6124 /// a non-static member function or a static function).
6125 /// \return returns 'true' if failed, 'false' if success.
6126 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6127 bool BuildAndDiagnose = true,
6128 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6129 bool ByCopy = false);
6130
6131 /// Determine whether the given type is the type of *this that is used
6132 /// outside of the body of a member function for a type that is currently
6133 /// being defined.
6134 bool isThisOutsideMemberFunctionBody(QualType BaseType);
6135
6136 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6137 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6138
6139
6140 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6141 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6142
6143 ExprResult
6144 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6145 SourceLocation AtLoc, SourceLocation RParen);
6146
6147 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6148 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6149
6150 //// ActOnCXXThrow - Parse throw expressions.
6151 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6152 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6153 bool IsThrownVarInScope);
6154 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6155
6156 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6157 /// Can be interpreted either as function-style casting ("int(x)")
6158 /// or class type construction ("ClassType(x,y,z)")
6159 /// or creation of a value-initialized type ("int()").
6160 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6161 SourceLocation LParenOrBraceLoc,
6162 MultiExprArg Exprs,
6163 SourceLocation RParenOrBraceLoc,
6164 bool ListInitialization);
6165
6166 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6167 SourceLocation LParenLoc,
6168 MultiExprArg Exprs,
6169 SourceLocation RParenLoc,
6170 bool ListInitialization);
6171
6172 /// ActOnCXXNew - Parsed a C++ 'new' expression.
6173 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6174 SourceLocation PlacementLParen,
6175 MultiExprArg PlacementArgs,
6176 SourceLocation PlacementRParen,
6177 SourceRange TypeIdParens, Declarator &D,
6178 Expr *Initializer);
6179 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
6180 SourceLocation PlacementLParen,
6181 MultiExprArg PlacementArgs,
6182 SourceLocation PlacementRParen,
6183 SourceRange TypeIdParens,
6184 QualType AllocType,
6185 TypeSourceInfo *AllocTypeInfo,
6186 Optional<Expr *> ArraySize,
6187 SourceRange DirectInitRange,
6188 Expr *Initializer);
6189
6190 /// Determine whether \p FD is an aligned allocation or deallocation
6191 /// function that is unavailable.
6192 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6193
6194 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6195 /// function that is unavailable.
6196 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6197 SourceLocation Loc);
6198
6199 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6200 SourceRange R);
6201
6202 /// The scope in which to find allocation functions.
6203 enum AllocationFunctionScope {
6204 /// Only look for allocation functions in the global scope.
6205 AFS_Global,
6206 /// Only look for allocation functions in the scope of the
6207 /// allocated class.
6208 AFS_Class,
6209 /// Look for allocation functions in both the global scope
6210 /// and in the scope of the allocated class.
6211 AFS_Both
6212 };
6213
6214 /// Finds the overloads of operator new and delete that are appropriate
6215 /// for the allocation.
6216 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6217 AllocationFunctionScope NewScope,
6218 AllocationFunctionScope DeleteScope,
6219 QualType AllocType, bool IsArray,
6220 bool &PassAlignment, MultiExprArg PlaceArgs,
6221 FunctionDecl *&OperatorNew,
6222 FunctionDecl *&OperatorDelete,
6223 bool Diagnose = true);
6224 void DeclareGlobalNewDelete();
6225 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6226 ArrayRef<QualType> Params);
6227
6228 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6229 DeclarationName Name, FunctionDecl* &Operator,
6230 bool Diagnose = true);
6231 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6232 bool CanProvideSize,
6233 bool Overaligned,
6234 DeclarationName Name);
6235 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6236 CXXRecordDecl *RD);
6237
6238 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6239 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6240 bool UseGlobal, bool ArrayForm,
6241 Expr *Operand);
6242 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6243 bool IsDelete, bool CallCanBeVirtual,
6244 bool WarnOnNonAbstractTypes,
6245 SourceLocation DtorLoc);
6246
6247 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6248 Expr *Operand, SourceLocation RParen);
6249 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6250 SourceLocation RParen);
6251
6252 /// Parsed one of the type trait support pseudo-functions.
6253 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6254 ArrayRef<ParsedType> Args,
6255 SourceLocation RParenLoc);
6256 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6257 ArrayRef<TypeSourceInfo *> Args,
6258 SourceLocation RParenLoc);
6259
6260 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6261 /// pseudo-functions.
6262 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6263 SourceLocation KWLoc,
6264 ParsedType LhsTy,
6265 Expr *DimExpr,
6266 SourceLocation RParen);
6267
6268 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6269 SourceLocation KWLoc,
6270 TypeSourceInfo *TSInfo,
6271 Expr *DimExpr,
6272 SourceLocation RParen);
6273
6274 /// ActOnExpressionTrait - Parsed one of the unary type trait support
6275 /// pseudo-functions.
6276 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6277 SourceLocation KWLoc,
6278 Expr *Queried,
6279 SourceLocation RParen);
6280
6281 ExprResult BuildExpressionTrait(ExpressionTrait OET,
6282 SourceLocation KWLoc,
6283 Expr *Queried,
6284 SourceLocation RParen);
6285
6286 ExprResult ActOnStartCXXMemberReference(Scope *S,
6287 Expr *Base,
6288 SourceLocation OpLoc,
6289 tok::TokenKind OpKind,
6290 ParsedType &ObjectType,
6291 bool &MayBePseudoDestructor);
6292
6293 ExprResult BuildPseudoDestructorExpr(Expr *Base,
6294 SourceLocation OpLoc,
6295 tok::TokenKind OpKind,
6296 const CXXScopeSpec &SS,
6297 TypeSourceInfo *ScopeType,
6298 SourceLocation CCLoc,
6299 SourceLocation TildeLoc,
6300 PseudoDestructorTypeStorage DestroyedType);
6301
6302 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6303 SourceLocation OpLoc,
6304 tok::TokenKind OpKind,
6305 CXXScopeSpec &SS,
6306 UnqualifiedId &FirstTypeName,
6307 SourceLocation CCLoc,
6308 SourceLocation TildeLoc,
6309 UnqualifiedId &SecondTypeName);
6310
6311 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6312 SourceLocation OpLoc,
6313 tok::TokenKind OpKind,
6314 SourceLocation TildeLoc,
6315 const DeclSpec& DS);
6316
6317 /// MaybeCreateExprWithCleanups - If the current full-expression
6318 /// requires any cleanups, surround it with a ExprWithCleanups node.
6319 /// Otherwise, just returns the passed-in expression.
6320 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6321 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6322 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6323
6324 MaterializeTemporaryExpr *
6325 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6326 bool BoundToLvalueReference);
6327
6328 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6329 return ActOnFinishFullExpr(
6330 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6331 }
6332 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6333 bool DiscardedValue, bool IsConstexpr = false);
6334 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6335
6336 // Marks SS invalid if it represents an incomplete type.
6337 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6338
6339 DeclContext *computeDeclContext(QualType T);
6340 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6341 bool EnteringContext = false);
6342 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6343 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6344
6345 /// The parser has parsed a global nested-name-specifier '::'.
6346 ///
6347 /// \param CCLoc The location of the '::'.
6348 ///
6349 /// \param SS The nested-name-specifier, which will be updated in-place
6350 /// to reflect the parsed nested-name-specifier.
6351 ///
6352 /// \returns true if an error occurred, false otherwise.
6353 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6354
6355 /// The parser has parsed a '__super' nested-name-specifier.
6356 ///
6357 /// \param SuperLoc The location of the '__super' keyword.
6358 ///
6359 /// \param ColonColonLoc The location of the '::'.
6360 ///
6361 /// \param SS The nested-name-specifier, which will be updated in-place
6362 /// to reflect the parsed nested-name-specifier.
6363 ///
6364 /// \returns true if an error occurred, false otherwise.
6365 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6366 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6367
6368 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6369 bool *CanCorrect = nullptr);
6370 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6371
6372 /// Keeps information about an identifier in a nested-name-spec.
6373 ///
6374 struct NestedNameSpecInfo {
6375 /// The type of the object, if we're parsing nested-name-specifier in
6376 /// a member access expression.
6377 ParsedType ObjectType;
6378
6379 /// The identifier preceding the '::'.
6380 IdentifierInfo *Identifier;
6381
6382 /// The location of the identifier.
6383 SourceLocation IdentifierLoc;
6384
6385 /// The location of the '::'.
6386 SourceLocation CCLoc;
6387
6388 /// Creates info object for the most typical case.
6389 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6390 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
6391 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6392 CCLoc(ColonColonLoc) {
6393 }
6394
6395 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6396 SourceLocation ColonColonLoc, QualType ObjectType)
6397 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6398 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6399 }
6400 };
6401
6402 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6403 NestedNameSpecInfo &IdInfo);
6404
6405 bool BuildCXXNestedNameSpecifier(Scope *S,
6406 NestedNameSpecInfo &IdInfo,
6407 bool EnteringContext,
6408 CXXScopeSpec &SS,
6409 NamedDecl *ScopeLookupResult,
6410 bool ErrorRecoveryLookup,
6411 bool *IsCorrectedToColon = nullptr,
6412 bool OnlyNamespace = false);
6413
6414 /// The parser has parsed a nested-name-specifier 'identifier::'.
6415 ///
6416 /// \param S The scope in which this nested-name-specifier occurs.
6417 ///
6418 /// \param IdInfo Parser information about an identifier in the
6419 /// nested-name-spec.
6420 ///
6421 /// \param EnteringContext Whether we're entering the context nominated by
6422 /// this nested-name-specifier.
6423 ///
6424 /// \param SS The nested-name-specifier, which is both an input
6425 /// parameter (the nested-name-specifier before this type) and an
6426 /// output parameter (containing the full nested-name-specifier,
6427 /// including this new type).
6428 ///
6429 /// \param ErrorRecoveryLookup If true, then this method is called to improve
6430 /// error recovery. In this case do not emit error message.
6431 ///
6432 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6433 /// are allowed. The bool value pointed by this parameter is set to 'true'
6434 /// if the identifier is treated as if it was followed by ':', not '::'.
6435 ///
6436 /// \param OnlyNamespace If true, only considers namespaces in lookup.
6437 ///
6438 /// \returns true if an error occurred, false otherwise.
6439 bool ActOnCXXNestedNameSpecifier(Scope *S,
6440 NestedNameSpecInfo &IdInfo,
6441 bool EnteringContext,
6442 CXXScopeSpec &SS,
6443 bool ErrorRecoveryLookup = false,
6444 bool *IsCorrectedToColon = nullptr,
6445 bool OnlyNamespace = false);
6446
6447 ExprResult ActOnDecltypeExpression(Expr *E);
6448
6449 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6450 const DeclSpec &DS,
6451 SourceLocation ColonColonLoc);
6452
6453 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6454 NestedNameSpecInfo &IdInfo,
6455 bool EnteringContext);
6456
6457 /// The parser has parsed a nested-name-specifier
6458 /// 'template[opt] template-name < template-args >::'.
6459 ///
6460 /// \param S The scope in which this nested-name-specifier occurs.
6461 ///
6462 /// \param SS The nested-name-specifier, which is both an input
6463 /// parameter (the nested-name-specifier before this type) and an
6464 /// output parameter (containing the full nested-name-specifier,
6465 /// including this new type).
6466 ///
6467 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6468 /// \param TemplateName the template name.
6469 /// \param TemplateNameLoc The location of the template name.
6470 /// \param LAngleLoc The location of the opening angle bracket ('<').
6471 /// \param TemplateArgs The template arguments.
6472 /// \param RAngleLoc The location of the closing angle bracket ('>').
6473 /// \param CCLoc The location of the '::'.
6474 ///
6475 /// \param EnteringContext Whether we're entering the context of the
6476 /// nested-name-specifier.
6477 ///
6478 ///
6479 /// \returns true if an error occurred, false otherwise.
6480 bool ActOnCXXNestedNameSpecifier(Scope *S,
6481 CXXScopeSpec &SS,
6482 SourceLocation TemplateKWLoc,
6483 TemplateTy TemplateName,
6484 SourceLocation TemplateNameLoc,
6485 SourceLocation LAngleLoc,
6486 ASTTemplateArgsPtr TemplateArgs,
6487 SourceLocation RAngleLoc,
6488 SourceLocation CCLoc,
6489 bool EnteringContext);
6490
6491 /// Given a C++ nested-name-specifier, produce an annotation value
6492 /// that the parser can use later to reconstruct the given
6493 /// nested-name-specifier.
6494 ///
6495 /// \param SS A nested-name-specifier.
6496 ///
6497 /// \returns A pointer containing all of the information in the
6498 /// nested-name-specifier \p SS.
6499 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6500
6501 /// Given an annotation pointer for a nested-name-specifier, restore
6502 /// the nested-name-specifier structure.
6503 ///
6504 /// \param Annotation The annotation pointer, produced by
6505 /// \c SaveNestedNameSpecifierAnnotation().
6506 ///
6507 /// \param AnnotationRange The source range corresponding to the annotation.
6508 ///
6509 /// \param SS The nested-name-specifier that will be updated with the contents
6510 /// of the annotation pointer.
6511 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6512 SourceRange AnnotationRange,
6513 CXXScopeSpec &SS);
6514
6515 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6516
6517 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6518 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6519 /// After this method is called, according to [C++ 3.4.3p3], names should be
6520 /// looked up in the declarator-id's scope, until the declarator is parsed and
6521 /// ActOnCXXExitDeclaratorScope is called.
6522 /// The 'SS' should be a non-empty valid CXXScopeSpec.
6523 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6524
6525 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6526 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6527 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6528 /// Used to indicate that names should revert to being looked up in the
6529 /// defining scope.
6530 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6531
6532 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6533 /// initializer for the declaration 'Dcl'.
6534 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6535 /// static data member of class X, names should be looked up in the scope of
6536 /// class X.
6537 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6538
6539 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6540 /// initializer for the declaration 'Dcl'.
6541 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6542
6543 /// Create a new lambda closure type.
6544 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6545 TypeSourceInfo *Info,
6546 bool KnownDependent,
6547 LambdaCaptureDefault CaptureDefault);
6548
6549 /// Start the definition of a lambda expression.
6550 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6551 SourceRange IntroducerRange,
6552 TypeSourceInfo *MethodType,
6553 SourceLocation EndLoc,
6554 ArrayRef<ParmVarDecl *> Params,
6555 ConstexprSpecKind ConstexprKind,
6556 Expr *TrailingRequiresClause);
6557
6558 /// Number lambda for linkage purposes if necessary.
6559 void handleLambdaNumbering(
6560 CXXRecordDecl *Class, CXXMethodDecl *Method,
6561 Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
6562
6563 /// Endow the lambda scope info with the relevant properties.
6564 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6565 CXXMethodDecl *CallOperator,
6566 SourceRange IntroducerRange,
6567 LambdaCaptureDefault CaptureDefault,
6568 SourceLocation CaptureDefaultLoc,
6569 bool ExplicitParams,
6570 bool ExplicitResultType,
6571 bool Mutable);
6572
6573 /// Perform initialization analysis of the init-capture and perform
6574 /// any implicit conversions such as an lvalue-to-rvalue conversion if
6575 /// not being used to initialize a reference.
6576 ParsedType actOnLambdaInitCaptureInitialization(
6577 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6578 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6579 return ParsedType::make(buildLambdaInitCaptureInitialization(
6580 Loc, ByRef, EllipsisLoc, None, Id,
6581 InitKind != LambdaCaptureInitKind::CopyInit, Init));
6582 }
6583 QualType buildLambdaInitCaptureInitialization(
6584 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6585 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6586 Expr *&Init);
6587
6588 /// Create a dummy variable within the declcontext of the lambda's
6589 /// call operator, for name lookup purposes for a lambda init capture.
6590 ///
6591 /// CodeGen handles emission of lambda captures, ignoring these dummy
6592 /// variables appropriately.
6593 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6594 QualType InitCaptureType,
6595 SourceLocation EllipsisLoc,
6596 IdentifierInfo *Id,
6597 unsigned InitStyle, Expr *Init);
6598
6599 /// Add an init-capture to a lambda scope.
6600 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6601
6602 /// Note that we have finished the explicit captures for the
6603 /// given lambda.
6604 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6605
6606 /// \brief This is called after parsing the explicit template parameter list
6607 /// on a lambda (if it exists) in C++2a.
6608 void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6609 ArrayRef<NamedDecl *> TParams,
6610 SourceLocation RAngleLoc,
6611 ExprResult RequiresClause);
6612
6613 /// Introduce the lambda parameters into scope.
6614 void addLambdaParameters(
6615 ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6616 CXXMethodDecl *CallOperator, Scope *CurScope);
6617
6618 /// Deduce a block or lambda's return type based on the return
6619 /// statements present in the body.
6620 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6621
6622 /// ActOnStartOfLambdaDefinition - This is called just before we start
6623 /// parsing the body of a lambda; it analyzes the explicit captures and
6624 /// arguments, and sets up various data-structures for the body of the
6625 /// lambda.
6626 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6627 Declarator &ParamInfo, Scope *CurScope);
6628
6629 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6630 /// is invoked to pop the information about the lambda.
6631 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6632 bool IsInstantiation = false);
6633
6634 /// ActOnLambdaExpr - This is called when the body of a lambda expression
6635 /// was successfully completed.
6636 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6637 Scope *CurScope);
6638
6639 /// Does copying/destroying the captured variable have side effects?
6640 bool CaptureHasSideEffects(const sema::Capture &From);
6641
6642 /// Diagnose if an explicit lambda capture is unused. Returns true if a
6643 /// diagnostic is emitted.
6644 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6645 const sema::Capture &From);
6646
6647 /// Build a FieldDecl suitable to hold the given capture.
6648 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6649
6650 /// Initialize the given capture with a suitable expression.
6651 ExprResult BuildCaptureInit(const sema::Capture &Capture,
6652 SourceLocation ImplicitCaptureLoc,
6653 bool IsOpenMPMapping = false);
6654
6655 /// Complete a lambda-expression having processed and attached the
6656 /// lambda body.
6657 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6658 sema::LambdaScopeInfo *LSI);
6659
6660 /// Get the return type to use for a lambda's conversion function(s) to
6661 /// function pointer type, given the type of the call operator.
6662 QualType
6663 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
6664 CallingConv CC);
6665
6666 /// Define the "body" of the conversion from a lambda object to a
6667 /// function pointer.
6668 ///
6669 /// This routine doesn't actually define a sensible body; rather, it fills
6670 /// in the initialization expression needed to copy the lambda object into
6671 /// the block, and IR generation actually generates the real body of the
6672 /// block pointer conversion.
6673 void DefineImplicitLambdaToFunctionPointerConversion(
6674 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6675
6676 /// Define the "body" of the conversion from a lambda object to a
6677 /// block pointer.
6678 ///
6679 /// This routine doesn't actually define a sensible body; rather, it fills
6680 /// in the initialization expression needed to copy the lambda object into
6681 /// the block, and IR generation actually generates the real body of the
6682 /// block pointer conversion.
6683 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6684 CXXConversionDecl *Conv);
6685
6686 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6687 SourceLocation ConvLocation,
6688 CXXConversionDecl *Conv,
6689 Expr *Src);
6690
6691 /// Check whether the given expression is a valid constraint expression.
6692 /// A diagnostic is emitted if it is not, false is returned, and
6693 /// PossibleNonPrimary will be set to true if the failure might be due to a
6694 /// non-primary expression being used as an atomic constraint.
6695 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
6696 bool *PossibleNonPrimary = nullptr,
6697 bool IsTrailingRequiresClause = false);
6698
6699private:
6700 /// Caches pairs of template-like decls whose associated constraints were
6701 /// checked for subsumption and whether or not the first's constraints did in
6702 /// fact subsume the second's.
6703 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6704 /// Caches the normalized associated constraints of declarations (concepts or
6705 /// constrained declarations). If an error occurred while normalizing the
6706 /// associated constraints of the template or concept, nullptr will be cached
6707 /// here.
6708 llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6709 NormalizationCache;
6710
6711 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
6712 SatisfactionCache;
6713
6714public:
6715 const NormalizedConstraint *
6716 getNormalizedAssociatedConstraints(
6717 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
6718
6719 /// \brief Check whether the given declaration's associated constraints are
6720 /// at least as constrained than another declaration's according to the
6721 /// partial ordering of constraints.
6722 ///
6723 /// \param Result If no error occurred, receives the result of true if D1 is
6724 /// at least constrained than D2, and false otherwise.
6725 ///
6726 /// \returns true if an error occurred, false otherwise.
6727 bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
6728 NamedDecl *D2, ArrayRef<const Expr *> AC2,
6729 bool &Result);
6730
6731 /// If D1 was not at least as constrained as D2, but would've been if a pair
6732 /// of atomic constraints involved had been declared in a concept and not
6733 /// repeated in two separate places in code.
6734 /// \returns true if such a diagnostic was emitted, false otherwise.
6735 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
6736 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
6737
6738 /// \brief Check whether the given list of constraint expressions are
6739 /// satisfied (as if in a 'conjunction') given template arguments.
6740 /// \param Template the template-like entity that triggered the constraints
6741 /// check (either a concept or a constrained entity).
6742 /// \param ConstraintExprs a list of constraint expressions, treated as if
6743 /// they were 'AND'ed together.
6744 /// \param TemplateArgs the list of template arguments to substitute into the
6745 /// constraint expression.
6746 /// \param TemplateIDRange The source range of the template id that
6747 /// caused the constraints check.
6748 /// \param Satisfaction if true is returned, will contain details of the
6749 /// satisfaction, with enough information to diagnose an unsatisfied
6750 /// expression.
6751 /// \returns true if an error occurred and satisfaction could not be checked,
6752 /// false otherwise.
6753 bool CheckConstraintSatisfaction(
6754 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
6755 ArrayRef<TemplateArgument> TemplateArgs,
6756 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
6757
6758 /// \brief Check whether the given non-dependent constraint expression is
6759 /// satisfied. Returns false and updates Satisfaction with the satisfaction
6760 /// verdict if successful, emits a diagnostic and returns true if an error
6761 /// occured and satisfaction could not be determined.
6762 ///
6763 /// \returns true if an error occurred, false otherwise.
6764 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
6765 ConstraintSatisfaction &Satisfaction);
6766
6767 /// Check whether the given function decl's trailing requires clause is
6768 /// satisfied, if any. Returns false and updates Satisfaction with the
6769 /// satisfaction verdict if successful, emits a diagnostic and returns true if
6770 /// an error occured and satisfaction could not be determined.
6771 ///
6772 /// \returns true if an error occurred, false otherwise.
6773 bool CheckFunctionConstraints(const FunctionDecl *FD,
6774 ConstraintSatisfaction &Satisfaction,
6775 SourceLocation UsageLoc = SourceLocation());
6776
6777
6778 /// \brief Ensure that the given template arguments satisfy the constraints
6779 /// associated with the given template, emitting a diagnostic if they do not.
6780 ///
6781 /// \param Template The template to which the template arguments are being
6782 /// provided.
6783 ///
6784 /// \param TemplateArgs The converted, canonicalized template arguments.
6785 ///
6786 /// \param TemplateIDRange The source range of the template id that
6787 /// caused the constraints check.
6788 ///
6789 /// \returns true if the constrains are not satisfied or could not be checked
6790 /// for satisfaction, false if the constraints are satisfied.
6791 bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
6792 ArrayRef<TemplateArgument> TemplateArgs,
6793 SourceRange TemplateIDRange);
6794
6795 /// \brief Emit diagnostics explaining why a constraint expression was deemed
6796 /// unsatisfied.
6797 /// \param First whether this is the first time an unsatisfied constraint is
6798 /// diagnosed for this error.
6799 void
6800 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
6801 bool First = true);
6802
6803 /// \brief Emit diagnostics explaining why a constraint expression was deemed
6804 /// unsatisfied.
6805 void
6806 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
6807 bool First = true);
6808
6809 // ParseObjCStringLiteral - Parse Objective-C string literals.
6810 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6811 ArrayRef<Expr *> Strings);
6812
6813 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6814
6815 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6816 /// numeric literal expression. Type of the expression will be "NSNumber *"
6817 /// or "id" if NSNumber is unavailable.
6818 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6819 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6820 bool Value);
6821 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6822
6823 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6824 /// '@' prefixed parenthesized expression. The type of the expression will
6825 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6826 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6827 /// "const char *" or C structure with attribute 'objc_boxable'.
6828 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6829
6830 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6831 Expr *IndexExpr,
6832 ObjCMethodDecl *getterMethod,
6833 ObjCMethodDecl *setterMethod);
6834
6835 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6836 MutableArrayRef<ObjCDictionaryElement> Elements);
6837
6838 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6839 TypeSourceInfo *EncodedTypeInfo,
6840 SourceLocation RParenLoc);
6841 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6842 CXXConversionDecl *Method,
6843 bool HadMultipleCandidates);
6844
6845 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6846 SourceLocation EncodeLoc,
6847 SourceLocation LParenLoc,
6848 ParsedType Ty,
6849 SourceLocation RParenLoc);
6850
6851 /// ParseObjCSelectorExpression - Build selector expression for \@selector
6852 ExprResult ParseObjCSelectorExpression(Selector Sel,
6853 SourceLocation AtLoc,
6854 SourceLocation SelLoc,
6855 SourceLocation LParenLoc,
6856 SourceLocation RParenLoc,
6857 bool WarnMultipleSelectors);
6858
6859 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
6860 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
6861 SourceLocation AtLoc,
6862 SourceLocation ProtoLoc,
6863 SourceLocation LParenLoc,
6864 SourceLocation ProtoIdLoc,
6865 SourceLocation RParenLoc);
6866
6867 //===--------------------------------------------------------------------===//
6868 // C++ Declarations
6869 //
6870 Decl *ActOnStartLinkageSpecification(Scope *S,
6871 SourceLocation ExternLoc,
6872 Expr *LangStr,
6873 SourceLocation LBraceLoc);
6874 Decl *ActOnFinishLinkageSpecification(Scope *S,
6875 Decl *LinkageSpec,
6876 SourceLocation RBraceLoc);
6877
6878
6879 //===--------------------------------------------------------------------===//
6880 // C++ Classes
6881 //
6882 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
6883 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
6884 const CXXScopeSpec *SS = nullptr);
6885 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
6886
6887 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
6888 SourceLocation ColonLoc,
6889 const ParsedAttributesView &Attrs);
6890
6891 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
6892 Declarator &D,
6893 MultiTemplateParamsArg TemplateParameterLists,
6894 Expr *BitfieldWidth, const VirtSpecifiers &VS,
6895 InClassInitStyle InitStyle);
6896
6897 void ActOnStartCXXInClassMemberInitializer();
6898 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
6899 SourceLocation EqualLoc,
6900 Expr *Init);
6901
6902 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6903 Scope *S,
6904 CXXScopeSpec &SS,
6905 IdentifierInfo *MemberOrBase,
6906 ParsedType TemplateTypeTy,
6907 const DeclSpec &DS,
6908 SourceLocation IdLoc,
6909 SourceLocation LParenLoc,
6910 ArrayRef<Expr *> Args,
6911 SourceLocation RParenLoc,
6912 SourceLocation EllipsisLoc);
6913
6914 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6915 Scope *S,
6916 CXXScopeSpec &SS,
6917 IdentifierInfo *MemberOrBase,
6918 ParsedType TemplateTypeTy,
6919 const DeclSpec &DS,
6920 SourceLocation IdLoc,
6921 Expr *InitList,
6922 SourceLocation EllipsisLoc);
6923
6924 MemInitResult BuildMemInitializer(Decl *ConstructorD,
6925 Scope *S,
6926 CXXScopeSpec &SS,
6927 IdentifierInfo *MemberOrBase,
6928 ParsedType TemplateTypeTy,
6929 const DeclSpec &DS,
6930 SourceLocation IdLoc,
6931 Expr *Init,
6932 SourceLocation EllipsisLoc);
6933
6934 MemInitResult BuildMemberInitializer(ValueDecl *Member,
6935 Expr *Init,
6936 SourceLocation IdLoc);
6937
6938 MemInitResult BuildBaseInitializer(QualType BaseType,
6939 TypeSourceInfo *BaseTInfo,
6940 Expr *Init,
6941 CXXRecordDecl *ClassDecl,
6942 SourceLocation EllipsisLoc);
6943
6944 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
6945 Expr *Init,
6946 CXXRecordDecl *ClassDecl);
6947
6948 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6949 CXXCtorInitializer *Initializer);
6950
6951 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6952 ArrayRef<CXXCtorInitializer *> Initializers = None);
6953
6954 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
6955
6956
6957 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6958 /// mark all the non-trivial destructors of its members and bases as
6959 /// referenced.
6960 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6961 CXXRecordDecl *Record);
6962
6963 /// Mark destructors of virtual bases of this class referenced. In the Itanium
6964 /// C++ ABI, this is done when emitting a destructor for any non-abstract
6965 /// class. In the Microsoft C++ ABI, this is done any time a class's
6966 /// destructor is referenced.
6967 void MarkVirtualBaseDestructorsReferenced(
6968 SourceLocation Location, CXXRecordDecl *ClassDecl,
6969 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
6970
6971 /// Do semantic checks to allow the complete destructor variant to be emitted
6972 /// when the destructor is defined in another translation unit. In the Itanium
6973 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
6974 /// can be emitted in separate TUs. To emit the complete variant, run a subset
6975 /// of the checks performed when emitting a regular destructor.
6976 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
6977 CXXDestructorDecl *Dtor);
6978
6979 /// The list of classes whose vtables have been used within
6980 /// this translation unit, and the source locations at which the
6981 /// first use occurred.
6982 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
6983
6984 /// The list of vtables that are required but have not yet been
6985 /// materialized.
6986 SmallVector<VTableUse, 16> VTableUses;
6987
6988 /// The set of classes whose vtables have been used within
6989 /// this translation unit, and a bit that will be true if the vtable is
6990 /// required to be emitted (otherwise, it should be emitted only if needed
6991 /// by code generation).
6992 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6993
6994 /// Load any externally-stored vtable uses.
6995 void LoadExternalVTableUses();
6996
6997 /// Note that the vtable for the given class was used at the
6998 /// given location.
6999 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7000 bool DefinitionRequired = false);
7001
7002 /// Mark the exception specifications of all virtual member functions
7003 /// in the given class as needed.
7004 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
7005 const CXXRecordDecl *RD);
7006
7007 /// MarkVirtualMembersReferenced - Will mark all members of the given
7008 /// CXXRecordDecl referenced.
7009 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
7010 bool ConstexprOnly = false);
7011
7012 /// Define all of the vtables that have been used in this
7013 /// translation unit and reference any virtual members used by those
7014 /// vtables.
7015 ///
7016 /// \returns true if any work was done, false otherwise.
7017 bool DefineUsedVTables();
7018
7019 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
7020
7021 void ActOnMemInitializers(Decl *ConstructorDecl,
7022 SourceLocation ColonLoc,
7023 ArrayRef<CXXCtorInitializer*> MemInits,
7024 bool AnyErrors);
7025
7026 /// Check class-level dllimport/dllexport attribute. The caller must
7027 /// ensure that referenceDLLExportedClassMethods is called some point later
7028 /// when all outer classes of Class are complete.
7029 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
7030 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
7031
7032 void referenceDLLExportedClassMethods();
7033
7034 void propagateDLLAttrToBaseClassTemplate(
7035 CXXRecordDecl *Class, Attr *ClassAttr,
7036 ClassTemplateSpecializationDecl *BaseTemplateSpec,
7037 SourceLocation BaseLoc);
7038
7039 /// Add gsl::Pointer attribute to std::container::iterator
7040 /// \param ND The declaration that introduces the name
7041 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
7042 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
7043
7044 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
7045 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
7046
7047 /// Add [[gsl::Pointer]] attributes for std:: types.
7048 void inferGslPointerAttribute(TypedefNameDecl *TD);
7049
7050 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
7051
7052 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
7053 /// conditions that are needed for the attribute to have an effect.
7054 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7055
7056 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7057 Decl *TagDecl, SourceLocation LBrac,
7058 SourceLocation RBrac,
7059 const ParsedAttributesView &AttrList);
7060 void ActOnFinishCXXMemberDecls();
7061 void ActOnFinishCXXNonNestedClass();
7062
7063 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7064 unsigned ActOnReenterTemplateScope(Decl *Template,
7065 llvm::function_ref<Scope *()> EnterScope);
7066 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7067 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7068 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7069 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7070 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7071 void ActOnFinishDelayedMemberInitializers(Decl *Record);
7072 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7073 CachedTokens &Toks);
7074 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7075 bool IsInsideALocalClassWithinATemplateFunction();
7076
7077 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7078 Expr *AssertExpr,
7079 Expr *AssertMessageExpr,
7080 SourceLocation RParenLoc);
7081 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7082 Expr *AssertExpr,
7083 StringLiteral *AssertMessageExpr,
7084 SourceLocation RParenLoc,
7085 bool Failed);
7086
7087 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7088 SourceLocation FriendLoc,
7089 TypeSourceInfo *TSInfo);
7090 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7091 MultiTemplateParamsArg TemplateParams);
7092 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7093 MultiTemplateParamsArg TemplateParams);
7094
7095 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7096 StorageClass& SC);
7097 void CheckConstructor(CXXConstructorDecl *Constructor);
7098 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7099 StorageClass& SC);
7100 bool CheckDestructor(CXXDestructorDecl *Destructor);
7101 void CheckConversionDeclarator(Declarator &D, QualType &R,
7102 StorageClass& SC);
7103 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7104 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7105 StorageClass &SC);
7106 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7107
7108 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7109
7110 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7111 CXXSpecialMember CSM);
7112 void CheckDelayedMemberExceptionSpecs();
7113
7114 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7115 DefaultedComparisonKind DCK);
7116 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7117 FunctionDecl *Spaceship);
7118 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7119 DefaultedComparisonKind DCK);
7120
7121 //===--------------------------------------------------------------------===//
7122 // C++ Derived Classes
7123 //
7124
7125 /// ActOnBaseSpecifier - Parsed a base specifier
7126 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7127 SourceRange SpecifierRange,
7128 bool Virtual, AccessSpecifier Access,
7129 TypeSourceInfo *TInfo,
7130 SourceLocation EllipsisLoc);
7131
7132 BaseResult ActOnBaseSpecifier(Decl *classdecl,
7133 SourceRange SpecifierRange,
7134 ParsedAttributes &Attrs,
7135 bool Virtual, AccessSpecifier Access,
7136 ParsedType basetype,
7137 SourceLocation BaseLoc,
7138 SourceLocation EllipsisLoc);
7139
7140 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7141 MutableArrayRef<CXXBaseSpecifier *> Bases);
7142 void ActOnBaseSpecifiers(Decl *ClassDecl,
7143 MutableArrayRef<CXXBaseSpecifier *> Bases);
7144
7145 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7146 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7147 CXXBasePaths &Paths);
7148
7149 // FIXME: I don't like this name.
7150 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7151
7152 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7153 SourceLocation Loc, SourceRange Range,
7154 CXXCastPath *BasePath = nullptr,
7155 bool IgnoreAccess = false);
7156 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7157 unsigned InaccessibleBaseID,
7158 unsigned AmbiguousBaseConvID,
7159 SourceLocation Loc, SourceRange Range,
7160 DeclarationName Name,
7161 CXXCastPath *BasePath,
7162 bool IgnoreAccess = false);
7163
7164 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7165
7166 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7167 const CXXMethodDecl *Old);
7168
7169 /// CheckOverridingFunctionReturnType - Checks whether the return types are
7170 /// covariant, according to C++ [class.virtual]p5.
7171 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7172 const CXXMethodDecl *Old);
7173
7174 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7175 /// spec is a subset of base spec.
7176 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7177 const CXXMethodDecl *Old);
7178
7179 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7180
7181 /// CheckOverrideControl - Check C++11 override control semantics.
7182 void CheckOverrideControl(NamedDecl *D);
7183
7184 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7185 /// not used in the declaration of an overriding method.
7186 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7187
7188 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7189 /// overrides a virtual member function marked 'final', according to
7190 /// C++11 [class.virtual]p4.
7191 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7192 const CXXMethodDecl *Old);
7193
7194
7195 //===--------------------------------------------------------------------===//
7196 // C++ Access Control
7197 //
7198
7199 enum AccessResult {
7200 AR_accessible,
7201 AR_inaccessible,
7202 AR_dependent,
7203 AR_delayed
7204 };
7205
7206 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7207 NamedDecl *PrevMemberDecl,
7208 AccessSpecifier LexicalAS);
7209
7210 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7211 DeclAccessPair FoundDecl);
7212 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7213 DeclAccessPair FoundDecl);
7214 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7215 SourceRange PlacementRange,
7216 CXXRecordDecl *NamingClass,
7217 DeclAccessPair FoundDecl,
7218 bool Diagnose = true);
7219 AccessResult CheckConstructorAccess(SourceLocation Loc,
7220 CXXConstructorDecl *D,
7221 DeclAccessPair FoundDecl,
7222 const InitializedEntity &Entity,
7223 bool IsCopyBindingRefToTemp = false);
7224 AccessResult CheckConstructorAccess(SourceLocation Loc,
7225 CXXConstructorDecl *D,
7226 DeclAccessPair FoundDecl,
7227 const InitializedEntity &Entity,
7228 const PartialDiagnostic &PDiag);
7229 AccessResult CheckDestructorAccess(SourceLocation Loc,
7230 CXXDestructorDecl *Dtor,
7231 const PartialDiagnostic &PDiag,
7232 QualType objectType = QualType());
7233 AccessResult CheckFriendAccess(NamedDecl *D);
7234 AccessResult CheckMemberAccess(SourceLocation UseLoc,
7235 CXXRecordDecl *NamingClass,
7236 DeclAccessPair Found);
7237 AccessResult
7238 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7239 CXXRecordDecl *DecomposedClass,
7240 DeclAccessPair Field);
7241 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7242 Expr *ObjectExpr,
7243 Expr *ArgExpr,
7244 DeclAccessPair FoundDecl);
7245 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7246 DeclAccessPair FoundDecl);
7247 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7248 QualType Base, QualType Derived,
7249 const CXXBasePath &Path,
7250 unsigned DiagID,
7251 bool ForceCheck = false,
7252 bool ForceUnprivileged = false);
7253 void CheckLookupAccess(const LookupResult &R);
7254 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7255 QualType BaseType);
7256 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7257 DeclAccessPair Found, QualType ObjectType,
7258 SourceLocation Loc,
7259 const PartialDiagnostic &Diag);
7260 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7261 DeclAccessPair Found,
7262 QualType ObjectType) {
7263 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7264 SourceLocation(), PDiag());
7265 }
7266
7267 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7268 const MultiLevelTemplateArgumentList &TemplateArgs);
7269 void PerformDependentDiagnostics(const DeclContext *Pattern,
7270 const MultiLevelTemplateArgumentList &TemplateArgs);
7271
7272 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7273
7274 /// When true, access checking violations are treated as SFINAE
7275 /// failures rather than hard errors.
7276 bool AccessCheckingSFINAE;
7277
7278 enum AbstractDiagSelID {
7279 AbstractNone = -1,
7280 AbstractReturnType,
7281 AbstractParamType,
7282 AbstractVariableType,
7283 AbstractFieldType,
7284 AbstractIvarType,
7285 AbstractSynthesizedIvarType,
7286 AbstractArrayType
7287 };
7288
7289 bool isAbstractType(SourceLocation Loc, QualType T);
7290 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7291 TypeDiagnoser &Diagnoser);
7292 template <typename... Ts>
7293 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7294 const Ts &...Args) {
7295 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7296 return RequireNonAbstractType(Loc, T, Diagnoser);
7297 }
7298
7299 void DiagnoseAbstractType(const CXXRecordDecl *RD);
7300
7301 //===--------------------------------------------------------------------===//
7302 // C++ Overloaded Operators [C++ 13.5]
7303 //
7304
7305 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7306
7307 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7308
7309 //===--------------------------------------------------------------------===//
7310 // C++ Templates [C++ 14]
7311 //
7312 void FilterAcceptableTemplateNames(LookupResult &R,
7313 bool AllowFunctionTemplates = true,
7314 bool AllowDependent = true);
7315 bool hasAnyAcceptableTemplateNames(LookupResult &R,
7316 bool AllowFunctionTemplates = true,
7317 bool AllowDependent = true,
7318 bool AllowNonTemplateFunctions = false);
7319 /// Try to interpret the lookup result D as a template-name.
7320 ///
7321 /// \param D A declaration found by name lookup.
7322 /// \param AllowFunctionTemplates Whether function templates should be
7323 /// considered valid results.
7324 /// \param AllowDependent Whether unresolved using declarations (that might
7325 /// name templates) should be considered valid results.
7326 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
7327 bool AllowFunctionTemplates = true,
7328 bool AllowDependent = true);
7329
7330 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
7331 /// Whether and why a template name is required in this lookup.
7332 class RequiredTemplateKind {
7333 public:
7334 /// Template name is required if TemplateKWLoc is valid.
7335 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
7336 : TemplateKW(TemplateKWLoc) {}
7337 /// Template name is unconditionally required.
7338 RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {}
7339
7340 SourceLocation getTemplateKeywordLoc() const {
7341 return TemplateKW.getValueOr(SourceLocation());
7342 }
7343 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
7344 bool isRequired() const { return TemplateKW != SourceLocation(); }
7345 explicit operator bool() const { return isRequired(); }
7346
7347 private:
7348 llvm::Optional<SourceLocation> TemplateKW;
7349 };
7350
7351 enum class AssumedTemplateKind {
7352 /// This is not assumed to be a template name.
7353 None,
7354 /// This is assumed to be a template name because lookup found nothing.
7355 FoundNothing,
7356 /// This is assumed to be a template name because lookup found one or more
7357 /// functions (but no function templates).
7358 FoundFunctions,
7359 };
7360 bool LookupTemplateName(
7361 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
7362 bool EnteringContext, bool &MemberOfUnknownSpecialization,
7363 RequiredTemplateKind RequiredTemplate = SourceLocation(),
7364 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
7365
7366 TemplateNameKind isTemplateName(Scope *S,
7367 CXXScopeSpec &SS,
7368 bool hasTemplateKeyword,
7369 const UnqualifiedId &Name,
7370 ParsedType ObjectType,
7371 bool EnteringContext,
7372 TemplateTy &Template,
7373 bool &MemberOfUnknownSpecialization,
7374 bool Disambiguation = false);
7375
7376 /// Try to resolve an undeclared template name as a type template.
7377 ///
7378 /// Sets II to the identifier corresponding to the template name, and updates
7379 /// Name to a corresponding (typo-corrected) type template name and TNK to
7380 /// the corresponding kind, if possible.
7381 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
7382 TemplateNameKind &TNK,
7383 SourceLocation NameLoc,
7384 IdentifierInfo *&II);
7385
7386 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
7387 SourceLocation NameLoc,
7388 bool Diagnose = true);
7389
7390 /// Determine whether a particular identifier might be the name in a C++1z
7391 /// deduction-guide declaration.
7392 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
7393 SourceLocation NameLoc,
7394 ParsedTemplateTy *Template = nullptr);
7395
7396 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
7397 SourceLocation IILoc,
7398 Scope *S,
7399 const CXXScopeSpec *SS,
7400 TemplateTy &SuggestedTemplate,
7401 TemplateNameKind &SuggestedKind);
7402
7403 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
7404 NamedDecl *Instantiation,
7405 bool InstantiatedFromMember,
7406 const NamedDecl *Pattern,
7407 const NamedDecl *PatternDef,
7408 TemplateSpecializationKind TSK,
7409 bool Complain = true);
7410
7411 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
7412 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
7413
7414 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
7415 SourceLocation EllipsisLoc,
7416 SourceLocation KeyLoc,
7417 IdentifierInfo *ParamName,
7418 SourceLocation ParamNameLoc,
7419 unsigned Depth, unsigned Position,
7420 SourceLocation EqualLoc,
7421 ParsedType DefaultArg, bool HasTypeConstraint);
7422
7423 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
7424 TemplateIdAnnotation *TypeConstraint,
7425 TemplateTypeParmDecl *ConstrainedParameter,
7426 SourceLocation EllipsisLoc);
7427
7428 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
7429 DeclarationNameInfo NameInfo,
7430 ConceptDecl *NamedConcept,
7431 const TemplateArgumentListInfo *TemplateArgs,
7432 TemplateTypeParmDecl *ConstrainedParameter,
7433 SourceLocation EllipsisLoc);
7434
7435 bool AttachTypeConstraint(AutoTypeLoc TL,
7436 NonTypeTemplateParmDecl *ConstrainedParameter,
7437 SourceLocation EllipsisLoc);
7438
7439 bool RequireStructuralType(QualType T, SourceLocation Loc);
7440
7441 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
7442 SourceLocation Loc);
7443 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
7444
7445 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
7446 unsigned Depth,
7447 unsigned Position,
7448 SourceLocation EqualLoc,
7449 Expr *DefaultArg);
7450 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
7451 SourceLocation TmpLoc,
7452 TemplateParameterList *Params,
7453 SourceLocation EllipsisLoc,
7454 IdentifierInfo *ParamName,
7455 SourceLocation ParamNameLoc,
7456 unsigned Depth,
7457 unsigned Position,
7458 SourceLocation EqualLoc,
7459 ParsedTemplateArgument DefaultArg);
7460
7461 TemplateParameterList *
7462 ActOnTemplateParameterList(unsigned Depth,
7463 SourceLocation ExportLoc,
7464 SourceLocation TemplateLoc,
7465 SourceLocation LAngleLoc,
7466 ArrayRef<NamedDecl *> Params,
7467 SourceLocation RAngleLoc,
7468 Expr *RequiresClause);
7469
7470 /// The context in which we are checking a template parameter list.
7471 enum TemplateParamListContext {
7472 TPC_ClassTemplate,
7473 TPC_VarTemplate,
7474 TPC_FunctionTemplate,
7475 TPC_ClassTemplateMember,
7476 TPC_FriendClassTemplate,
7477 TPC_FriendFunctionTemplate,
7478 TPC_FriendFunctionTemplateDefinition,
7479 TPC_TypeAliasTemplate
7480 };
7481
7482 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7483 TemplateParameterList *OldParams,
7484 TemplateParamListContext TPC,
7485 SkipBodyInfo *SkipBody = nullptr);
7486 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7487 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7488 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7489 ArrayRef<TemplateParameterList *> ParamLists,
7490 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7491 bool SuppressDiagnostic = false);
7492
7493 DeclResult CheckClassTemplate(
7494 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7495 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7496 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7497 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7498 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7499 TemplateParameterList **OuterTemplateParamLists,
7500 SkipBodyInfo *SkipBody = nullptr);
7501
7502 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7503 QualType NTTPType,
7504 SourceLocation Loc);
7505
7506 /// Get a template argument mapping the given template parameter to itself,
7507 /// e.g. for X in \c template<int X>, this would return an expression template
7508 /// argument referencing X.
7509 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7510 SourceLocation Location);
7511
7512 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7513 TemplateArgumentListInfo &Out);
7514
7515 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7516
7517 void NoteAllFoundTemplates(TemplateName Name);
7518
7519 QualType CheckTemplateIdType(TemplateName Template,
7520 SourceLocation TemplateLoc,
7521 TemplateArgumentListInfo &TemplateArgs);
7522
7523 TypeResult
7524 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7525 TemplateTy Template, IdentifierInfo *TemplateII,
7526 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7527 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7528 bool IsCtorOrDtorName = false, bool IsClassName = false);
7529
7530 /// Parsed an elaborated-type-specifier that refers to a template-id,
7531 /// such as \c class T::template apply<U>.
7532 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7533 TypeSpecifierType TagSpec,
7534 SourceLocation TagLoc,
7535 CXXScopeSpec &SS,
7536 SourceLocation TemplateKWLoc,
7537 TemplateTy TemplateD,
7538 SourceLocation TemplateLoc,
7539 SourceLocation LAngleLoc,
7540 ASTTemplateArgsPtr TemplateArgsIn,
7541 SourceLocation RAngleLoc);
7542
7543 DeclResult ActOnVarTemplateSpecialization(
7544 Scope *S, Declarator &D, TypeSourceInfo *DI,
7545 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7546 StorageClass SC, bool IsPartialSpecialization);
7547
7548 /// Get the specialization of the given variable template corresponding to
7549 /// the specified argument list, or a null-but-valid result if the arguments
7550 /// are dependent.
7551 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7552 SourceLocation TemplateLoc,
7553 SourceLocation TemplateNameLoc,
7554 const TemplateArgumentListInfo &TemplateArgs);
7555
7556 /// Form a reference to the specialization of the given variable template
7557 /// corresponding to the specified argument list, or a null-but-valid result
7558 /// if the arguments are dependent.
7559 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7560 const DeclarationNameInfo &NameInfo,
7561 VarTemplateDecl *Template,
7562 SourceLocation TemplateLoc,
7563 const TemplateArgumentListInfo *TemplateArgs);
7564
7565 ExprResult
7566 CheckConceptTemplateId(const CXXScopeSpec &SS,
7567 SourceLocation TemplateKWLoc,
7568 const DeclarationNameInfo &ConceptNameInfo,
7569 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7570 const TemplateArgumentListInfo *TemplateArgs);
7571
7572 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7573
7574 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7575 SourceLocation TemplateKWLoc,
7576 LookupResult &R,
7577 bool RequiresADL,
7578 const TemplateArgumentListInfo *TemplateArgs);
7579
7580 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7581 SourceLocation TemplateKWLoc,
7582 const DeclarationNameInfo &NameInfo,
7583 const TemplateArgumentListInfo *TemplateArgs);
7584
7585 TemplateNameKind ActOnTemplateName(
7586 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7587 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7588 TemplateTy &Template, bool AllowInjectedClassName = false);
7589
7590 DeclResult ActOnClassTemplateSpecialization(
7591 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7592 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7593 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7594 MultiTemplateParamsArg TemplateParameterLists,
7595 SkipBodyInfo *SkipBody = nullptr);
7596
7597 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7598 TemplateDecl *PrimaryTemplate,
7599 unsigned NumExplicitArgs,
7600 ArrayRef<TemplateArgument> Args);
7601 void CheckTemplatePartialSpecialization(
7602 ClassTemplatePartialSpecializationDecl *Partial);
7603 void CheckTemplatePartialSpecialization(
7604 VarTemplatePartialSpecializationDecl *Partial);
7605
7606 Decl *ActOnTemplateDeclarator(Scope *S,
7607 MultiTemplateParamsArg TemplateParameterLists,
7608 Declarator &D);
7609
7610 bool
7611 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7612 TemplateSpecializationKind NewTSK,
7613 NamedDecl *PrevDecl,
7614 TemplateSpecializationKind PrevTSK,
7615 SourceLocation PrevPtOfInstantiation,
7616 bool &SuppressNew);
7617
7618 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7619 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7620 LookupResult &Previous);
7621
7622 bool CheckFunctionTemplateSpecialization(
7623 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7624 LookupResult &Previous, bool QualifiedFriend = false);
7625 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7626 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7627
7628 DeclResult ActOnExplicitInstantiation(
7629 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7630 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7631 TemplateTy Template, SourceLocation TemplateNameLoc,
7632 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7633 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7634
7635 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7636 SourceLocation TemplateLoc,
7637 unsigned TagSpec, SourceLocation KWLoc,
7638 CXXScopeSpec &SS, IdentifierInfo *Name,
7639 SourceLocation NameLoc,
7640 const ParsedAttributesView &Attr);
7641
7642 DeclResult ActOnExplicitInstantiation(Scope *S,
7643 SourceLocation ExternLoc,
7644 SourceLocation TemplateLoc,
7645 Declarator &D);
7646
7647 TemplateArgumentLoc
7648 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7649 SourceLocation TemplateLoc,
7650 SourceLocation RAngleLoc,
7651 Decl *Param,
7652 SmallVectorImpl<TemplateArgument>
7653 &Converted,
7654 bool &HasDefaultArg);
7655
7656 /// Specifies the context in which a particular template
7657 /// argument is being checked.
7658 enum CheckTemplateArgumentKind {
7659 /// The template argument was specified in the code or was
7660 /// instantiated with some deduced template arguments.
7661 CTAK_Specified,
7662
7663 /// The template argument was deduced via template argument
7664 /// deduction.
7665 CTAK_Deduced,
7666
7667 /// The template argument was deduced from an array bound
7668 /// via template argument deduction.
7669 CTAK_DeducedFromArrayBound
7670 };
7671
7672 bool CheckTemplateArgument(NamedDecl *Param,
7673 TemplateArgumentLoc &Arg,
7674 NamedDecl *Template,
7675 SourceLocation TemplateLoc,
7676 SourceLocation RAngleLoc,
7677 unsigned ArgumentPackIndex,
7678 SmallVectorImpl<TemplateArgument> &Converted,
7679 CheckTemplateArgumentKind CTAK = CTAK_Specified);
7680
7681 /// Check that the given template arguments can be be provided to
7682 /// the given template, converting the arguments along the way.
7683 ///
7684 /// \param Template The template to which the template arguments are being
7685 /// provided.
7686 ///
7687 /// \param TemplateLoc The location of the template name in the source.
7688 ///
7689 /// \param TemplateArgs The list of template arguments. If the template is
7690 /// a template template parameter, this function may extend the set of
7691 /// template arguments to also include substituted, defaulted template
7692 /// arguments.
7693 ///
7694 /// \param PartialTemplateArgs True if the list of template arguments is
7695 /// intentionally partial, e.g., because we're checking just the initial
7696 /// set of template arguments.
7697 ///
7698 /// \param Converted Will receive the converted, canonicalized template
7699 /// arguments.
7700 ///
7701 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
7702 /// contain the converted forms of the template arguments as written.
7703 /// Otherwise, \p TemplateArgs will not be modified.
7704 ///
7705 /// \param ConstraintsNotSatisfied If provided, and an error occured, will
7706 /// receive true if the cause for the error is the associated constraints of
7707 /// the template not being satisfied by the template arguments.
7708 ///
7709 /// \returns true if an error occurred, false otherwise.
7710 bool CheckTemplateArgumentList(TemplateDecl *Template,
7711 SourceLocation TemplateLoc,
7712 TemplateArgumentListInfo &TemplateArgs,
7713 bool PartialTemplateArgs,
7714 SmallVectorImpl<TemplateArgument> &Converted,
7715 bool UpdateArgsWithConversions = true,
7716 bool *ConstraintsNotSatisfied = nullptr);
7717
7718 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
7719 TemplateArgumentLoc &Arg,
7720 SmallVectorImpl<TemplateArgument> &Converted);
7721
7722 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
7723 TypeSourceInfo *Arg);
7724 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7725 QualType InstantiatedParamType, Expr *Arg,
7726 TemplateArgument &Converted,
7727 CheckTemplateArgumentKind CTAK = CTAK_Specified);
7728 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7729 TemplateParameterList *Params,
7730 TemplateArgumentLoc &Arg);
7731
7732 ExprResult
7733 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7734 QualType ParamType,
7735 SourceLocation Loc);
7736 ExprResult
7737 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7738 SourceLocation Loc);
7739
7740 /// Enumeration describing how template parameter lists are compared
7741 /// for equality.
7742 enum TemplateParameterListEqualKind {
7743 /// We are matching the template parameter lists of two templates
7744 /// that might be redeclarations.
7745 ///
7746 /// \code
7747 /// template<typename T> struct X;
7748 /// template<typename T> struct X;
7749 /// \endcode
7750 TPL_TemplateMatch,
7751
7752 /// We are matching the template parameter lists of two template
7753 /// template parameters as part of matching the template parameter lists
7754 /// of two templates that might be redeclarations.
7755 ///
7756 /// \code
7757 /// template<template<int I> class TT> struct X;
7758 /// template<template<int Value> class Other> struct X;
7759 /// \endcode
7760 TPL_TemplateTemplateParmMatch,
7761
7762 /// We are matching the template parameter lists of a template
7763 /// template argument against the template parameter lists of a template
7764 /// template parameter.
7765 ///
7766 /// \code
7767 /// template<template<int Value> class Metafun> struct X;
7768 /// template<int Value> struct integer_c;
7769 /// X<integer_c> xic;
7770 /// \endcode
7771 TPL_TemplateTemplateArgumentMatch
7772 };
7773
7774 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
7775 TemplateParameterList *Old,
7776 bool Complain,
7777 TemplateParameterListEqualKind Kind,
7778 SourceLocation TemplateArgLoc
7779 = SourceLocation());
7780
7781 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
7782
7783 /// Called when the parser has parsed a C++ typename
7784 /// specifier, e.g., "typename T::type".
7785 ///
7786 /// \param S The scope in which this typename type occurs.
7787 /// \param TypenameLoc the location of the 'typename' keyword
7788 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7789 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
7790 /// \param IdLoc the location of the identifier.
7791 TypeResult
7792 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7793 const CXXScopeSpec &SS, const IdentifierInfo &II,
7794 SourceLocation IdLoc);
7795
7796 /// Called when the parser has parsed a C++ typename
7797 /// specifier that ends in a template-id, e.g.,
7798 /// "typename MetaFun::template apply<T1, T2>".
7799 ///
7800 /// \param S The scope in which this typename type occurs.
7801 /// \param TypenameLoc the location of the 'typename' keyword
7802 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7803 /// \param TemplateLoc the location of the 'template' keyword, if any.
7804 /// \param TemplateName The template name.
7805 /// \param TemplateII The identifier used to name the template.
7806 /// \param TemplateIILoc The location of the template name.
7807 /// \param LAngleLoc The location of the opening angle bracket ('<').
7808 /// \param TemplateArgs The template arguments.
7809 /// \param RAngleLoc The location of the closing angle bracket ('>').
7810 TypeResult
7811 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7812 const CXXScopeSpec &SS,
7813 SourceLocation TemplateLoc,
7814 TemplateTy TemplateName,
7815 IdentifierInfo *TemplateII,
7816 SourceLocation TemplateIILoc,
7817 SourceLocation LAngleLoc,
7818 ASTTemplateArgsPtr TemplateArgs,
7819 SourceLocation RAngleLoc);
7820
7821 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7822 SourceLocation KeywordLoc,
7823 NestedNameSpecifierLoc QualifierLoc,
7824 const IdentifierInfo &II,
7825 SourceLocation IILoc,
7826 TypeSourceInfo **TSI,
7827 bool DeducedTSTContext);
7828
7829 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7830 SourceLocation KeywordLoc,
7831 NestedNameSpecifierLoc QualifierLoc,
7832 const IdentifierInfo &II,
7833 SourceLocation IILoc,
7834 bool DeducedTSTContext = true);
7835
7836
7837 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7838 SourceLocation Loc,
7839 DeclarationName Name);
7840 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
7841
7842 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
7843 bool RebuildTemplateParamsInCurrentInstantiation(
7844 TemplateParameterList *Params);
7845
7846 std::string
7847 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7848 const TemplateArgumentList &Args);
7849
7850 std::string
7851 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7852 const TemplateArgument *Args,
7853 unsigned NumArgs);
7854
7855 //===--------------------------------------------------------------------===//
7856 // C++ Concepts
7857 //===--------------------------------------------------------------------===//
7858 Decl *ActOnConceptDefinition(
7859 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
7860 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
7861
7862 RequiresExprBodyDecl *
7863 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
7864 ArrayRef<ParmVarDecl *> LocalParameters,
7865 Scope *BodyScope);
7866 void ActOnFinishRequiresExpr();
7867 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
7868 concepts::Requirement *ActOnTypeRequirement(
7869 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7870 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
7871 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
7872 SourceLocation NoexceptLoc);
7873 concepts::Requirement *
7874 ActOnCompoundRequirement(
7875 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7876 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
7877 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
7878 concepts::ExprRequirement *
7879 BuildExprRequirement(
7880 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
7881 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7882 concepts::ExprRequirement *
7883 BuildExprRequirement(
7884 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
7885 bool IsSatisfied, SourceLocation NoexceptLoc,
7886 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7887 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
7888 concepts::TypeRequirement *
7889 BuildTypeRequirement(
7890 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7891 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
7892 concepts::NestedRequirement *
7893 BuildNestedRequirement(
7894 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7895 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
7896 RequiresExprBodyDecl *Body,
7897 ArrayRef<ParmVarDecl *> LocalParameters,
7898 ArrayRef<concepts::Requirement *> Requirements,
7899 SourceLocation ClosingBraceLoc);
7900
7901 //===--------------------------------------------------------------------===//
7902 // C++ Variadic Templates (C++0x [temp.variadic])
7903 //===--------------------------------------------------------------------===//
7904
7905 /// Determine whether an unexpanded parameter pack might be permitted in this
7906 /// location. Useful for error recovery.
7907 bool isUnexpandedParameterPackPermitted();
7908
7909 /// The context in which an unexpanded parameter pack is
7910 /// being diagnosed.
7911 ///
7912 /// Note that the values of this enumeration line up with the first
7913 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
7914 enum UnexpandedParameterPackContext {
7915 /// An arbitrary expression.
7916 UPPC_Expression = 0,
7917
7918 /// The base type of a class type.
7919 UPPC_BaseType,
7920
7921 /// The type of an arbitrary declaration.
7922 UPPC_DeclarationType,
7923
7924 /// The type of a data member.
7925 UPPC_DataMemberType,
7926
7927 /// The size of a bit-field.
7928 UPPC_BitFieldWidth,
7929
7930 /// The expression in a static assertion.
7931 UPPC_StaticAssertExpression,
7932
7933 /// The fixed underlying type of an enumeration.
7934 UPPC_FixedUnderlyingType,
7935
7936 /// The enumerator value.
7937 UPPC_EnumeratorValue,
7938
7939 /// A using declaration.
7940 UPPC_UsingDeclaration,
7941
7942 /// A friend declaration.
7943 UPPC_FriendDeclaration,
7944
7945 /// A declaration qualifier.
7946 UPPC_DeclarationQualifier,
7947
7948 /// An initializer.
7949 UPPC_Initializer,
7950
7951 /// A default argument.
7952 UPPC_DefaultArgument,
7953
7954 /// The type of a non-type template parameter.
7955 UPPC_NonTypeTemplateParameterType,
7956
7957 /// The type of an exception.
7958 UPPC_ExceptionType,
7959
7960 /// Partial specialization.
7961 UPPC_PartialSpecialization,
7962
7963 /// Microsoft __if_exists.
7964 UPPC_IfExists,
7965
7966 /// Microsoft __if_not_exists.
7967 UPPC_IfNotExists,
7968
7969 /// Lambda expression.
7970 UPPC_Lambda,
7971
7972 /// Block expression.
7973 UPPC_Block,
7974
7975 /// A type constraint.
7976 UPPC_TypeConstraint,
7977
7978 // A requirement in a requires-expression.
7979 UPPC_Requirement,
7980
7981 // A requires-clause.
7982 UPPC_RequiresClause,
7983 };
7984
7985 /// Diagnose unexpanded parameter packs.
7986 ///
7987 /// \param Loc The location at which we should emit the diagnostic.
7988 ///
7989 /// \param UPPC The context in which we are diagnosing unexpanded
7990 /// parameter packs.
7991 ///
7992 /// \param Unexpanded the set of unexpanded parameter packs.
7993 ///
7994 /// \returns true if an error occurred, false otherwise.
7995 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
7996 UnexpandedParameterPackContext UPPC,
7997 ArrayRef<UnexpandedParameterPack> Unexpanded);
7998
7999 /// If the given type contains an unexpanded parameter pack,
8000 /// diagnose the error.
8001 ///
8002 /// \param Loc The source location where a diagnostc should be emitted.
8003 ///
8004 /// \param T The type that is being checked for unexpanded parameter
8005 /// packs.
8006 ///
8007 /// \returns true if an error occurred, false otherwise.
8008 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
8009 UnexpandedParameterPackContext UPPC);
8010
8011 /// If the given expression contains an unexpanded parameter
8012 /// pack, diagnose the error.
8013 ///
8014 /// \param E The expression that is being checked for unexpanded
8015 /// parameter packs.
8016 ///
8017 /// \returns true if an error occurred, false otherwise.
8018 bool DiagnoseUnexpandedParameterPack(Expr *E,
8019 UnexpandedParameterPackContext UPPC = UPPC_Expression);
8020
8021 /// If the given requirees-expression contains an unexpanded reference to one
8022 /// of its own parameter packs, diagnose the error.
8023 ///
8024 /// \param RE The requiress-expression that is being checked for unexpanded
8025 /// parameter packs.
8026 ///
8027 /// \returns true if an error occurred, false otherwise.
8028 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
8029
8030 /// If the given nested-name-specifier contains an unexpanded
8031 /// parameter pack, diagnose the error.
8032 ///
8033 /// \param SS The nested-name-specifier that is being checked for
8034 /// unexpanded parameter packs.
8035 ///
8036 /// \returns true if an error occurred, false otherwise.
8037 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
8038 UnexpandedParameterPackContext UPPC);
8039
8040 /// If the given name contains an unexpanded parameter pack,
8041 /// diagnose the error.
8042 ///
8043 /// \param NameInfo The name (with source location information) that
8044 /// is being checked for unexpanded parameter packs.
8045 ///
8046 /// \returns true if an error occurred, false otherwise.
8047 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
8048 UnexpandedParameterPackContext UPPC);
8049
8050 /// If the given template name contains an unexpanded parameter pack,
8051 /// diagnose the error.
8052 ///
8053 /// \param Loc The location of the template name.
8054 ///
8055 /// \param Template The template name that is being checked for unexpanded
8056 /// parameter packs.
8057 ///
8058 /// \returns true if an error occurred, false otherwise.
8059 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8060 TemplateName Template,
8061 UnexpandedParameterPackContext UPPC);
8062
8063 /// If the given template argument contains an unexpanded parameter
8064 /// pack, diagnose the error.
8065 ///
8066 /// \param Arg The template argument that is being checked for unexpanded
8067 /// parameter packs.
8068 ///
8069 /// \returns true if an error occurred, false otherwise.
8070 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8071 UnexpandedParameterPackContext UPPC);
8072
8073 /// Collect the set of unexpanded parameter packs within the given
8074 /// template argument.
8075 ///
8076 /// \param Arg The template argument that will be traversed to find
8077 /// unexpanded parameter packs.
8078 void collectUnexpandedParameterPacks(TemplateArgument Arg,
8079 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8080
8081 /// Collect the set of unexpanded parameter packs within the given
8082 /// template argument.
8083 ///
8084 /// \param Arg The template argument that will be traversed to find
8085 /// unexpanded parameter packs.
8086 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8087 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8088
8089 /// Collect the set of unexpanded parameter packs within the given
8090 /// type.
8091 ///
8092 /// \param T The type that will be traversed to find
8093 /// unexpanded parameter packs.
8094 void collectUnexpandedParameterPacks(QualType T,
8095 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8096
8097 /// Collect the set of unexpanded parameter packs within the given
8098 /// type.
8099 ///
8100 /// \param TL The type that will be traversed to find
8101 /// unexpanded parameter packs.
8102 void collectUnexpandedParameterPacks(TypeLoc TL,
8103 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8104
8105 /// Collect the set of unexpanded parameter packs within the given
8106 /// nested-name-specifier.
8107 ///
8108 /// \param NNS The nested-name-specifier that will be traversed to find
8109 /// unexpanded parameter packs.
8110 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8111 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8112
8113 /// Collect the set of unexpanded parameter packs within the given
8114 /// name.
8115 ///
8116 /// \param NameInfo The name that will be traversed to find
8117 /// unexpanded parameter packs.
8118 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8119 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8120
8121 /// Invoked when parsing a template argument followed by an
8122 /// ellipsis, which creates a pack expansion.
8123 ///
8124 /// \param Arg The template argument preceding the ellipsis, which
8125 /// may already be invalid.
8126 ///
8127 /// \param EllipsisLoc The location of the ellipsis.
8128 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8129 SourceLocation EllipsisLoc);
8130
8131 /// Invoked when parsing a type followed by an ellipsis, which
8132 /// creates a pack expansion.
8133 ///
8134 /// \param Type The type preceding the ellipsis, which will become
8135 /// the pattern of the pack expansion.
8136 ///
8137 /// \param EllipsisLoc The location of the ellipsis.
8138 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8139
8140 /// Construct a pack expansion type from the pattern of the pack
8141 /// expansion.
8142 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8143 SourceLocation EllipsisLoc,
8144 Optional<unsigned> NumExpansions);
8145
8146 /// Construct a pack expansion type from the pattern of the pack
8147 /// expansion.
8148 QualType CheckPackExpansion(QualType Pattern,
8149 SourceRange PatternRange,
8150 SourceLocation EllipsisLoc,
8151 Optional<unsigned> NumExpansions);
8152
8153 /// Invoked when parsing an expression followed by an ellipsis, which
8154 /// creates a pack expansion.
8155 ///
8156 /// \param Pattern The expression preceding the ellipsis, which will become
8157 /// the pattern of the pack expansion.
8158 ///
8159 /// \param EllipsisLoc The location of the ellipsis.
8160 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8161
8162 /// Invoked when parsing an expression followed by an ellipsis, which
8163 /// creates a pack expansion.
8164 ///
8165 /// \param Pattern The expression preceding the ellipsis, which will become
8166 /// the pattern of the pack expansion.
8167 ///
8168 /// \param EllipsisLoc The location of the ellipsis.
8169 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8170 Optional<unsigned> NumExpansions);
8171
8172 /// Determine whether we could expand a pack expansion with the
8173 /// given set of parameter packs into separate arguments by repeatedly
8174 /// transforming the pattern.
8175 ///
8176 /// \param EllipsisLoc The location of the ellipsis that identifies the
8177 /// pack expansion.
8178 ///
8179 /// \param PatternRange The source range that covers the entire pattern of
8180 /// the pack expansion.
8181 ///
8182 /// \param Unexpanded The set of unexpanded parameter packs within the
8183 /// pattern.
8184 ///
8185 /// \param ShouldExpand Will be set to \c true if the transformer should
8186 /// expand the corresponding pack expansions into separate arguments. When
8187 /// set, \c NumExpansions must also be set.
8188 ///
8189 /// \param RetainExpansion Whether the caller should add an unexpanded
8190 /// pack expansion after all of the expanded arguments. This is used
8191 /// when extending explicitly-specified template argument packs per
8192 /// C++0x [temp.arg.explicit]p9.
8193 ///
8194 /// \param NumExpansions The number of separate arguments that will be in
8195 /// the expanded form of the corresponding pack expansion. This is both an
8196 /// input and an output parameter, which can be set by the caller if the
8197 /// number of expansions is known a priori (e.g., due to a prior substitution)
8198 /// and will be set by the callee when the number of expansions is known.
8199 /// The callee must set this value when \c ShouldExpand is \c true; it may
8200 /// set this value in other cases.
8201 ///
8202 /// \returns true if an error occurred (e.g., because the parameter packs
8203 /// are to be instantiated with arguments of different lengths), false
8204 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8205 /// must be set.
8206 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
8207 SourceRange PatternRange,
8208 ArrayRef<UnexpandedParameterPack> Unexpanded,
8209 const MultiLevelTemplateArgumentList &TemplateArgs,
8210 bool &ShouldExpand,
8211 bool &RetainExpansion,
8212 Optional<unsigned> &NumExpansions);
8213
8214 /// Determine the number of arguments in the given pack expansion
8215 /// type.
8216 ///
8217 /// This routine assumes that the number of arguments in the expansion is
8218 /// consistent across all of the unexpanded parameter packs in its pattern.
8219 ///
8220 /// Returns an empty Optional if the type can't be expanded.
8221 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
8222 const MultiLevelTemplateArgumentList &TemplateArgs);
8223
8224 /// Determine whether the given declarator contains any unexpanded
8225 /// parameter packs.
8226 ///
8227 /// This routine is used by the parser to disambiguate function declarators
8228 /// with an ellipsis prior to the ')', e.g.,
8229 ///
8230 /// \code
8231 /// void f(T...);
8232 /// \endcode
8233 ///
8234 /// To determine whether we have an (unnamed) function parameter pack or
8235 /// a variadic function.
8236 ///
8237 /// \returns true if the declarator contains any unexpanded parameter packs,
8238 /// false otherwise.
8239 bool containsUnexpandedParameterPacks(Declarator &D);
8240
8241 /// Returns the pattern of the pack expansion for a template argument.
8242 ///
8243 /// \param OrigLoc The template argument to expand.
8244 ///
8245 /// \param Ellipsis Will be set to the location of the ellipsis.
8246 ///
8247 /// \param NumExpansions Will be set to the number of expansions that will
8248 /// be generated from this pack expansion, if known a priori.
8249 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8250 TemplateArgumentLoc OrigLoc,
8251 SourceLocation &Ellipsis,
8252 Optional<unsigned> &NumExpansions) const;
8253
8254 /// Given a template argument that contains an unexpanded parameter pack, but
8255 /// which has already been substituted, attempt to determine the number of
8256 /// elements that will be produced once this argument is fully-expanded.
8257 ///
8258 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8259 /// avoid actually expanding the pack where possible.
8260 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8261
8262 //===--------------------------------------------------------------------===//
8263 // C++ Template Argument Deduction (C++ [temp.deduct])
8264 //===--------------------------------------------------------------------===//
8265
8266 /// Adjust the type \p ArgFunctionType to match the calling convention,
8267 /// noreturn, and optionally the exception specification of \p FunctionType.
8268 /// Deduction often wants to ignore these properties when matching function
8269 /// types.
8270 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8271 bool AdjustExceptionSpec = false);
8272
8273 /// Describes the result of template argument deduction.
8274 ///
8275 /// The TemplateDeductionResult enumeration describes the result of
8276 /// template argument deduction, as returned from
8277 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8278 /// structure provides additional information about the results of
8279 /// template argument deduction, e.g., the deduced template argument
8280 /// list (if successful) or the specific template parameters or
8281 /// deduced arguments that were involved in the failure.
8282 enum TemplateDeductionResult {
8283 /// Template argument deduction was successful.
8284 TDK_Success = 0,
8285 /// The declaration was invalid; do nothing.
8286 TDK_Invalid,
8287 /// Template argument deduction exceeded the maximum template
8288 /// instantiation depth (which has already been diagnosed).
8289 TDK_InstantiationDepth,
8290 /// Template argument deduction did not deduce a value
8291 /// for every template parameter.
8292 TDK_Incomplete,
8293 /// Template argument deduction did not deduce a value for every
8294 /// expansion of an expanded template parameter pack.
8295 TDK_IncompletePack,
8296 /// Template argument deduction produced inconsistent
8297 /// deduced values for the given template parameter.
8298 TDK_Inconsistent,
8299 /// Template argument deduction failed due to inconsistent
8300 /// cv-qualifiers on a template parameter type that would
8301 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
8302 /// but were given a non-const "X".
8303 TDK_Underqualified,
8304 /// Substitution of the deduced template argument values
8305 /// resulted in an error.
8306 TDK_SubstitutionFailure,
8307 /// After substituting deduced template arguments, a dependent
8308 /// parameter type did not match the corresponding argument.
8309 TDK_DeducedMismatch,
8310 /// After substituting deduced template arguments, an element of
8311 /// a dependent parameter type did not match the corresponding element
8312 /// of the corresponding argument (when deducing from an initializer list).
8313 TDK_DeducedMismatchNested,
8314 /// A non-depnedent component of the parameter did not match the
8315 /// corresponding component of the argument.
8316 TDK_NonDeducedMismatch,
8317 /// When performing template argument deduction for a function
8318 /// template, there were too many call arguments.
8319 TDK_TooManyArguments,
8320 /// When performing template argument deduction for a function
8321 /// template, there were too few call arguments.
8322 TDK_TooFewArguments,
8323 /// The explicitly-specified template arguments were not valid
8324 /// template arguments for the given template.
8325 TDK_InvalidExplicitArguments,
8326 /// Checking non-dependent argument conversions failed.
8327 TDK_NonDependentConversionFailure,
8328 /// The deduced arguments did not satisfy the constraints associated
8329 /// with the template.
8330 TDK_ConstraintsNotSatisfied,
8331 /// Deduction failed; that's all we know.
8332 TDK_MiscellaneousDeductionFailure,
8333 /// CUDA Target attributes do not match.
8334 TDK_CUDATargetMismatch
8335 };
8336
8337 TemplateDeductionResult
8338 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
8339 const TemplateArgumentList &TemplateArgs,
8340 sema::TemplateDeductionInfo &Info);
8341
8342 TemplateDeductionResult
8343 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
8344 const TemplateArgumentList &TemplateArgs,
8345 sema::TemplateDeductionInfo &Info);
8346
8347 TemplateDeductionResult SubstituteExplicitTemplateArguments(
8348 FunctionTemplateDecl *FunctionTemplate,
8349 TemplateArgumentListInfo &ExplicitTemplateArgs,
8350 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8351 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
8352 sema::TemplateDeductionInfo &Info);
8353
8354 /// brief A function argument from which we performed template argument
8355 // deduction for a call.
8356 struct OriginalCallArg {
8357 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
8358 unsigned ArgIdx, QualType OriginalArgType)
8359 : OriginalParamType(OriginalParamType),
8360 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
8361 OriginalArgType(OriginalArgType) {}
8362
8363 QualType OriginalParamType;
8364 bool DecomposedParam;
8365 unsigned ArgIdx;
8366 QualType OriginalArgType;
8367 };
8368
8369 TemplateDeductionResult FinishTemplateArgumentDeduction(
8370 FunctionTemplateDecl *FunctionTemplate,
8371 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8372 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
8373 sema::TemplateDeductionInfo &Info,
8374 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
8375 bool PartialOverloading = false,
8376 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
8377
8378 TemplateDeductionResult DeduceTemplateArguments(
8379 FunctionTemplateDecl *FunctionTemplate,
8380 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8381 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
8382 bool PartialOverloading,
8383 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
8384
8385 TemplateDeductionResult
8386 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8387 TemplateArgumentListInfo *ExplicitTemplateArgs,
8388 QualType ArgFunctionType,
8389 FunctionDecl *&Specialization,
8390 sema::TemplateDeductionInfo &Info,
8391 bool IsAddressOfFunction = false);
8392
8393 TemplateDeductionResult
8394 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8395 QualType ToType,
8396 CXXConversionDecl *&Specialization,
8397 sema::TemplateDeductionInfo &Info);
8398
8399 TemplateDeductionResult
8400 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8401 TemplateArgumentListInfo *ExplicitTemplateArgs,
8402 FunctionDecl *&Specialization,
8403 sema::TemplateDeductionInfo &Info,
8404 bool IsAddressOfFunction = false);
8405
8406 /// Substitute Replacement for \p auto in \p TypeWithAuto
8407 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
8408 /// Substitute Replacement for auto in TypeWithAuto
8409 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8410 QualType Replacement);
8411 /// Completely replace the \c auto in \p TypeWithAuto by
8412 /// \p Replacement. This does not retain any \c auto type sugar.
8413 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
8414 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8415 QualType Replacement);
8416
8417 /// Result type of DeduceAutoType.
8418 enum DeduceAutoResult {
8419 DAR_Succeeded,
8420 DAR_Failed,
8421 DAR_FailedAlreadyDiagnosed
8422 };
8423
8424 DeduceAutoResult
8425 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
8426 Optional<unsigned> DependentDeductionDepth = None,
8427 bool IgnoreConstraints = false);
8428 DeduceAutoResult
8429 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
8430 Optional<unsigned> DependentDeductionDepth = None,
8431 bool IgnoreConstraints = false);
8432 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
8433 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
8434 bool Diagnose = true);
8435
8436 /// Declare implicit deduction guides for a class template if we've
8437 /// not already done so.
8438 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
8439 SourceLocation Loc);
8440
8441 QualType DeduceTemplateSpecializationFromInitializer(
8442 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8443 const InitializationKind &Kind, MultiExprArg Init);
8444
8445 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
8446 QualType Type, TypeSourceInfo *TSI,
8447 SourceRange Range, bool DirectInit,
8448 Expr *Init);
8449
8450 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
8451
8452 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
8453 SourceLocation ReturnLoc,
8454 Expr *&RetExpr, AutoType *AT);
8455
8456 FunctionTemplateDecl *getMoreSpecializedTemplate(
8457 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
8458 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
8459 unsigned NumCallArguments2, bool Reversed = false);
8460 UnresolvedSetIterator
8461 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
8462 TemplateSpecCandidateSet &FailedCandidates,
8463 SourceLocation Loc,
8464 const PartialDiagnostic &NoneDiag,
8465 const PartialDiagnostic &AmbigDiag,
8466 const PartialDiagnostic &CandidateDiag,
8467 bool Complain = true, QualType TargetType = QualType());
8468
8469 ClassTemplatePartialSpecializationDecl *
8470 getMoreSpecializedPartialSpecialization(
8471 ClassTemplatePartialSpecializationDecl *PS1,
8472 ClassTemplatePartialSpecializationDecl *PS2,
8473 SourceLocation Loc);
8474
8475 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
8476 sema::TemplateDeductionInfo &Info);
8477
8478 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
8479 VarTemplatePartialSpecializationDecl *PS1,
8480 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
8481
8482 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
8483 sema::TemplateDeductionInfo &Info);
8484
8485 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
8486 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
8487
8488 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
8489 unsigned Depth, llvm::SmallBitVector &Used);
8490
8491 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
8492 bool OnlyDeduced,
8493 unsigned Depth,
8494 llvm::SmallBitVector &Used);
8495 void MarkDeducedTemplateParameters(
8496 const FunctionTemplateDecl *FunctionTemplate,
8497 llvm::SmallBitVector &Deduced) {
8498 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8499 }
8500 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8501 const FunctionTemplateDecl *FunctionTemplate,
8502 llvm::SmallBitVector &Deduced);
8503
8504 //===--------------------------------------------------------------------===//
8505 // C++ Template Instantiation
8506 //
8507
8508 MultiLevelTemplateArgumentList
8509 getTemplateInstantiationArgs(NamedDecl *D,
8510 const TemplateArgumentList *Innermost = nullptr,
8511 bool RelativeToPrimary = false,
8512 const FunctionDecl *Pattern = nullptr);
8513
8514 /// A context in which code is being synthesized (where a source location
8515 /// alone is not sufficient to identify the context). This covers template
8516 /// instantiation and various forms of implicitly-generated functions.
8517 struct CodeSynthesisContext {
8518 /// The kind of template instantiation we are performing
8519 enum SynthesisKind {
8520 /// We are instantiating a template declaration. The entity is
8521 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8522 TemplateInstantiation,
8523
8524 /// We are instantiating a default argument for a template
8525 /// parameter. The Entity is the template parameter whose argument is
8526 /// being instantiated, the Template is the template, and the
8527 /// TemplateArgs/NumTemplateArguments provide the template arguments as
8528 /// specified.
8529 DefaultTemplateArgumentInstantiation,
8530
8531 /// We are instantiating a default argument for a function.
8532 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8533 /// provides the template arguments as specified.
8534 DefaultFunctionArgumentInstantiation,
8535
8536 /// We are substituting explicit template arguments provided for
8537 /// a function template. The entity is a FunctionTemplateDecl.
8538 ExplicitTemplateArgumentSubstitution,
8539
8540 /// We are substituting template argument determined as part of
8541 /// template argument deduction for either a class template
8542 /// partial specialization or a function template. The
8543 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8544 /// a TemplateDecl.
8545 DeducedTemplateArgumentSubstitution,
8546
8547 /// We are substituting prior template arguments into a new
8548 /// template parameter. The template parameter itself is either a
8549 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8550 PriorTemplateArgumentSubstitution,
8551
8552 /// We are checking the validity of a default template argument that
8553 /// has been used when naming a template-id.
8554 DefaultTemplateArgumentChecking,
8555
8556 /// We are computing the exception specification for a defaulted special
8557 /// member function.
8558 ExceptionSpecEvaluation,
8559
8560 /// We are instantiating the exception specification for a function
8561 /// template which was deferred until it was needed.
8562 ExceptionSpecInstantiation,
8563
8564 /// We are instantiating a requirement of a requires expression.
8565 RequirementInstantiation,
8566
8567 /// We are checking the satisfaction of a nested requirement of a requires
8568 /// expression.
8569 NestedRequirementConstraintsCheck,
8570
8571 /// We are declaring an implicit special member function.
8572 DeclaringSpecialMember,
8573
8574 /// We are declaring an implicit 'operator==' for a defaulted
8575 /// 'operator<=>'.
8576 DeclaringImplicitEqualityComparison,
8577
8578 /// We are defining a synthesized function (such as a defaulted special
8579 /// member).
8580 DefiningSynthesizedFunction,
8581
8582 // We are checking the constraints associated with a constrained entity or
8583 // the constraint expression of a concept. This includes the checks that
8584 // atomic constraints have the type 'bool' and that they can be constant
8585 // evaluated.
8586 ConstraintsCheck,
8587
8588 // We are substituting template arguments into a constraint expression.
8589 ConstraintSubstitution,
8590
8591 // We are normalizing a constraint expression.
8592 ConstraintNormalization,
8593
8594 // We are substituting into the parameter mapping of an atomic constraint
8595 // during normalization.
8596 ParameterMappingSubstitution,
8597
8598 /// We are rewriting a comparison operator in terms of an operator<=>.
8599 RewritingOperatorAsSpaceship,
8600
8601 /// We are initializing a structured binding.
8602 InitializingStructuredBinding,
8603
8604 /// We are marking a class as __dllexport.
8605 MarkingClassDllexported,
8606
8607 /// Added for Template instantiation observation.
8608 /// Memoization means we are _not_ instantiating a template because
8609 /// it is already instantiated (but we entered a context where we
8610 /// would have had to if it was not already instantiated).
8611 Memoization
8612 } Kind;
8613
8614 /// Was the enclosing context a non-instantiation SFINAE context?
8615 bool SavedInNonInstantiationSFINAEContext;
8616
8617 /// The point of instantiation or synthesis within the source code.
8618 SourceLocation PointOfInstantiation;
8619
8620 /// The entity that is being synthesized.
8621 Decl *Entity;
8622
8623 /// The template (or partial specialization) in which we are
8624 /// performing the instantiation, for substitutions of prior template
8625 /// arguments.
8626 NamedDecl *Template;
8627
8628 /// The list of template arguments we are substituting, if they
8629 /// are not part of the entity.
8630 const TemplateArgument *TemplateArgs;
8631
8632 // FIXME: Wrap this union around more members, or perhaps store the
8633 // kind-specific members in the RAII object owning the context.
8634 union {
8635 /// The number of template arguments in TemplateArgs.
8636 unsigned NumTemplateArgs;
8637
8638 /// The special member being declared or defined.
8639 CXXSpecialMember SpecialMember;
8640 };
8641
8642 ArrayRef<TemplateArgument> template_arguments() const {
8643 assert(Kind != DeclaringSpecialMember)((Kind != DeclaringSpecialMember) ? static_cast<void> (
0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 8643, __PRETTY_FUNCTION__))
;
8644 return {TemplateArgs, NumTemplateArgs};
8645 }
8646
8647 /// The template deduction info object associated with the
8648 /// substitution or checking of explicit or deduced template arguments.
8649 sema::TemplateDeductionInfo *DeductionInfo;
8650
8651 /// The source range that covers the construct that cause
8652 /// the instantiation, e.g., the template-id that causes a class
8653 /// template instantiation.
8654 SourceRange InstantiationRange;
8655
8656 CodeSynthesisContext()
8657 : Kind(TemplateInstantiation),
8658 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8659 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8660 DeductionInfo(nullptr) {}
8661
8662 /// Determines whether this template is an actual instantiation
8663 /// that should be counted toward the maximum instantiation depth.
8664 bool isInstantiationRecord() const;
8665 };
8666
8667 /// List of active code synthesis contexts.
8668 ///
8669 /// This vector is treated as a stack. As synthesis of one entity requires
8670 /// synthesis of another, additional contexts are pushed onto the stack.
8671 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8672
8673 /// Specializations whose definitions are currently being instantiated.
8674 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8675
8676 /// Non-dependent types used in templates that have already been instantiated
8677 /// by some template instantiation.
8678 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8679
8680 /// Extra modules inspected when performing a lookup during a template
8681 /// instantiation. Computed lazily.
8682 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8683
8684 /// Cache of additional modules that should be used for name lookup
8685 /// within the current template instantiation. Computed lazily; use
8686 /// getLookupModules() to get a complete set.
8687 llvm::DenseSet<Module*> LookupModulesCache;
8688
8689 /// Get the set of additional modules that should be checked during
8690 /// name lookup. A module and its imports become visible when instanting a
8691 /// template defined within it.
8692 llvm::DenseSet<Module*> &getLookupModules();
8693
8694 /// Map from the most recent declaration of a namespace to the most
8695 /// recent visible declaration of that namespace.
8696 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
8697
8698 /// Whether we are in a SFINAE context that is not associated with
8699 /// template instantiation.
8700 ///
8701 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
8702 /// of a template instantiation or template argument deduction.
8703 bool InNonInstantiationSFINAEContext;
8704
8705 /// The number of \p CodeSynthesisContexts that are not template
8706 /// instantiations and, therefore, should not be counted as part of the
8707 /// instantiation depth.
8708 ///
8709 /// When the instantiation depth reaches the user-configurable limit
8710 /// \p LangOptions::InstantiationDepth we will abort instantiation.
8711 // FIXME: Should we have a similar limit for other forms of synthesis?
8712 unsigned NonInstantiationEntries;
8713
8714 /// The depth of the context stack at the point when the most recent
8715 /// error or warning was produced.
8716 ///
8717 /// This value is used to suppress printing of redundant context stacks
8718 /// when there are multiple errors or warnings in the same instantiation.
8719 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
8720 unsigned LastEmittedCodeSynthesisContextDepth = 0;
8721
8722 /// The template instantiation callbacks to trace or track
8723 /// instantiations (objects can be chained).
8724 ///
8725 /// This callbacks is used to print, trace or track template
8726 /// instantiations as they are being constructed.
8727 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
8728 TemplateInstCallbacks;
8729
8730 /// The current index into pack expansion arguments that will be
8731 /// used for substitution of parameter packs.
8732 ///
8733 /// The pack expansion index will be -1 to indicate that parameter packs
8734 /// should be instantiated as themselves. Otherwise, the index specifies
8735 /// which argument within the parameter pack will be used for substitution.
8736 int ArgumentPackSubstitutionIndex;
8737
8738 /// RAII object used to change the argument pack substitution index
8739 /// within a \c Sema object.
8740 ///
8741 /// See \c ArgumentPackSubstitutionIndex for more information.
8742 class ArgumentPackSubstitutionIndexRAII {
8743 Sema &Self;
8744 int OldSubstitutionIndex;
8745
8746 public:
8747 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
8748 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
8749 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
8750 }
8751
8752 ~ArgumentPackSubstitutionIndexRAII() {
8753 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
8754 }
8755 };
8756
8757 friend class ArgumentPackSubstitutionRAII;
8758
8759 /// For each declaration that involved template argument deduction, the
8760 /// set of diagnostics that were suppressed during that template argument
8761 /// deduction.
8762 ///
8763 /// FIXME: Serialize this structure to the AST file.
8764 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
8765 SuppressedDiagnosticsMap;
8766 SuppressedDiagnosticsMap SuppressedDiagnostics;
8767
8768 /// A stack object to be created when performing template
8769 /// instantiation.
8770 ///
8771 /// Construction of an object of type \c InstantiatingTemplate
8772 /// pushes the current instantiation onto the stack of active
8773 /// instantiations. If the size of this stack exceeds the maximum
8774 /// number of recursive template instantiations, construction
8775 /// produces an error and evaluates true.
8776 ///
8777 /// Destruction of this object will pop the named instantiation off
8778 /// the stack.
8779 struct InstantiatingTemplate {
8780 /// Note that we are instantiating a class template,
8781 /// function template, variable template, alias template,
8782 /// or a member thereof.
8783 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8784 Decl *Entity,
8785 SourceRange InstantiationRange = SourceRange());
8786
8787 struct ExceptionSpecification {};
8788 /// Note that we are instantiating an exception specification
8789 /// of a function template.
8790 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8791 FunctionDecl *Entity, ExceptionSpecification,
8792 SourceRange InstantiationRange = SourceRange());
8793
8794 /// Note that we are instantiating a default argument in a
8795 /// template-id.
8796 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8797 TemplateParameter Param, TemplateDecl *Template,
8798 ArrayRef<TemplateArgument> TemplateArgs,
8799 SourceRange InstantiationRange = SourceRange());
8800
8801 /// Note that we are substituting either explicitly-specified or
8802 /// deduced template arguments during function template argument deduction.
8803 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8804 FunctionTemplateDecl *FunctionTemplate,
8805 ArrayRef<TemplateArgument> TemplateArgs,
8806 CodeSynthesisContext::SynthesisKind Kind,
8807 sema::TemplateDeductionInfo &DeductionInfo,
8808 SourceRange InstantiationRange = SourceRange());
8809
8810 /// Note that we are instantiating as part of template
8811 /// argument deduction for a class template declaration.
8812 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8813 TemplateDecl *Template,
8814 ArrayRef<TemplateArgument> TemplateArgs,
8815 sema::TemplateDeductionInfo &DeductionInfo,
8816 SourceRange InstantiationRange = SourceRange());
8817
8818 /// Note that we are instantiating as part of template
8819 /// argument deduction for a class template partial
8820 /// specialization.
8821 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8822 ClassTemplatePartialSpecializationDecl *PartialSpec,
8823 ArrayRef<TemplateArgument> TemplateArgs,
8824 sema::TemplateDeductionInfo &DeductionInfo,
8825 SourceRange InstantiationRange = SourceRange());
8826
8827 /// Note that we are instantiating as part of template
8828 /// argument deduction for a variable template partial
8829 /// specialization.
8830 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8831 VarTemplatePartialSpecializationDecl *PartialSpec,
8832 ArrayRef<TemplateArgument> TemplateArgs,
8833 sema::TemplateDeductionInfo &DeductionInfo,
8834 SourceRange InstantiationRange = SourceRange());
8835
8836 /// Note that we are instantiating a default argument for a function
8837 /// parameter.
8838 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8839 ParmVarDecl *Param,
8840 ArrayRef<TemplateArgument> TemplateArgs,
8841 SourceRange InstantiationRange = SourceRange());
8842
8843 /// Note that we are substituting prior template arguments into a
8844 /// non-type parameter.
8845 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8846 NamedDecl *Template,
8847 NonTypeTemplateParmDecl *Param,
8848 ArrayRef<TemplateArgument> TemplateArgs,
8849 SourceRange InstantiationRange);
8850
8851 /// Note that we are substituting prior template arguments into a
8852 /// template template parameter.
8853 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8854 NamedDecl *Template,
8855 TemplateTemplateParmDecl *Param,
8856 ArrayRef<TemplateArgument> TemplateArgs,
8857 SourceRange InstantiationRange);
8858
8859 /// Note that we are checking the default template argument
8860 /// against the template parameter for a given template-id.
8861 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8862 TemplateDecl *Template,
8863 NamedDecl *Param,
8864 ArrayRef<TemplateArgument> TemplateArgs,
8865 SourceRange InstantiationRange);
8866
8867 struct ConstraintsCheck {};
8868 /// \brief Note that we are checking the constraints associated with some
8869 /// constrained entity (a concept declaration or a template with associated
8870 /// constraints).
8871 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8872 ConstraintsCheck, NamedDecl *Template,
8873 ArrayRef<TemplateArgument> TemplateArgs,
8874 SourceRange InstantiationRange);
8875
8876 struct ConstraintSubstitution {};
8877 /// \brief Note that we are checking a constraint expression associated
8878 /// with a template declaration or as part of the satisfaction check of a
8879 /// concept.
8880 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8881 ConstraintSubstitution, NamedDecl *Template,
8882 sema::TemplateDeductionInfo &DeductionInfo,
8883 SourceRange InstantiationRange);
8884
8885 struct ConstraintNormalization {};
8886 /// \brief Note that we are normalizing a constraint expression.
8887 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8888 ConstraintNormalization, NamedDecl *Template,
8889 SourceRange InstantiationRange);
8890
8891 struct ParameterMappingSubstitution {};
8892 /// \brief Note that we are subtituting into the parameter mapping of an
8893 /// atomic constraint during constraint normalization.
8894 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8895 ParameterMappingSubstitution, NamedDecl *Template,
8896 SourceRange InstantiationRange);
8897
8898 /// \brief Note that we are substituting template arguments into a part of
8899 /// a requirement of a requires expression.
8900 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8901 concepts::Requirement *Req,
8902 sema::TemplateDeductionInfo &DeductionInfo,
8903 SourceRange InstantiationRange = SourceRange());
8904
8905 /// \brief Note that we are checking the satisfaction of the constraint
8906 /// expression inside of a nested requirement.
8907 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8908 concepts::NestedRequirement *Req, ConstraintsCheck,
8909 SourceRange InstantiationRange = SourceRange());
8910
8911 /// Note that we have finished instantiating this template.
8912 void Clear();
8913
8914 ~InstantiatingTemplate() { Clear(); }
8915
8916 /// Determines whether we have exceeded the maximum
8917 /// recursive template instantiations.
8918 bool isInvalid() const { return Invalid; }
8919
8920 /// Determine whether we are already instantiating this
8921 /// specialization in some surrounding active instantiation.
8922 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
8923
8924 private:
8925 Sema &SemaRef;
8926 bool Invalid;
8927 bool AlreadyInstantiating;
8928 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
8929 SourceRange InstantiationRange);
8930
8931 InstantiatingTemplate(
8932 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
8933 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
8934 Decl *Entity, NamedDecl *Template = nullptr,
8935 ArrayRef<TemplateArgument> TemplateArgs = None,
8936 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
8937
8938 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
8939
8940 InstantiatingTemplate&
8941 operator=(const InstantiatingTemplate&) = delete;
8942 };
8943
8944 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
8945 void popCodeSynthesisContext();
8946
8947 /// Determine whether we are currently performing template instantiation.
8948 bool inTemplateInstantiation() const {
8949 return CodeSynthesisContexts.size() > NonInstantiationEntries;
8950 }
8951
8952 void PrintContextStack() {
8953 if (!CodeSynthesisContexts.empty() &&
8954 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
8955 PrintInstantiationStack();
8956 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
8957 }
8958 if (PragmaAttributeCurrentTargetDecl)
8959 PrintPragmaAttributeInstantiationPoint();
8960 }
8961 void PrintInstantiationStack();
8962
8963 void PrintPragmaAttributeInstantiationPoint();
8964
8965 /// Determines whether we are currently in a context where
8966 /// template argument substitution failures are not considered
8967 /// errors.
8968 ///
8969 /// \returns An empty \c Optional if we're not in a SFINAE context.
8970 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
8971 /// template-deduction context object, which can be used to capture
8972 /// diagnostics that will be suppressed.
8973 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
8974
8975 /// Determines whether we are currently in a context that
8976 /// is not evaluated as per C++ [expr] p5.
8977 bool isUnevaluatedContext() const {
8978 assert(!ExprEvalContexts.empty() &&((!ExprEvalContexts.empty() && "Must be in an expression evaluation context"
) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 8979, __PRETTY_FUNCTION__))
8979 "Must be in an expression evaluation context")((!ExprEvalContexts.empty() && "Must be in an expression evaluation context"
) ? static_cast<void> (0) : __assert_fail ("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 8979, __PRETTY_FUNCTION__))
;
8980 return ExprEvalContexts.back().isUnevaluated();
8981 }
8982
8983 /// RAII class used to determine whether SFINAE has
8984 /// trapped any errors that occur during template argument
8985 /// deduction.
8986 class SFINAETrap {
8987 Sema &SemaRef;
8988 unsigned PrevSFINAEErrors;
8989 bool PrevInNonInstantiationSFINAEContext;
8990 bool PrevAccessCheckingSFINAE;
8991 bool PrevLastDiagnosticIgnored;
8992
8993 public:
8994 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
8995 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
8996 PrevInNonInstantiationSFINAEContext(
8997 SemaRef.InNonInstantiationSFINAEContext),
8998 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
8999 PrevLastDiagnosticIgnored(
9000 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
9001 {
9002 if (!SemaRef.isSFINAEContext())
9003 SemaRef.InNonInstantiationSFINAEContext = true;
9004 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
9005 }
9006
9007 ~SFINAETrap() {
9008 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
9009 SemaRef.InNonInstantiationSFINAEContext
9010 = PrevInNonInstantiationSFINAEContext;
9011 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
9012 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
9013 PrevLastDiagnosticIgnored);
9014 }
9015
9016 /// Determine whether any SFINAE errors have been trapped.
9017 bool hasErrorOccurred() const {
9018 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
9019 }
9020 };
9021
9022 /// RAII class used to indicate that we are performing provisional
9023 /// semantic analysis to determine the validity of a construct, so
9024 /// typo-correction and diagnostics in the immediate context (not within
9025 /// implicitly-instantiated templates) should be suppressed.
9026 class TentativeAnalysisScope {
9027 Sema &SemaRef;
9028 // FIXME: Using a SFINAETrap for this is a hack.
9029 SFINAETrap Trap;
9030 bool PrevDisableTypoCorrection;
9031 public:
9032 explicit TentativeAnalysisScope(Sema &SemaRef)
9033 : SemaRef(SemaRef), Trap(SemaRef, true),
9034 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
9035 SemaRef.DisableTypoCorrection = true;
9036 }
9037 ~TentativeAnalysisScope() {
9038 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
9039 }
9040 };
9041
9042 /// The current instantiation scope used to store local
9043 /// variables.
9044 LocalInstantiationScope *CurrentInstantiationScope;
9045
9046 /// Tracks whether we are in a context where typo correction is
9047 /// disabled.
9048 bool DisableTypoCorrection;
9049
9050 /// The number of typos corrected by CorrectTypo.
9051 unsigned TyposCorrected;
9052
9053 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9054 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9055
9056 /// A cache containing identifiers for which typo correction failed and
9057 /// their locations, so that repeated attempts to correct an identifier in a
9058 /// given location are ignored if typo correction already failed for it.
9059 IdentifierSourceLocations TypoCorrectionFailures;
9060
9061 /// Worker object for performing CFG-based warnings.
9062 sema::AnalysisBasedWarnings AnalysisWarnings;
9063 threadSafety::BeforeSet *ThreadSafetyDeclCache;
9064
9065 /// An entity for which implicit template instantiation is required.
9066 ///
9067 /// The source location associated with the declaration is the first place in
9068 /// the source code where the declaration was "used". It is not necessarily
9069 /// the point of instantiation (which will be either before or after the
9070 /// namespace-scope declaration that triggered this implicit instantiation),
9071 /// However, it is the location that diagnostics should generally refer to,
9072 /// because users will need to know what code triggered the instantiation.
9073 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9074
9075 /// The queue of implicit template instantiations that are required
9076 /// but have not yet been performed.
9077 std::deque<PendingImplicitInstantiation> PendingInstantiations;
9078
9079 /// Queue of implicit template instantiations that cannot be performed
9080 /// eagerly.
9081 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9082
9083 class GlobalEagerInstantiationScope {
9084 public:
9085 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9086 : S(S), Enabled(Enabled) {
9087 if (!Enabled) return;
9088
9089 SavedPendingInstantiations.swap(S.PendingInstantiations);
9090 SavedVTableUses.swap(S.VTableUses);
9091 }
9092
9093 void perform() {
9094 if (Enabled) {
9095 S.DefineUsedVTables();
9096 S.PerformPendingInstantiations();
9097 }
9098 }
9099
9100 ~GlobalEagerInstantiationScope() {
9101 if (!Enabled) return;
9102
9103 // Restore the set of pending vtables.
9104 assert(S.VTableUses.empty() &&((S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 9105, __PRETTY_FUNCTION__))
9105 "VTableUses should be empty before it is discarded.")((S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 9105, __PRETTY_FUNCTION__))
;
9106 S.VTableUses.swap(SavedVTableUses);
9107
9108 // Restore the set of pending implicit instantiations.
9109 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9110 assert(S.PendingInstantiations.empty() &&((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 9111, __PRETTY_FUNCTION__))
9111 "PendingInstantiations should be empty before it is discarded.")((S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."
) ? static_cast<void> (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 9111, __PRETTY_FUNCTION__))
;
9112 S.PendingInstantiations.swap(SavedPendingInstantiations);
9113 } else {
9114 // Template instantiations in the PCH may be delayed until the TU.
9115 S.PendingInstantiations.swap(SavedPendingInstantiations);
9116 S.PendingInstantiations.insert(S.PendingInstantiations.end(),
9117 SavedPendingInstantiations.begin(),
9118 SavedPendingInstantiations.end());
9119 }
9120 }
9121
9122 private:
9123 Sema &S;
9124 SmallVector<VTableUse, 16> SavedVTableUses;
9125 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
9126 bool Enabled;
9127 };
9128
9129 /// The queue of implicit template instantiations that are required
9130 /// and must be performed within the current local scope.
9131 ///
9132 /// This queue is only used for member functions of local classes in
9133 /// templates, which must be instantiated in the same scope as their
9134 /// enclosing function, so that they can reference function-local
9135 /// types, static variables, enumerators, etc.
9136 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
9137
9138 class LocalEagerInstantiationScope {
9139 public:
9140 LocalEagerInstantiationScope(Sema &S) : S(S) {
9141 SavedPendingLocalImplicitInstantiations.swap(
9142 S.PendingLocalImplicitInstantiations);
9143 }
9144
9145 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
9146
9147 ~LocalEagerInstantiationScope() {
9148 assert(S.PendingLocalImplicitInstantiations.empty() &&((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"
) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 9149, __PRETTY_FUNCTION__))
9149 "there shouldn't be any pending local implicit instantiations")((S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"
) ? static_cast<void> (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 9149, __PRETTY_FUNCTION__))
;
9150 SavedPendingLocalImplicitInstantiations.swap(
9151 S.PendingLocalImplicitInstantiations);
9152 }
9153
9154 private:
9155 Sema &S;
9156 std::deque<PendingImplicitInstantiation>
9157 SavedPendingLocalImplicitInstantiations;
9158 };
9159
9160 /// A helper class for building up ExtParameterInfos.
9161 class ExtParameterInfoBuilder {
9162 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
9163 bool HasInteresting = false;
9164
9165 public:
9166 /// Set the ExtParameterInfo for the parameter at the given index,
9167 ///
9168 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
9169 assert(Infos.size() <= index)((Infos.size() <= index) ? static_cast<void> (0) : __assert_fail
("Infos.size() <= index", "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 9169, __PRETTY_FUNCTION__))
;
9170 Infos.resize(index);
9171 Infos.push_back(info);
9172
9173 if (!HasInteresting)
9174 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
9175 }
9176
9177 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
9178 /// ExtParameterInfo array we've built up.
9179 const FunctionProtoType::ExtParameterInfo *
9180 getPointerOrNull(unsigned numParams) {
9181 if (!HasInteresting) return nullptr;
9182 Infos.resize(numParams);
9183 return Infos.data();
9184 }
9185 };
9186
9187 void PerformPendingInstantiations(bool LocalOnly = false);
9188
9189 TypeSourceInfo *SubstType(TypeSourceInfo *T,
9190 const MultiLevelTemplateArgumentList &TemplateArgs,
9191 SourceLocation Loc, DeclarationName Entity,
9192 bool AllowDeducedTST = false);
9193
9194 QualType SubstType(QualType T,
9195 const MultiLevelTemplateArgumentList &TemplateArgs,
9196 SourceLocation Loc, DeclarationName Entity);
9197
9198 TypeSourceInfo *SubstType(TypeLoc TL,
9199 const MultiLevelTemplateArgumentList &TemplateArgs,
9200 SourceLocation Loc, DeclarationName Entity);
9201
9202 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
9203 const MultiLevelTemplateArgumentList &TemplateArgs,
9204 SourceLocation Loc,
9205 DeclarationName Entity,
9206 CXXRecordDecl *ThisContext,
9207 Qualifiers ThisTypeQuals);
9208 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
9209 const MultiLevelTemplateArgumentList &Args);
9210 bool SubstExceptionSpec(SourceLocation Loc,
9211 FunctionProtoType::ExceptionSpecInfo &ESI,
9212 SmallVectorImpl<QualType> &ExceptionStorage,
9213 const MultiLevelTemplateArgumentList &Args);
9214 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
9215 const MultiLevelTemplateArgumentList &TemplateArgs,
9216 int indexAdjustment,
9217 Optional<unsigned> NumExpansions,
9218 bool ExpectParameterPack);
9219 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
9220 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
9221 const MultiLevelTemplateArgumentList &TemplateArgs,
9222 SmallVectorImpl<QualType> &ParamTypes,
9223 SmallVectorImpl<ParmVarDecl *> *OutParams,
9224 ExtParameterInfoBuilder &ParamInfos);
9225 ExprResult SubstExpr(Expr *E,
9226 const MultiLevelTemplateArgumentList &TemplateArgs);
9227
9228 /// Substitute the given template arguments into a list of
9229 /// expressions, expanding pack expansions if required.
9230 ///
9231 /// \param Exprs The list of expressions to substitute into.
9232 ///
9233 /// \param IsCall Whether this is some form of call, in which case
9234 /// default arguments will be dropped.
9235 ///
9236 /// \param TemplateArgs The set of template arguments to substitute.
9237 ///
9238 /// \param Outputs Will receive all of the substituted arguments.
9239 ///
9240 /// \returns true if an error occurred, false otherwise.
9241 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
9242 const MultiLevelTemplateArgumentList &TemplateArgs,
9243 SmallVectorImpl<Expr *> &Outputs);
9244
9245 StmtResult SubstStmt(Stmt *S,
9246 const MultiLevelTemplateArgumentList &TemplateArgs);
9247
9248 TemplateParameterList *
9249 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
9250 const MultiLevelTemplateArgumentList &TemplateArgs);
9251
9252 bool
9253 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
9254 const MultiLevelTemplateArgumentList &TemplateArgs,
9255 TemplateArgumentListInfo &Outputs);
9256
9257
9258 Decl *SubstDecl(Decl *D, DeclContext *Owner,
9259 const MultiLevelTemplateArgumentList &TemplateArgs);
9260
9261 /// Substitute the name and return type of a defaulted 'operator<=>' to form
9262 /// an implicit 'operator=='.
9263 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
9264 FunctionDecl *Spaceship);
9265
9266 ExprResult SubstInitializer(Expr *E,
9267 const MultiLevelTemplateArgumentList &TemplateArgs,
9268 bool CXXDirectInit);
9269
9270 bool
9271 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
9272 CXXRecordDecl *Pattern,
9273 const MultiLevelTemplateArgumentList &TemplateArgs);
9274
9275 bool
9276 InstantiateClass(SourceLocation PointOfInstantiation,
9277 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
9278 const MultiLevelTemplateArgumentList &TemplateArgs,
9279 TemplateSpecializationKind TSK,
9280 bool Complain = true);
9281
9282 bool InstantiateEnum(SourceLocation PointOfInstantiation,
9283 EnumDecl *Instantiation, EnumDecl *Pattern,
9284 const MultiLevelTemplateArgumentList &TemplateArgs,
9285 TemplateSpecializationKind TSK);
9286
9287 bool InstantiateInClassInitializer(
9288 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
9289 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
9290
9291 struct LateInstantiatedAttribute {
9292 const Attr *TmplAttr;
9293 LocalInstantiationScope *Scope;
9294 Decl *NewDecl;
9295
9296 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
9297 Decl *D)
9298 : TmplAttr(A), Scope(S), NewDecl(D)
9299 { }
9300 };
9301 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
9302
9303 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
9304 const Decl *Pattern, Decl *Inst,
9305 LateInstantiatedAttrVec *LateAttrs = nullptr,
9306 LocalInstantiationScope *OuterMostScope = nullptr);
9307
9308 void
9309 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
9310 const Decl *Pattern, Decl *Inst,
9311 LateInstantiatedAttrVec *LateAttrs = nullptr,
9312 LocalInstantiationScope *OuterMostScope = nullptr);
9313
9314 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
9315
9316 bool usesPartialOrExplicitSpecialization(
9317 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
9318
9319 bool
9320 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
9321 ClassTemplateSpecializationDecl *ClassTemplateSpec,
9322 TemplateSpecializationKind TSK,
9323 bool Complain = true);
9324
9325 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
9326 CXXRecordDecl *Instantiation,
9327 const MultiLevelTemplateArgumentList &TemplateArgs,
9328 TemplateSpecializationKind TSK);
9329
9330 void InstantiateClassTemplateSpecializationMembers(
9331 SourceLocation PointOfInstantiation,
9332 ClassTemplateSpecializationDecl *ClassTemplateSpec,
9333 TemplateSpecializationKind TSK);
9334
9335 NestedNameSpecifierLoc
9336 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
9337 const MultiLevelTemplateArgumentList &TemplateArgs);
9338
9339 DeclarationNameInfo
9340 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
9341 const MultiLevelTemplateArgumentList &TemplateArgs);
9342 TemplateName
9343 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
9344 SourceLocation Loc,
9345 const MultiLevelTemplateArgumentList &TemplateArgs);
9346 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
9347 TemplateArgumentListInfo &Result,
9348 const MultiLevelTemplateArgumentList &TemplateArgs);
9349
9350 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
9351 ParmVarDecl *Param);
9352 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
9353 FunctionDecl *Function);
9354 bool CheckInstantiatedFunctionTemplateConstraints(
9355 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
9356 ArrayRef<TemplateArgument> TemplateArgs,
9357 ConstraintSatisfaction &Satisfaction);
9358 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
9359 const TemplateArgumentList *Args,
9360 SourceLocation Loc);
9361 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
9362 FunctionDecl *Function,
9363 bool Recursive = false,
9364 bool DefinitionRequired = false,
9365 bool AtEndOfTU = false);
9366 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
9367 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
9368 const TemplateArgumentList &TemplateArgList,
9369 const TemplateArgumentListInfo &TemplateArgsInfo,
9370 SmallVectorImpl<TemplateArgument> &Converted,
9371 SourceLocation PointOfInstantiation,
9372 LateInstantiatedAttrVec *LateAttrs = nullptr,
9373 LocalInstantiationScope *StartingScope = nullptr);
9374 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
9375 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
9376 const MultiLevelTemplateArgumentList &TemplateArgs);
9377 void
9378 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
9379 const MultiLevelTemplateArgumentList &TemplateArgs,
9380 LateInstantiatedAttrVec *LateAttrs,
9381 DeclContext *Owner,
9382 LocalInstantiationScope *StartingScope,
9383 bool InstantiatingVarTemplate = false,
9384 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
9385
9386 void InstantiateVariableInitializer(
9387 VarDecl *Var, VarDecl *OldVar,
9388 const MultiLevelTemplateArgumentList &TemplateArgs);
9389 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
9390 VarDecl *Var, bool Recursive = false,
9391 bool DefinitionRequired = false,
9392 bool AtEndOfTU = false);
9393
9394 void InstantiateMemInitializers(CXXConstructorDecl *New,
9395 const CXXConstructorDecl *Tmpl,
9396 const MultiLevelTemplateArgumentList &TemplateArgs);
9397
9398 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
9399 const MultiLevelTemplateArgumentList &TemplateArgs,
9400 bool FindingInstantiatedContext = false);
9401 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
9402 const MultiLevelTemplateArgumentList &TemplateArgs);
9403
9404 // Objective-C declarations.
9405 enum ObjCContainerKind {
9406 OCK_None = -1,
9407 OCK_Interface = 0,
9408 OCK_Protocol,
9409 OCK_Category,
9410 OCK_ClassExtension,
9411 OCK_Implementation,
9412 OCK_CategoryImplementation
9413 };
9414 ObjCContainerKind getObjCContainerKind() const;
9415
9416 DeclResult actOnObjCTypeParam(Scope *S,
9417 ObjCTypeParamVariance variance,
9418 SourceLocation varianceLoc,
9419 unsigned index,
9420 IdentifierInfo *paramName,
9421 SourceLocation paramLoc,
9422 SourceLocation colonLoc,
9423 ParsedType typeBound);
9424
9425 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
9426 ArrayRef<Decl *> typeParams,
9427 SourceLocation rAngleLoc);
9428 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
9429
9430 Decl *ActOnStartClassInterface(
9431 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9432 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9433 IdentifierInfo *SuperName, SourceLocation SuperLoc,
9434 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
9435 Decl *const *ProtoRefs, unsigned NumProtoRefs,
9436 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9437 const ParsedAttributesView &AttrList);
9438
9439 void ActOnSuperClassOfClassInterface(Scope *S,
9440 SourceLocation AtInterfaceLoc,
9441 ObjCInterfaceDecl *IDecl,
9442 IdentifierInfo *ClassName,
9443 SourceLocation ClassLoc,
9444 IdentifierInfo *SuperName,
9445 SourceLocation SuperLoc,
9446 ArrayRef<ParsedType> SuperTypeArgs,
9447 SourceRange SuperTypeArgsRange);
9448
9449 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
9450 SmallVectorImpl<SourceLocation> &ProtocolLocs,
9451 IdentifierInfo *SuperName,
9452 SourceLocation SuperLoc);
9453
9454 Decl *ActOnCompatibilityAlias(
9455 SourceLocation AtCompatibilityAliasLoc,
9456 IdentifierInfo *AliasName, SourceLocation AliasLocation,
9457 IdentifierInfo *ClassName, SourceLocation ClassLocation);
9458
9459 bool CheckForwardProtocolDeclarationForCircularDependency(
9460 IdentifierInfo *PName,
9461 SourceLocation &PLoc, SourceLocation PrevLoc,
9462 const ObjCList<ObjCProtocolDecl> &PList);
9463
9464 Decl *ActOnStartProtocolInterface(
9465 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
9466 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
9467 unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
9468 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
9469
9470 Decl *ActOnStartCategoryInterface(
9471 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9472 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9473 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
9474 Decl *const *ProtoRefs, unsigned NumProtoRefs,
9475 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9476 const ParsedAttributesView &AttrList);
9477
9478 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
9479 IdentifierInfo *ClassName,
9480 SourceLocation ClassLoc,
9481 IdentifierInfo *SuperClassname,
9482 SourceLocation SuperClassLoc,
9483 const ParsedAttributesView &AttrList);
9484
9485 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
9486 IdentifierInfo *ClassName,
9487 SourceLocation ClassLoc,
9488 IdentifierInfo *CatName,
9489 SourceLocation CatLoc,
9490 const ParsedAttributesView &AttrList);
9491
9492 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
9493 ArrayRef<Decl *> Decls);
9494
9495 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
9496 IdentifierInfo **IdentList,
9497 SourceLocation *IdentLocs,
9498 ArrayRef<ObjCTypeParamList *> TypeParamLists,
9499 unsigned NumElts);
9500
9501 DeclGroupPtrTy
9502 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
9503 ArrayRef<IdentifierLocPair> IdentList,
9504 const ParsedAttributesView &attrList);
9505
9506 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
9507 ArrayRef<IdentifierLocPair> ProtocolId,
9508 SmallVectorImpl<Decl *> &Protocols);
9509
9510 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
9511 SourceLocation ProtocolLoc,
9512 IdentifierInfo *TypeArgId,
9513 SourceLocation TypeArgLoc,
9514 bool SelectProtocolFirst = false);
9515
9516 /// Given a list of identifiers (and their locations), resolve the
9517 /// names to either Objective-C protocol qualifiers or type
9518 /// arguments, as appropriate.
9519 void actOnObjCTypeArgsOrProtocolQualifiers(
9520 Scope *S,
9521 ParsedType baseType,
9522 SourceLocation lAngleLoc,
9523 ArrayRef<IdentifierInfo *> identifiers,
9524 ArrayRef<SourceLocation> identifierLocs,
9525 SourceLocation rAngleLoc,
9526 SourceLocation &typeArgsLAngleLoc,
9527 SmallVectorImpl<ParsedType> &typeArgs,
9528 SourceLocation &typeArgsRAngleLoc,
9529 SourceLocation &protocolLAngleLoc,
9530 SmallVectorImpl<Decl *> &protocols,
9531 SourceLocation &protocolRAngleLoc,
9532 bool warnOnIncompleteProtocols);
9533
9534 /// Build a an Objective-C protocol-qualified 'id' type where no
9535 /// base type was specified.
9536 TypeResult actOnObjCProtocolQualifierType(
9537 SourceLocation lAngleLoc,
9538 ArrayRef<Decl *> protocols,
9539 ArrayRef<SourceLocation> protocolLocs,
9540 SourceLocation rAngleLoc);
9541
9542 /// Build a specialized and/or protocol-qualified Objective-C type.
9543 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9544 Scope *S,
9545 SourceLocation Loc,
9546 ParsedType BaseType,
9547 SourceLocation TypeArgsLAngleLoc,
9548 ArrayRef<ParsedType> TypeArgs,
9549 SourceLocation TypeArgsRAngleLoc,
9550 SourceLocation ProtocolLAngleLoc,
9551 ArrayRef<Decl *> Protocols,
9552 ArrayRef<SourceLocation> ProtocolLocs,
9553 SourceLocation ProtocolRAngleLoc);
9554
9555 /// Build an Objective-C type parameter type.
9556 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9557 SourceLocation ProtocolLAngleLoc,
9558 ArrayRef<ObjCProtocolDecl *> Protocols,
9559 ArrayRef<SourceLocation> ProtocolLocs,
9560 SourceLocation ProtocolRAngleLoc,
9561 bool FailOnError = false);
9562
9563 /// Build an Objective-C object pointer type.
9564 QualType BuildObjCObjectType(QualType BaseType,
9565 SourceLocation Loc,
9566 SourceLocation TypeArgsLAngleLoc,
9567 ArrayRef<TypeSourceInfo *> TypeArgs,
9568 SourceLocation TypeArgsRAngleLoc,
9569 SourceLocation ProtocolLAngleLoc,
9570 ArrayRef<ObjCProtocolDecl *> Protocols,
9571 ArrayRef<SourceLocation> ProtocolLocs,
9572 SourceLocation ProtocolRAngleLoc,
9573 bool FailOnError = false);
9574
9575 /// Ensure attributes are consistent with type.
9576 /// \param [in, out] Attributes The attributes to check; they will
9577 /// be modified to be consistent with \p PropertyTy.
9578 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9579 SourceLocation Loc,
9580 unsigned &Attributes,
9581 bool propertyInPrimaryClass);
9582
9583 /// Process the specified property declaration and create decls for the
9584 /// setters and getters as needed.
9585 /// \param property The property declaration being processed
9586 void ProcessPropertyDecl(ObjCPropertyDecl *property);
9587
9588
9589 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9590 ObjCPropertyDecl *SuperProperty,
9591 const IdentifierInfo *Name,
9592 bool OverridingProtocolProperty);
9593
9594 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
9595 ObjCInterfaceDecl *ID);
9596
9597 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
9598 ArrayRef<Decl *> allMethods = None,
9599 ArrayRef<DeclGroupPtrTy> allTUVars = None);
9600
9601 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
9602 SourceLocation LParenLoc,
9603 FieldDeclarator &FD, ObjCDeclSpec &ODS,
9604 Selector GetterSel, Selector SetterSel,
9605 tok::ObjCKeywordKind MethodImplKind,
9606 DeclContext *lexicalDC = nullptr);
9607
9608 Decl *ActOnPropertyImplDecl(Scope *S,
9609 SourceLocation AtLoc,
9610 SourceLocation PropertyLoc,
9611 bool ImplKind,
9612 IdentifierInfo *PropertyId,
9613 IdentifierInfo *PropertyIvar,
9614 SourceLocation PropertyIvarLoc,
9615 ObjCPropertyQueryKind QueryKind);
9616
9617 enum ObjCSpecialMethodKind {
9618 OSMK_None,
9619 OSMK_Alloc,
9620 OSMK_New,
9621 OSMK_Copy,
9622 OSMK_RetainingInit,
9623 OSMK_NonRetainingInit
9624 };
9625
9626 struct ObjCArgInfo {
9627 IdentifierInfo *Name;
9628 SourceLocation NameLoc;
9629 // The Type is null if no type was specified, and the DeclSpec is invalid
9630 // in this case.
9631 ParsedType Type;
9632 ObjCDeclSpec DeclSpec;
9633
9634 /// ArgAttrs - Attribute list for this argument.
9635 ParsedAttributesView ArgAttrs;
9636 };
9637
9638 Decl *ActOnMethodDeclaration(
9639 Scope *S,
9640 SourceLocation BeginLoc, // location of the + or -.
9641 SourceLocation EndLoc, // location of the ; or {.
9642 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
9643 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
9644 // optional arguments. The number of types/arguments is obtained
9645 // from the Sel.getNumArgs().
9646 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
9647 unsigned CNumArgs, // c-style args
9648 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
9649 bool isVariadic, bool MethodDefinition);
9650
9651 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
9652 const ObjCObjectPointerType *OPT,
9653 bool IsInstance);
9654 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
9655 bool IsInstance);
9656
9657 bool CheckARCMethodDecl(ObjCMethodDecl *method);
9658 bool inferObjCARCLifetime(ValueDecl *decl);
9659
9660 void deduceOpenCLAddressSpace(ValueDecl *decl);
9661
9662 ExprResult
9663 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
9664 Expr *BaseExpr,
9665 SourceLocation OpLoc,
9666 DeclarationName MemberName,
9667 SourceLocation MemberLoc,
9668 SourceLocation SuperLoc, QualType SuperType,
9669 bool Super);
9670
9671 ExprResult
9672 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9673 IdentifierInfo &propertyName,
9674 SourceLocation receiverNameLoc,
9675 SourceLocation propertyNameLoc);
9676
9677 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9678
9679 /// Describes the kind of message expression indicated by a message
9680 /// send that starts with an identifier.
9681 enum ObjCMessageKind {
9682 /// The message is sent to 'super'.
9683 ObjCSuperMessage,
9684 /// The message is an instance message.
9685 ObjCInstanceMessage,
9686 /// The message is a class message, and the identifier is a type
9687 /// name.
9688 ObjCClassMessage
9689 };
9690
9691 ObjCMessageKind getObjCMessageKind(Scope *S,
9692 IdentifierInfo *Name,
9693 SourceLocation NameLoc,
9694 bool IsSuper,
9695 bool HasTrailingDot,
9696 ParsedType &ReceiverType);
9697
9698 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
9699 Selector Sel,
9700 SourceLocation LBracLoc,
9701 ArrayRef<SourceLocation> SelectorLocs,
9702 SourceLocation RBracLoc,
9703 MultiExprArg Args);
9704
9705 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
9706 QualType ReceiverType,
9707 SourceLocation SuperLoc,
9708 Selector Sel,
9709 ObjCMethodDecl *Method,
9710 SourceLocation LBracLoc,
9711 ArrayRef<SourceLocation> SelectorLocs,
9712 SourceLocation RBracLoc,
9713 MultiExprArg Args,
9714 bool isImplicit = false);
9715
9716 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
9717 bool isSuperReceiver,
9718 SourceLocation Loc,
9719 Selector Sel,
9720 ObjCMethodDecl *Method,
9721 MultiExprArg Args);
9722
9723 ExprResult ActOnClassMessage(Scope *S,
9724 ParsedType Receiver,
9725 Selector Sel,
9726 SourceLocation LBracLoc,
9727 ArrayRef<SourceLocation> SelectorLocs,
9728 SourceLocation RBracLoc,
9729 MultiExprArg Args);
9730
9731 ExprResult BuildInstanceMessage(Expr *Receiver,
9732 QualType ReceiverType,
9733 SourceLocation SuperLoc,
9734 Selector Sel,
9735 ObjCMethodDecl *Method,
9736 SourceLocation LBracLoc,
9737 ArrayRef<SourceLocation> SelectorLocs,
9738 SourceLocation RBracLoc,
9739 MultiExprArg Args,
9740 bool isImplicit = false);
9741
9742 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
9743 QualType ReceiverType,
9744 SourceLocation Loc,
9745 Selector Sel,
9746 ObjCMethodDecl *Method,
9747 MultiExprArg Args);
9748
9749 ExprResult ActOnInstanceMessage(Scope *S,
9750 Expr *Receiver,
9751 Selector Sel,
9752 SourceLocation LBracLoc,
9753 ArrayRef<SourceLocation> SelectorLocs,
9754 SourceLocation RBracLoc,
9755 MultiExprArg Args);
9756
9757 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
9758 ObjCBridgeCastKind Kind,
9759 SourceLocation BridgeKeywordLoc,
9760 TypeSourceInfo *TSInfo,
9761 Expr *SubExpr);
9762
9763 ExprResult ActOnObjCBridgedCast(Scope *S,
9764 SourceLocation LParenLoc,
9765 ObjCBridgeCastKind Kind,
9766 SourceLocation BridgeKeywordLoc,
9767 ParsedType Type,
9768 SourceLocation RParenLoc,
9769 Expr *SubExpr);
9770
9771 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
9772
9773 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
9774
9775 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
9776 CastKind &Kind);
9777
9778 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
9779 QualType DestType, QualType SrcType,
9780 ObjCInterfaceDecl *&RelatedClass,
9781 ObjCMethodDecl *&ClassMethod,
9782 ObjCMethodDecl *&InstanceMethod,
9783 TypedefNameDecl *&TDNDecl,
9784 bool CfToNs, bool Diagnose = true);
9785
9786 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
9787 QualType DestType, QualType SrcType,
9788 Expr *&SrcExpr, bool Diagnose = true);
9789
9790 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
9791 bool Diagnose = true);
9792
9793 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
9794
9795 /// Check whether the given new method is a valid override of the
9796 /// given overridden method, and set any properties that should be inherited.
9797 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
9798 const ObjCMethodDecl *Overridden);
9799
9800 /// Describes the compatibility of a result type with its method.
9801 enum ResultTypeCompatibilityKind {
9802 RTC_Compatible,
9803 RTC_Incompatible,
9804 RTC_Unknown
9805 };
9806
9807 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
9808 ObjCMethodDecl *overridden);
9809
9810 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
9811 ObjCInterfaceDecl *CurrentClass,
9812 ResultTypeCompatibilityKind RTC);
9813
9814 enum PragmaOptionsAlignKind {
9815 POAK_Native, // #pragma options align=native
9816 POAK_Natural, // #pragma options align=natural
9817 POAK_Packed, // #pragma options align=packed
9818 POAK_Power, // #pragma options align=power
9819 POAK_Mac68k, // #pragma options align=mac68k
9820 POAK_Reset // #pragma options align=reset
9821 };
9822
9823 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
9824 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
9825 PragmaClangSectionAction Action,
9826 PragmaClangSectionKind SecKind, StringRef SecName);
9827
9828 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
9829 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
9830 SourceLocation PragmaLoc);
9831
9832 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
9833 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
9834 StringRef SlotLabel, Expr *Alignment);
9835
9836 enum class PragmaAlignPackDiagnoseKind {
9837 NonDefaultStateAtInclude,
9838 ChangedStateAtExit
9839 };
9840
9841 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
9842 SourceLocation IncludeLoc);
9843 void DiagnoseUnterminatedPragmaAlignPack();
9844
9845 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
9846 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
9847
9848 /// ActOnPragmaMSComment - Called on well formed
9849 /// \#pragma comment(kind, "arg").
9850 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
9851 StringRef Arg);
9852
9853 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
9854 /// pointers_to_members(representation method[, general purpose
9855 /// representation]).
9856 void ActOnPragmaMSPointersToMembers(
9857 LangOptions::PragmaMSPointersToMembersKind Kind,
9858 SourceLocation PragmaLoc);
9859
9860 /// Called on well formed \#pragma vtordisp().
9861 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
9862 SourceLocation PragmaLoc,
9863 MSVtorDispMode Value);
9864
9865 enum PragmaSectionKind {
9866 PSK_DataSeg,
9867 PSK_BSSSeg,
9868 PSK_ConstSeg,
9869 PSK_CodeSeg,
9870 };
9871
9872 bool UnifySection(StringRef SectionName, int SectionFlags,
9873 NamedDecl *TheDecl);
9874 bool UnifySection(StringRef SectionName,
9875 int SectionFlags,
9876 SourceLocation PragmaSectionLocation);
9877
9878 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
9879 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
9880 PragmaMsStackAction Action,
9881 llvm::StringRef StackSlotLabel,
9882 StringLiteral *SegmentName,
9883 llvm::StringRef PragmaName);
9884
9885 /// Called on well formed \#pragma section().
9886 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
9887 int SectionFlags, StringLiteral *SegmentName);
9888
9889 /// Called on well-formed \#pragma init_seg().
9890 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
9891 StringLiteral *SegmentName);
9892
9893 /// Called on #pragma clang __debug dump II
9894 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9895
9896 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
9897 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
9898 StringRef Value);
9899
9900 /// Are precise floating point semantics currently enabled?
9901 bool isPreciseFPEnabled() {
9902 return !CurFPFeatures.getAllowFPReassociate() &&
9903 !CurFPFeatures.getNoSignedZero() &&
9904 !CurFPFeatures.getAllowReciprocal() &&
9905 !CurFPFeatures.getAllowApproxFunc();
9906 }
9907
9908 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
9909 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
9910 PragmaFloatControlKind Value);
9911
9912 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
9913 void ActOnPragmaUnused(const Token &Identifier,
9914 Scope *curScope,
9915 SourceLocation PragmaLoc);
9916
9917 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
9918 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
9919 SourceLocation PragmaLoc);
9920
9921 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
9922 SourceLocation Loc);
9923 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
9924
9925 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
9926 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
9927 SourceLocation PragmaLoc,
9928 SourceLocation WeakNameLoc);
9929
9930 /// ActOnPragmaRedefineExtname - Called on well formed
9931 /// \#pragma redefine_extname oldname newname.
9932 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
9933 IdentifierInfo* AliasName,
9934 SourceLocation PragmaLoc,
9935 SourceLocation WeakNameLoc,
9936 SourceLocation AliasNameLoc);
9937
9938 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
9939 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
9940 IdentifierInfo* AliasName,
9941 SourceLocation PragmaLoc,
9942 SourceLocation WeakNameLoc,
9943 SourceLocation AliasNameLoc);
9944
9945 /// ActOnPragmaFPContract - Called on well formed
9946 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
9947 /// \#pragma clang fp contract
9948 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
9949
9950 /// Called on well formed
9951 /// \#pragma clang fp reassociate
9952 void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
9953
9954 /// ActOnPragmaFenvAccess - Called on well formed
9955 /// \#pragma STDC FENV_ACCESS
9956 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
9957
9958 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
9959 void ActOnPragmaFPExceptions(SourceLocation Loc,
9960 LangOptions::FPExceptionModeKind);
9961
9962 /// Called to set constant rounding mode for floating point operations.
9963 void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
9964
9965 /// Called to set exception behavior for floating point operations.
9966 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
9967
9968 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
9969 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
9970 void AddAlignmentAttributesForRecord(RecordDecl *RD);
9971
9972 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
9973 void AddMsStructLayoutForRecord(RecordDecl *RD);
9974
9975 /// PushNamespaceVisibilityAttr - Note that we've entered a
9976 /// namespace with a visibility attribute.
9977 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
9978 SourceLocation Loc);
9979
9980 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
9981 /// add an appropriate visibility attribute.
9982 void AddPushedVisibilityAttribute(Decl *RD);
9983
9984 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
9985 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
9986 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
9987
9988 /// FreeVisContext - Deallocate and null out VisContext.
9989 void FreeVisContext();
9990
9991 /// AddCFAuditedAttribute - Check whether we're currently within
9992 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
9993 /// the appropriate attribute.
9994 void AddCFAuditedAttribute(Decl *D);
9995
9996 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
9997 SourceLocation PragmaLoc,
9998 attr::ParsedSubjectMatchRuleSet Rules);
9999 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
10000 const IdentifierInfo *Namespace);
10001
10002 /// Called on well-formed '\#pragma clang attribute pop'.
10003 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
10004 const IdentifierInfo *Namespace);
10005
10006 /// Adds the attributes that have been specified using the
10007 /// '\#pragma clang attribute push' directives to the given declaration.
10008 void AddPragmaAttributes(Scope *S, Decl *D);
10009
10010 void DiagnoseUnterminatedPragmaAttribute();
10011
10012 /// Called on well formed \#pragma clang optimize.
10013 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
10014
10015 /// Get the location for the currently active "\#pragma clang optimize
10016 /// off". If this location is invalid, then the state of the pragma is "on".
10017 SourceLocation getOptimizeOffPragmaLocation() const {
10018 return OptimizeOffPragmaLocation;
10019 }
10020
10021 /// Only called on function definitions; if there is a pragma in scope
10022 /// with the effect of a range-based optnone, consider marking the function
10023 /// with attribute optnone.
10024 void AddRangeBasedOptnone(FunctionDecl *FD);
10025
10026 /// Adds the 'optnone' attribute to the function declaration if there
10027 /// are no conflicts; Loc represents the location causing the 'optnone'
10028 /// attribute to be added (usually because of a pragma).
10029 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
10030
10031 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
10032 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10033 bool IsPackExpansion);
10034 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
10035 bool IsPackExpansion);
10036
10037 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
10038 /// declaration.
10039 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10040 Expr *OE);
10041
10042 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
10043 /// declaration.
10044 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
10045 Expr *ParamExpr);
10046
10047 /// AddAlignValueAttr - Adds an align_value attribute to a particular
10048 /// declaration.
10049 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
10050
10051 /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
10052 void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
10053 StringRef Annot, MutableArrayRef<Expr *> Args);
10054
10055 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
10056 /// declaration.
10057 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
10058 Expr *MaxThreads, Expr *MinBlocks);
10059
10060 /// AddModeAttr - Adds a mode attribute to a particular declaration.
10061 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
10062 bool InInstantiation = false);
10063
10064 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
10065 ParameterABI ABI);
10066
10067 enum class RetainOwnershipKind {NS, CF, OS};
10068 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
10069 RetainOwnershipKind K, bool IsTemplateInstantiation);
10070
10071 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
10072 /// attribute to a particular declaration.
10073 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
10074 Expr *Min, Expr *Max);
10075
10076 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
10077 /// particular declaration.
10078 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
10079 Expr *Min, Expr *Max);
10080
10081 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
10082
10083 //===--------------------------------------------------------------------===//
10084 // C++ Coroutines TS
10085 //
10086 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
10087 StringRef Keyword);
10088 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10089 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10090 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
10091
10092 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10093 bool IsImplicit = false);
10094 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10095 UnresolvedLookupExpr* Lookup);
10096 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
10097 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
10098 bool IsImplicit = false);
10099 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
10100 bool buildCoroutineParameterMoves(SourceLocation Loc);
10101 VarDecl *buildCoroutinePromise(SourceLocation Loc);
10102 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
10103 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
10104 SourceLocation FuncLoc);
10105 /// Check that the expression co_await promise.final_suspend() shall not be
10106 /// potentially-throwing.
10107 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
10108
10109 //===--------------------------------------------------------------------===//
10110 // OpenCL extensions.
10111 //
10112private:
10113 std::string CurrOpenCLExtension;
10114 /// Extensions required by an OpenCL type.
10115 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
10116 /// Extensions required by an OpenCL declaration.
10117 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
10118public:
10119 llvm::StringRef getCurrentOpenCLExtension() const {
10120 return CurrOpenCLExtension;
10121 }
10122
10123 /// Check if a function declaration \p FD associates with any
10124 /// extensions present in OpenCLDeclExtMap and if so return the
10125 /// extension(s) name(s).
10126 std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
10127
10128 /// Check if a function type \p FT associates with any
10129 /// extensions present in OpenCLTypeExtMap and if so return the
10130 /// extension(s) name(s).
10131 std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
10132
10133 /// Find an extension in an appropriate extension map and return its name
10134 template<typename T, typename MapT>
10135 std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
10136
10137 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
10138 CurrOpenCLExtension = std::string(Ext);
10139 }
10140
10141 /// Set OpenCL extensions for a type which can only be used when these
10142 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
10143 /// \param Exts A space separated list of OpenCL extensions.
10144 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
10145
10146 /// Set OpenCL extensions for a declaration which can only be
10147 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
10148 /// nothing.
10149 /// \param Exts A space separated list of OpenCL extensions.
10150 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
10151
10152 /// Set current OpenCL extensions for a type which can only be used
10153 /// when these OpenCL extensions are enabled. If current OpenCL extension is
10154 /// empty, do nothing.
10155 void setCurrentOpenCLExtensionForType(QualType T);
10156
10157 /// Set current OpenCL extensions for a declaration which
10158 /// can only be used when these OpenCL extensions are enabled. If current
10159 /// OpenCL extension is empty, do nothing.
10160 void setCurrentOpenCLExtensionForDecl(Decl *FD);
10161
10162 bool isOpenCLDisabledDecl(Decl *FD);
10163
10164 /// Check if type \p T corresponding to declaration specifier \p DS
10165 /// is disabled due to required OpenCL extensions being disabled. If so,
10166 /// emit diagnostics.
10167 /// \return true if type is disabled.
10168 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
10169
10170 /// Check if declaration \p D used by expression \p E
10171 /// is disabled due to required OpenCL extensions being disabled. If so,
10172 /// emit diagnostics.
10173 /// \return true if type is disabled.
10174 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
10175
10176 //===--------------------------------------------------------------------===//
10177 // OpenMP directives and clauses.
10178 //
10179private:
10180 void *VarDataSharingAttributesStack;
10181 /// Number of nested '#pragma omp declare target' directives.
10182 SmallVector<SourceLocation, 4> DeclareTargetNesting;
10183 /// Initialization of data-sharing attributes stack.
10184 void InitDataSharingAttributesStack();
10185 void DestroyDataSharingAttributesStack();
10186 ExprResult
10187 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
10188 bool StrictlyPositive = true);
10189 /// Returns OpenMP nesting level for current directive.
10190 unsigned getOpenMPNestingLevel() const;
10191
10192 /// Adjusts the function scopes index for the target-based regions.
10193 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
10194 unsigned Level) const;
10195
10196 /// Returns the number of scopes associated with the construct on the given
10197 /// OpenMP level.
10198 int getNumberOfConstructScopes(unsigned Level) const;
10199
10200 /// Push new OpenMP function region for non-capturing function.
10201 void pushOpenMPFunctionRegion();
10202
10203 /// Pop OpenMP function region for non-capturing function.
10204 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
10205
10206 /// Checks if a type or a declaration is disabled due to the owning extension
10207 /// being disabled, and emits diagnostic messages if it is disabled.
10208 /// \param D type or declaration to be checked.
10209 /// \param DiagLoc source location for the diagnostic message.
10210 /// \param DiagInfo information to be emitted for the diagnostic message.
10211 /// \param SrcRange source range of the declaration.
10212 /// \param Map maps type or declaration to the extensions.
10213 /// \param Selector selects diagnostic message: 0 for type and 1 for
10214 /// declaration.
10215 /// \return true if the type or declaration is disabled.
10216 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
10217 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
10218 MapT &Map, unsigned Selector = 0,
10219 SourceRange SrcRange = SourceRange());
10220
10221 /// Helper to keep information about the current `omp begin/end declare
10222 /// variant` nesting.
10223 struct OMPDeclareVariantScope {
10224 /// The associated OpenMP context selector.
10225 OMPTraitInfo *TI;
10226
10227 /// The associated OpenMP context selector mangling.
10228 std::string NameSuffix;
10229
10230 OMPDeclareVariantScope(OMPTraitInfo &TI);
10231 };
10232
10233 /// Return the OMPTraitInfo for the surrounding scope, if any.
10234 OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
10235 return OMPDeclareVariantScopes.empty() ? nullptr
10236 : OMPDeclareVariantScopes.back().TI;
10237 }
10238
10239 /// The current `omp begin/end declare variant` scopes.
10240 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
10241
10242 /// The current `omp begin/end assumes` scopes.
10243 SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
10244
10245 /// All `omp assumes` we encountered so far.
10246 SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
10247
10248public:
10249 /// The declarator \p D defines a function in the scope \p S which is nested
10250 /// in an `omp begin/end declare variant` scope. In this method we create a
10251 /// declaration for \p D and rename \p D according to the OpenMP context
10252 /// selector of the surrounding scope. Return all base functions in \p Bases.
10253 void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
10254 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
10255 SmallVectorImpl<FunctionDecl *> &Bases);
10256
10257 /// Register \p D as specialization of all base functions in \p Bases in the
10258 /// current `omp begin/end declare variant` scope.
10259 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
10260 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
10261
10262 /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
10263 void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
10264
10265 /// Can we exit an OpenMP declare variant scope at the moment.
10266 bool isInOpenMPDeclareVariantScope() const {
10267 return !OMPDeclareVariantScopes.empty();
10268 }
10269
10270 /// Given the potential call expression \p Call, determine if there is a
10271 /// specialization via the OpenMP declare variant mechanism available. If
10272 /// there is, return the specialized call expression, otherwise return the
10273 /// original \p Call.
10274 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
10275 SourceLocation LParenLoc, MultiExprArg ArgExprs,
10276 SourceLocation RParenLoc, Expr *ExecConfig);
10277
10278 /// Handle a `omp begin declare variant`.
10279 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
10280
10281 /// Handle a `omp end declare variant`.
10282 void ActOnOpenMPEndDeclareVariant();
10283
10284 /// Checks if the variant/multiversion functions are compatible.
10285 bool areMultiversionVariantFunctionsCompatible(
10286 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10287 const PartialDiagnostic &NoProtoDiagID,
10288 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10289 const PartialDiagnosticAt &NoSupportDiagIDAt,
10290 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10291 bool ConstexprSupported, bool CLinkageMayDiffer);
10292
10293 /// Function tries to capture lambda's captured variables in the OpenMP region
10294 /// before the original lambda is captured.
10295 void tryCaptureOpenMPLambdas(ValueDecl *V);
10296
10297 /// Return true if the provided declaration \a VD should be captured by
10298 /// reference.
10299 /// \param Level Relative level of nested OpenMP construct for that the check
10300 /// is performed.
10301 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
10302 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
10303 unsigned OpenMPCaptureLevel) const;
10304
10305 /// Check if the specified variable is used in one of the private
10306 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
10307 /// constructs.
10308 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
10309 unsigned StopAt = 0);
10310 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10311 ExprObjectKind OK, SourceLocation Loc);
10312
10313 /// If the current region is a loop-based region, mark the start of the loop
10314 /// construct.
10315 void startOpenMPLoop();
10316
10317 /// If the current region is a range loop-based region, mark the start of the
10318 /// loop construct.
10319 void startOpenMPCXXRangeFor();
10320
10321 /// Check if the specified variable is used in 'private' clause.
10322 /// \param Level Relative level of nested OpenMP construct for that the check
10323 /// is performed.
10324 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
10325 unsigned CapLevel) const;
10326
10327 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
10328 /// for \p FD based on DSA for the provided corresponding captured declaration
10329 /// \p D.
10330 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
10331
10332 /// Check if the specified variable is captured by 'target' directive.
10333 /// \param Level Relative level of nested OpenMP construct for that the check
10334 /// is performed.
10335 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
10336 unsigned CaptureLevel) const;
10337
10338 /// Check if the specified global variable must be captured by outer capture
10339 /// regions.
10340 /// \param Level Relative level of nested OpenMP construct for that
10341 /// the check is performed.
10342 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
10343 unsigned CaptureLevel) const;
10344
10345 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
10346 Expr *Op);
10347 /// Called on start of new data sharing attribute block.
10348 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
10349 const DeclarationNameInfo &DirName, Scope *CurScope,
10350 SourceLocation Loc);
10351 /// Start analysis of clauses.
10352 void StartOpenMPClause(OpenMPClauseKind K);
10353 /// End analysis of clauses.
10354 void EndOpenMPClause();
10355 /// Called on end of data sharing attribute block.
10356 void EndOpenMPDSABlock(Stmt *CurDirective);
10357
10358 /// Check if the current region is an OpenMP loop region and if it is,
10359 /// mark loop control variable, used in \p Init for loop initialization, as
10360 /// private by default.
10361 /// \param Init First part of the for loop.
10362 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
10363
10364 // OpenMP directives and clauses.
10365 /// Called on correct id-expression from the '#pragma omp
10366 /// threadprivate'.
10367 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10368 const DeclarationNameInfo &Id,
10369 OpenMPDirectiveKind Kind);
10370 /// Called on well-formed '#pragma omp threadprivate'.
10371 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
10372 SourceLocation Loc,
10373 ArrayRef<Expr *> VarList);
10374 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
10375 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
10376 ArrayRef<Expr *> VarList);
10377 /// Called on well-formed '#pragma omp allocate'.
10378 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
10379 ArrayRef<Expr *> VarList,
10380 ArrayRef<OMPClause *> Clauses,
10381 DeclContext *Owner = nullptr);
10382
10383 /// Called on well-formed '#pragma omp [begin] assume[s]'.
10384 void ActOnOpenMPAssumesDirective(SourceLocation Loc,
10385 OpenMPDirectiveKind DKind,
10386 ArrayRef<StringRef> Assumptions,
10387 bool SkippedClauses);
10388
10389 /// Check if there is an active global `omp begin assumes` directive.
10390 bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
10391
10392 /// Check if there is an active global `omp assumes` directive.
10393 bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
10394
10395 /// Called on well-formed '#pragma omp end assumes'.
10396 void ActOnOpenMPEndAssumesDirective();
10397
10398 /// Called on well-formed '#pragma omp requires'.
10399 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
10400 ArrayRef<OMPClause *> ClauseList);
10401 /// Check restrictions on Requires directive
10402 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
10403 ArrayRef<OMPClause *> Clauses);
10404 /// Check if the specified type is allowed to be used in 'omp declare
10405 /// reduction' construct.
10406 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10407 TypeResult ParsedType);
10408 /// Called on start of '#pragma omp declare reduction'.
10409 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
10410 Scope *S, DeclContext *DC, DeclarationName Name,
10411 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10412 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
10413 /// Initialize declare reduction construct initializer.
10414 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
10415 /// Finish current declare reduction construct initializer.
10416 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
10417 /// Initialize declare reduction construct initializer.
10418 /// \return omp_priv variable.
10419 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
10420 /// Finish current declare reduction construct initializer.
10421 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
10422 VarDecl *OmpPrivParm);
10423 /// Called at the end of '#pragma omp declare reduction'.
10424 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
10425 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
10426
10427 /// Check variable declaration in 'omp declare mapper' construct.
10428 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
10429 /// Check if the specified type is allowed to be used in 'omp declare
10430 /// mapper' construct.
10431 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
10432 TypeResult ParsedType);
10433 /// Called on start of '#pragma omp declare mapper'.
10434 DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
10435 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
10436 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
10437 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
10438 Decl *PrevDeclInScope = nullptr);
10439 /// Build the mapper variable of '#pragma omp declare mapper'.
10440 ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
10441 QualType MapperType,
10442 SourceLocation StartLoc,
10443 DeclarationName VN);
10444 bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
10445 const ValueDecl *getOpenMPDeclareMapperVarName() const;
10446
10447 /// Called on the start of target region i.e. '#pragma omp declare target'.
10448 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
10449 /// Called at the end of target region i.e. '#pragme omp end declare target'.
10450 void ActOnFinishOpenMPDeclareTargetDirective();
10451 /// Searches for the provided declaration name for OpenMP declare target
10452 /// directive.
10453 NamedDecl *
10454 lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10455 const DeclarationNameInfo &Id,
10456 NamedDeclSetType &SameDirectiveDecls);
10457 /// Called on correct id-expression from the '#pragma omp declare target'.
10458 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
10459 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10460 OMPDeclareTargetDeclAttr::DevTypeTy DT);
10461 /// Check declaration inside target region.
10462 void
10463 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
10464 SourceLocation IdLoc = SourceLocation());
10465 /// Finishes analysis of the deferred functions calls that may be declared as
10466 /// host/nohost during device/host compilation.
10467 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
10468 const FunctionDecl *Callee,
10469 SourceLocation Loc);
10470 /// Return true inside OpenMP declare target region.
10471 bool isInOpenMPDeclareTargetContext() const {
10472 return !DeclareTargetNesting.empty();
10473 }
10474 /// Return true inside OpenMP target region.
10475 bool isInOpenMPTargetExecutionDirective() const;
10476
10477 /// Return the number of captured regions created for an OpenMP directive.
10478 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
10479
10480 /// Initialization of captured region for OpenMP region.
10481 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
10482 /// End of OpenMP region.
10483 ///
10484 /// \param S Statement associated with the current OpenMP region.
10485 /// \param Clauses List of clauses for the current OpenMP region.
10486 ///
10487 /// \returns Statement for finished OpenMP region.
10488 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
10489 StmtResult ActOnOpenMPExecutableDirective(
10490 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
10491 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
10492 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
10493 /// Called on well-formed '\#pragma omp parallel' after parsing
10494 /// of the associated statement.
10495 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
10496 Stmt *AStmt,
10497 SourceLocation StartLoc,
10498 SourceLocation EndLoc);
10499 using VarsWithInheritedDSAType =
10500 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
10501 /// Called on well-formed '\#pragma omp simd' after parsing
10502 /// of the associated statement.
10503 StmtResult
10504 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10505 SourceLocation StartLoc, SourceLocation EndLoc,
10506 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10507 /// Called on well-formed '\#pragma omp for' after parsing
10508 /// of the associated statement.
10509 StmtResult
10510 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10511 SourceLocation StartLoc, SourceLocation EndLoc,
10512 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10513 /// Called on well-formed '\#pragma omp for simd' after parsing
10514 /// of the associated statement.
10515 StmtResult
10516 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10517 SourceLocation StartLoc, SourceLocation EndLoc,
10518 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10519 /// Called on well-formed '\#pragma omp sections' after parsing
10520 /// of the associated statement.
10521 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10522 Stmt *AStmt, SourceLocation StartLoc,
10523 SourceLocation EndLoc);
10524 /// Called on well-formed '\#pragma omp section' after parsing of the
10525 /// associated statement.
10526 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
10527 SourceLocation EndLoc);
10528 /// Called on well-formed '\#pragma omp single' after parsing of the
10529 /// associated statement.
10530 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10531 Stmt *AStmt, SourceLocation StartLoc,
10532 SourceLocation EndLoc);
10533 /// Called on well-formed '\#pragma omp master' after parsing of the
10534 /// associated statement.
10535 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
10536 SourceLocation EndLoc);
10537 /// Called on well-formed '\#pragma omp critical' after parsing of the
10538 /// associated statement.
10539 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
10540 ArrayRef<OMPClause *> Clauses,
10541 Stmt *AStmt, SourceLocation StartLoc,
10542 SourceLocation EndLoc);
10543 /// Called on well-formed '\#pragma omp parallel for' after parsing
10544 /// of the associated statement.
10545 StmtResult ActOnOpenMPParallelForDirective(
10546 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10547 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10548 /// Called on well-formed '\#pragma omp parallel for simd' after
10549 /// parsing of the associated statement.
10550 StmtResult ActOnOpenMPParallelForSimdDirective(
10551 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10552 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10553 /// Called on well-formed '\#pragma omp parallel master' after
10554 /// parsing of the associated statement.
10555 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10556 Stmt *AStmt,
10557 SourceLocation StartLoc,
10558 SourceLocation EndLoc);
10559 /// Called on well-formed '\#pragma omp parallel sections' after
10560 /// parsing of the associated statement.
10561 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10562 Stmt *AStmt,
10563 SourceLocation StartLoc,
10564 SourceLocation EndLoc);
10565 /// Called on well-formed '\#pragma omp task' after parsing of the
10566 /// associated statement.
10567 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10568 Stmt *AStmt, SourceLocation StartLoc,
10569 SourceLocation EndLoc);
10570 /// Called on well-formed '\#pragma omp taskyield'.
10571 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10572 SourceLocation EndLoc);
10573 /// Called on well-formed '\#pragma omp barrier'.
10574 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10575 SourceLocation EndLoc);
10576 /// Called on well-formed '\#pragma omp taskwait'.
10577 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10578 SourceLocation EndLoc);
10579 /// Called on well-formed '\#pragma omp taskgroup'.
10580 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10581 Stmt *AStmt, SourceLocation StartLoc,
10582 SourceLocation EndLoc);
10583 /// Called on well-formed '\#pragma omp flush'.
10584 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10585 SourceLocation StartLoc,
10586 SourceLocation EndLoc);
10587 /// Called on well-formed '\#pragma omp depobj'.
10588 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10589 SourceLocation StartLoc,
10590 SourceLocation EndLoc);
10591 /// Called on well-formed '\#pragma omp scan'.
10592 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10593 SourceLocation StartLoc,
10594 SourceLocation EndLoc);
10595 /// Called on well-formed '\#pragma omp ordered' after parsing of the
10596 /// associated statement.
10597 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10598 Stmt *AStmt, SourceLocation StartLoc,
10599 SourceLocation EndLoc);
10600 /// Called on well-formed '\#pragma omp atomic' after parsing of the
10601 /// associated statement.
10602 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10603 Stmt *AStmt, SourceLocation StartLoc,
10604 SourceLocation EndLoc);
10605 /// Called on well-formed '\#pragma omp target' after parsing of the
10606 /// associated statement.
10607 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10608 Stmt *AStmt, SourceLocation StartLoc,
10609 SourceLocation EndLoc);
10610 /// Called on well-formed '\#pragma omp target data' after parsing of
10611 /// the associated statement.
10612 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10613 Stmt *AStmt, SourceLocation StartLoc,
10614 SourceLocation EndLoc);
10615 /// Called on well-formed '\#pragma omp target enter data' after
10616 /// parsing of the associated statement.
10617 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10618 SourceLocation StartLoc,
10619 SourceLocation EndLoc,
10620 Stmt *AStmt);
10621 /// Called on well-formed '\#pragma omp target exit data' after
10622 /// parsing of the associated statement.
10623 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10624 SourceLocation StartLoc,
10625 SourceLocation EndLoc,
10626 Stmt *AStmt);
10627 /// Called on well-formed '\#pragma omp target parallel' after
10628 /// parsing of the associated statement.
10629 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10630 Stmt *AStmt,
10631 SourceLocation StartLoc,
10632 SourceLocation EndLoc);
10633 /// Called on well-formed '\#pragma omp target parallel for' after
10634 /// parsing of the associated statement.
10635 StmtResult ActOnOpenMPTargetParallelForDirective(
10636 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10637 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10638 /// Called on well-formed '\#pragma omp teams' after parsing of the
10639 /// associated statement.
10640 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10641 Stmt *AStmt, SourceLocation StartLoc,
10642 SourceLocation EndLoc);
10643 /// Called on well-formed '\#pragma omp cancellation point'.
10644 StmtResult
10645 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10646 SourceLocation EndLoc,
10647 OpenMPDirectiveKind CancelRegion);
10648 /// Called on well-formed '\#pragma omp cancel'.
10649 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10650 SourceLocation StartLoc,
10651 SourceLocation EndLoc,
10652 OpenMPDirectiveKind CancelRegion);
10653 /// Called on well-formed '\#pragma omp taskloop' after parsing of the
10654 /// associated statement.
10655 StmtResult
10656 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10657 SourceLocation StartLoc, SourceLocation EndLoc,
10658 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10659 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
10660 /// the associated statement.
10661 StmtResult ActOnOpenMPTaskLoopSimdDirective(
10662 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10663 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10664 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
10665 /// associated statement.
10666 StmtResult ActOnOpenMPMasterTaskLoopDirective(
10667 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10668 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10669 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
10670 /// the associated statement.
10671 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
10672 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10673 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10674 /// Called on well-formed '\#pragma omp parallel master taskloop' after
10675 /// parsing of the associated statement.
10676 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
10677 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10678 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10679 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
10680 /// parsing of the associated statement.
10681 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10682 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10683 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10684 /// Called on well-formed '\#pragma omp distribute' after parsing
10685 /// of the associated statement.
10686 StmtResult
10687 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10688 SourceLocation StartLoc, SourceLocation EndLoc,
10689 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10690 /// Called on well-formed '\#pragma omp target update'.
10691 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10692 SourceLocation StartLoc,
10693 SourceLocation EndLoc,
10694 Stmt *AStmt);
10695 /// Called on well-formed '\#pragma omp distribute parallel for' after
10696 /// parsing of the associated statement.
10697 StmtResult ActOnOpenMPDistributeParallelForDirective(
10698 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10699 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10700 /// Called on well-formed '\#pragma omp distribute parallel for simd'
10701 /// after parsing of the associated statement.
10702 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
10703 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10704 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10705 /// Called on well-formed '\#pragma omp distribute simd' after
10706 /// parsing of the associated statement.
10707 StmtResult ActOnOpenMPDistributeSimdDirective(
10708 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10709 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10710 /// Called on well-formed '\#pragma omp target parallel for simd' after
10711 /// parsing of the associated statement.
10712 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
10713 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10714 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10715 /// Called on well-formed '\#pragma omp target simd' after parsing of
10716 /// the associated statement.
10717 StmtResult
10718 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10719 SourceLocation StartLoc, SourceLocation EndLoc,
10720 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10721 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
10722 /// the associated statement.
10723 StmtResult ActOnOpenMPTeamsDistributeDirective(
10724 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10725 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10726 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
10727 /// of the associated statement.
10728 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
10729 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10730 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10731 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
10732 /// after parsing of the associated statement.
10733 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10734 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10735 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10736 /// Called on well-formed '\#pragma omp teams distribute parallel for'
10737 /// after parsing of the associated statement.
10738 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
10739 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10740 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10741 /// Called on well-formed '\#pragma omp target teams' after parsing of the
10742 /// associated statement.
10743 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10744 Stmt *AStmt,
10745 SourceLocation StartLoc,
10746 SourceLocation EndLoc);
10747 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
10748 /// of the associated statement.
10749 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
10750 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10751 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10752 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
10753 /// after parsing of the associated statement.
10754 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10755 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10756 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10757 /// Called on well-formed '\#pragma omp target teams distribute parallel for
10758 /// simd' after parsing of the associated statement.
10759 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10760 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10761 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10762 /// Called on well-formed '\#pragma omp target teams distribute simd' after
10763 /// parsing of the associated statement.
10764 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
10765 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10766 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10767
10768 /// Checks correctness of linear modifiers.
10769 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10770 SourceLocation LinLoc);
10771 /// Checks that the specified declaration matches requirements for the linear
10772 /// decls.
10773 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
10774 OpenMPLinearClauseKind LinKind, QualType Type,
10775 bool IsDeclareSimd = false);
10776
10777 /// Called on well-formed '\#pragma omp declare simd' after parsing of
10778 /// the associated method/function.
10779 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
10780 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
10781 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
10782 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
10783 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
10784
10785 /// Checks '\#pragma omp declare variant' variant function and original
10786 /// functions after parsing of the associated method/function.
10787 /// \param DG Function declaration to which declare variant directive is
10788 /// applied to.
10789 /// \param VariantRef Expression that references the variant function, which
10790 /// must be used instead of the original one, specified in \p DG.
10791 /// \param TI The trait info object representing the match clause.
10792 /// \returns None, if the function/variant function are not compatible with
10793 /// the pragma, pair of original function/variant ref expression otherwise.
10794 Optional<std::pair<FunctionDecl *, Expr *>>
10795 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
10796 OMPTraitInfo &TI, SourceRange SR);
10797
10798 /// Called on well-formed '\#pragma omp declare variant' after parsing of
10799 /// the associated method/function.
10800 /// \param FD Function declaration to which declare variant directive is
10801 /// applied to.
10802 /// \param VariantRef Expression that references the variant function, which
10803 /// must be used instead of the original one, specified in \p DG.
10804 /// \param TI The context traits associated with the function variant.
10805 void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
10806 OMPTraitInfo &TI, SourceRange SR);
10807
10808 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
10809 Expr *Expr,
10810 SourceLocation StartLoc,
10811 SourceLocation LParenLoc,
10812 SourceLocation EndLoc);
10813 /// Called on well-formed 'allocator' clause.
10814 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
10815 SourceLocation StartLoc,
10816 SourceLocation LParenLoc,
10817 SourceLocation EndLoc);
10818 /// Called on well-formed 'if' clause.
10819 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10820 Expr *Condition, SourceLocation StartLoc,
10821 SourceLocation LParenLoc,
10822 SourceLocation NameModifierLoc,
10823 SourceLocation ColonLoc,
10824 SourceLocation EndLoc);
10825 /// Called on well-formed 'final' clause.
10826 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
10827 SourceLocation LParenLoc,
10828 SourceLocation EndLoc);
10829 /// Called on well-formed 'num_threads' clause.
10830 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
10831 SourceLocation StartLoc,
10832 SourceLocation LParenLoc,
10833 SourceLocation EndLoc);
10834 /// Called on well-formed 'safelen' clause.
10835 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
10836 SourceLocation StartLoc,
10837 SourceLocation LParenLoc,
10838 SourceLocation EndLoc);
10839 /// Called on well-formed 'simdlen' clause.
10840 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
10841 SourceLocation LParenLoc,
10842 SourceLocation EndLoc);
10843 /// Called on well-formed 'collapse' clause.
10844 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
10845 SourceLocation StartLoc,
10846 SourceLocation LParenLoc,
10847 SourceLocation EndLoc);
10848 /// Called on well-formed 'ordered' clause.
10849 OMPClause *
10850 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
10851 SourceLocation LParenLoc = SourceLocation(),
10852 Expr *NumForLoops = nullptr);
10853 /// Called on well-formed 'grainsize' clause.
10854 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
10855 SourceLocation LParenLoc,
10856 SourceLocation EndLoc);
10857 /// Called on well-formed 'num_tasks' clause.
10858 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
10859 SourceLocation LParenLoc,
10860 SourceLocation EndLoc);
10861 /// Called on well-formed 'hint' clause.
10862 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10863 SourceLocation LParenLoc,
10864 SourceLocation EndLoc);
10865 /// Called on well-formed 'detach' clause.
10866 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
10867 SourceLocation LParenLoc,
10868 SourceLocation EndLoc);
10869
10870 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
10871 unsigned Argument,
10872 SourceLocation ArgumentLoc,
10873 SourceLocation StartLoc,
10874 SourceLocation LParenLoc,
10875 SourceLocation EndLoc);
10876 /// Called on well-formed 'default' clause.
10877 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
10878 SourceLocation KindLoc,
10879 SourceLocation StartLoc,
10880 SourceLocation LParenLoc,
10881 SourceLocation EndLoc);
10882 /// Called on well-formed 'proc_bind' clause.
10883 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
10884 SourceLocation KindLoc,
10885 SourceLocation StartLoc,
10886 SourceLocation LParenLoc,
10887 SourceLocation EndLoc);
10888 /// Called on well-formed 'order' clause.
10889 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
10890 SourceLocation KindLoc,
10891 SourceLocation StartLoc,
10892 SourceLocation LParenLoc,
10893 SourceLocation EndLoc);
10894 /// Called on well-formed 'update' clause.
10895 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
10896 SourceLocation KindLoc,
10897 SourceLocation StartLoc,
10898 SourceLocation LParenLoc,
10899 SourceLocation EndLoc);
10900
10901 OMPClause *ActOnOpenMPSingleExprWithArgClause(
10902 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
10903 SourceLocation StartLoc, SourceLocation LParenLoc,
10904 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
10905 SourceLocation EndLoc);
10906 /// Called on well-formed 'schedule' clause.
10907 OMPClause *ActOnOpenMPScheduleClause(
10908 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
10909 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10910 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10911 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
10912
10913 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
10914 SourceLocation EndLoc);
10915 /// Called on well-formed 'nowait' clause.
10916 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10917 SourceLocation EndLoc);
10918 /// Called on well-formed 'untied' clause.
10919 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10920 SourceLocation EndLoc);
10921 /// Called on well-formed 'mergeable' clause.
10922 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10923 SourceLocation EndLoc);
10924 /// Called on well-formed 'read' clause.
10925 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
10926 SourceLocation EndLoc);
10927 /// Called on well-formed 'write' clause.
10928 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
10929 SourceLocation EndLoc);
10930 /// Called on well-formed 'update' clause.
10931 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10932 SourceLocation EndLoc);
10933 /// Called on well-formed 'capture' clause.
10934 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10935 SourceLocation EndLoc);
10936 /// Called on well-formed 'seq_cst' clause.
10937 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10938 SourceLocation EndLoc);
10939 /// Called on well-formed 'acq_rel' clause.
10940 OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
10941 SourceLocation EndLoc);
10942 /// Called on well-formed 'acquire' clause.
10943 OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
10944 SourceLocation EndLoc);
10945 /// Called on well-formed 'release' clause.
10946 OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
10947 SourceLocation EndLoc);
10948 /// Called on well-formed 'relaxed' clause.
10949 OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
10950 SourceLocation EndLoc);
10951 /// Called on well-formed 'destroy' clause.
10952 OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc,
10953 SourceLocation EndLoc);
10954 /// Called on well-formed 'threads' clause.
10955 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10956 SourceLocation EndLoc);
10957 /// Called on well-formed 'simd' clause.
10958 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10959 SourceLocation EndLoc);
10960 /// Called on well-formed 'nogroup' clause.
10961 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10962 SourceLocation EndLoc);
10963 /// Called on well-formed 'unified_address' clause.
10964 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10965 SourceLocation EndLoc);
10966
10967 /// Called on well-formed 'unified_address' clause.
10968 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10969 SourceLocation EndLoc);
10970
10971 /// Called on well-formed 'reverse_offload' clause.
10972 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10973 SourceLocation EndLoc);
10974
10975 /// Called on well-formed 'dynamic_allocators' clause.
10976 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10977 SourceLocation EndLoc);
10978
10979 /// Called on well-formed 'atomic_default_mem_order' clause.
10980 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
10981 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
10982 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10983
10984 OMPClause *ActOnOpenMPVarListClause(
10985 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr,
10986 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10987 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10988 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
10989 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10990 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
10991 SourceLocation ExtraModifierLoc,
10992 ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
10993 ArrayRef<SourceLocation> MotionModifiersLoc);
10994 /// Called on well-formed 'inclusive' clause.
10995 OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
10996 SourceLocation StartLoc,
10997 SourceLocation LParenLoc,
10998 SourceLocation EndLoc);
10999 /// Called on well-formed 'exclusive' clause.
11000 OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
11001 SourceLocation StartLoc,
11002 SourceLocation LParenLoc,
11003 SourceLocation EndLoc);
11004 /// Called on well-formed 'allocate' clause.
11005 OMPClause *
11006 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
11007 SourceLocation StartLoc, SourceLocation ColonLoc,
11008 SourceLocation LParenLoc, SourceLocation EndLoc);
11009 /// Called on well-formed 'private' clause.
11010 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11011 SourceLocation StartLoc,
11012 SourceLocation LParenLoc,
11013 SourceLocation EndLoc);
11014 /// Called on well-formed 'firstprivate' clause.
11015 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
11016 SourceLocation StartLoc,
11017 SourceLocation LParenLoc,
11018 SourceLocation EndLoc);
11019 /// Called on well-formed 'lastprivate' clause.
11020 OMPClause *ActOnOpenMPLastprivateClause(
11021 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
11022 SourceLocation LPKindLoc, SourceLocation ColonLoc,
11023 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11024 /// Called on well-formed 'shared' clause.
11025 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11026 SourceLocation StartLoc,
11027 SourceLocation LParenLoc,
11028 SourceLocation EndLoc);
11029 /// Called on well-formed 'reduction' clause.
11030 OMPClause *ActOnOpenMPReductionClause(
11031 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
11032 SourceLocation StartLoc, SourceLocation LParenLoc,
11033 SourceLocation ModifierLoc, SourceLocation ColonLoc,
11034 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
11035 const DeclarationNameInfo &ReductionId,
11036 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11037 /// Called on well-formed 'task_reduction' clause.
11038 OMPClause *ActOnOpenMPTaskReductionClause(
11039 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11040 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11041 CXXScopeSpec &ReductionIdScopeSpec,
11042 const DeclarationNameInfo &ReductionId,
11043 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11044 /// Called on well-formed 'in_reduction' clause.
11045 OMPClause *ActOnOpenMPInReductionClause(
11046 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11047 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11048 CXXScopeSpec &ReductionIdScopeSpec,
11049 const DeclarationNameInfo &ReductionId,
11050 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11051 /// Called on well-formed 'linear' clause.
11052 OMPClause *
11053 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
11054 SourceLocation StartLoc, SourceLocation LParenLoc,
11055 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
11056 SourceLocation ColonLoc, SourceLocation EndLoc);
11057 /// Called on well-formed 'aligned' clause.
11058 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
11059 Expr *Alignment,
11060 SourceLocation StartLoc,
11061 SourceLocation LParenLoc,
11062 SourceLocation ColonLoc,
11063 SourceLocation EndLoc);
11064 /// Called on well-formed 'copyin' clause.
11065 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11066 SourceLocation StartLoc,
11067 SourceLocation LParenLoc,
11068 SourceLocation EndLoc);
11069 /// Called on well-formed 'copyprivate' clause.
11070 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11071 SourceLocation StartLoc,
11072 SourceLocation LParenLoc,
11073 SourceLocation EndLoc);
11074 /// Called on well-formed 'flush' pseudo clause.
11075 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11076 SourceLocation StartLoc,
11077 SourceLocation LParenLoc,
11078 SourceLocation EndLoc);
11079 /// Called on well-formed 'depobj' pseudo clause.
11080 OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
11081 SourceLocation LParenLoc,
11082 SourceLocation EndLoc);
11083 /// Called on well-formed 'depend' clause.
11084 OMPClause *
11085 ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
11086 SourceLocation DepLoc, SourceLocation ColonLoc,
11087 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11088 SourceLocation LParenLoc, SourceLocation EndLoc);
11089 /// Called on well-formed 'device' clause.
11090 OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
11091 Expr *Device, SourceLocation StartLoc,
11092 SourceLocation LParenLoc,
11093 SourceLocation ModifierLoc,
11094 SourceLocation EndLoc);
11095 /// Called on well-formed 'map' clause.
11096 OMPClause *
11097 ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11098 ArrayRef<SourceLocation> MapTypeModifiersLoc,
11099 CXXScopeSpec &MapperIdScopeSpec,
11100 DeclarationNameInfo &MapperId,
11101 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11102 SourceLocation MapLoc, SourceLocation ColonLoc,
11103 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11104 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11105 /// Called on well-formed 'num_teams' clause.
11106 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
11107 SourceLocation LParenLoc,
11108 SourceLocation EndLoc);
11109 /// Called on well-formed 'thread_limit' clause.
11110 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11111 SourceLocation StartLoc,
11112 SourceLocation LParenLoc,
11113 SourceLocation EndLoc);
11114 /// Called on well-formed 'priority' clause.
11115 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
11116 SourceLocation LParenLoc,
11117 SourceLocation EndLoc);
11118 /// Called on well-formed 'dist_schedule' clause.
11119 OMPClause *ActOnOpenMPDistScheduleClause(
11120 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
11121 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
11122 SourceLocation CommaLoc, SourceLocation EndLoc);
11123 /// Called on well-formed 'defaultmap' clause.
11124 OMPClause *ActOnOpenMPDefaultmapClause(
11125 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11126 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11127 SourceLocation KindLoc, SourceLocation EndLoc);
11128 /// Called on well-formed 'to' clause.
11129 OMPClause *
11130 ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11131 ArrayRef<SourceLocation> MotionModifiersLoc,
11132 CXXScopeSpec &MapperIdScopeSpec,
11133 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11134 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11135 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11136 /// Called on well-formed 'from' clause.
11137 OMPClause *
11138 ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11139 ArrayRef<SourceLocation> MotionModifiersLoc,
11140 CXXScopeSpec &MapperIdScopeSpec,
11141 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11142 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11143 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11144 /// Called on well-formed 'use_device_ptr' clause.
11145 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11146 const OMPVarListLocTy &Locs);
11147 /// Called on well-formed 'use_device_addr' clause.
11148 OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
11149 const OMPVarListLocTy &Locs);
11150 /// Called on well-formed 'is_device_ptr' clause.
11151 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11152 const OMPVarListLocTy &Locs);
11153 /// Called on well-formed 'nontemporal' clause.
11154 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
11155 SourceLocation StartLoc,
11156 SourceLocation LParenLoc,
11157 SourceLocation EndLoc);
11158
11159 /// Data for list of allocators.
11160 struct UsesAllocatorsData {
11161 /// Allocator.
11162 Expr *Allocator = nullptr;
11163 /// Allocator traits.
11164 Expr *AllocatorTraits = nullptr;
11165 /// Locations of '(' and ')' symbols.
11166 SourceLocation LParenLoc, RParenLoc;
11167 };
11168 /// Called on well-formed 'uses_allocators' clause.
11169 OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
11170 SourceLocation LParenLoc,
11171 SourceLocation EndLoc,
11172 ArrayRef<UsesAllocatorsData> Data);
11173 /// Called on well-formed 'affinity' clause.
11174 OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
11175 SourceLocation LParenLoc,
11176 SourceLocation ColonLoc,
11177 SourceLocation EndLoc, Expr *Modifier,
11178 ArrayRef<Expr *> Locators);
11179
11180 /// The kind of conversion being performed.
11181 enum CheckedConversionKind {
11182 /// An implicit conversion.
11183 CCK_ImplicitConversion,
11184 /// A C-style cast.
11185 CCK_CStyleCast,
11186 /// A functional-style cast.
11187 CCK_FunctionalCast,
11188 /// A cast other than a C-style cast.
11189 CCK_OtherCast,
11190 /// A conversion for an operand of a builtin overloaded operator.
11191 CCK_ForBuiltinOverloadedOp
11192 };
11193
11194 static bool isCast(CheckedConversionKind CCK) {
11195 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
11196 CCK == CCK_OtherCast;
11197 }
11198
11199 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
11200 /// cast. If there is already an implicit cast, merge into the existing one.
11201 /// If isLvalue, the result of the cast is an lvalue.
11202 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
11203 ExprValueKind VK = VK_RValue,
11204 const CXXCastPath *BasePath = nullptr,
11205 CheckedConversionKind CCK
11206 = CCK_ImplicitConversion);
11207
11208 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
11209 /// to the conversion from scalar type ScalarTy to the Boolean type.
11210 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
11211
11212 /// IgnoredValueConversions - Given that an expression's result is
11213 /// syntactically ignored, perform any conversions that are
11214 /// required.
11215 ExprResult IgnoredValueConversions(Expr *E);
11216
11217 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
11218 // functions and arrays to their respective pointers (C99 6.3.2.1).
11219 ExprResult UsualUnaryConversions(Expr *E);
11220
11221 /// CallExprUnaryConversions - a special case of an unary conversion
11222 /// performed on a function designator of a call expression.
11223 ExprResult CallExprUnaryConversions(Expr *E);
11224
11225 // DefaultFunctionArrayConversion - converts functions and arrays
11226 // to their respective pointers (C99 6.3.2.1).
11227 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
11228
11229 // DefaultFunctionArrayLvalueConversion - converts functions and
11230 // arrays to their respective pointers and performs the
11231 // lvalue-to-rvalue conversion.
11232 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
11233 bool Diagnose = true);
11234
11235 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
11236 // the operand. This function is a no-op if the operand has a function type
11237 // or an array type.
11238 ExprResult DefaultLvalueConversion(Expr *E);
11239
11240 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
11241 // do not have a prototype. Integer promotions are performed on each
11242 // argument, and arguments that have type float are promoted to double.
11243 ExprResult DefaultArgumentPromotion(Expr *E);
11244
11245 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
11246 /// it as an xvalue. In C++98, the result will still be a prvalue, because
11247 /// we don't have xvalues there.
11248 ExprResult TemporaryMaterializationConversion(Expr *E);
11249
11250 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
11251 enum VariadicCallType {
11252 VariadicFunction,
11253 VariadicBlock,
11254 VariadicMethod,
11255 VariadicConstructor,
11256 VariadicDoesNotApply
11257 };
11258
11259 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
11260 const FunctionProtoType *Proto,
11261 Expr *Fn);
11262
11263 // Used for determining in which context a type is allowed to be passed to a
11264 // vararg function.
11265 enum VarArgKind {
11266 VAK_Valid,
11267 VAK_ValidInCXX11,
11268 VAK_Undefined,
11269 VAK_MSVCUndefined,
11270 VAK_Invalid
11271 };
11272
11273 // Determines which VarArgKind fits an expression.
11274 VarArgKind isValidVarArgType(const QualType &Ty);
11275
11276 /// Check to see if the given expression is a valid argument to a variadic
11277 /// function, issuing a diagnostic if not.
11278 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
11279
11280 /// Check to see if a given expression could have '.c_str()' called on it.
11281 bool hasCStrMethod(const Expr *E);
11282
11283 /// GatherArgumentsForCall - Collector argument expressions for various
11284 /// form of call prototypes.
11285 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
11286 const FunctionProtoType *Proto,
11287 unsigned FirstParam, ArrayRef<Expr *> Args,
11288 SmallVectorImpl<Expr *> &AllArgs,
11289 VariadicCallType CallType = VariadicDoesNotApply,
11290 bool AllowExplicit = false,
11291 bool IsListInitialization = false);
11292
11293 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
11294 // will create a runtime trap if the resulting type is not a POD type.
11295 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
11296 FunctionDecl *FDecl);
11297
11298 /// Context in which we're performing a usual arithmetic conversion.
11299 enum ArithConvKind {
11300 /// An arithmetic operation.
11301 ACK_Arithmetic,
11302 /// A bitwise operation.
11303 ACK_BitwiseOp,
11304 /// A comparison.
11305 ACK_Comparison,
11306 /// A conditional (?:) operator.
11307 ACK_Conditional,
11308 /// A compound assignment expression.
11309 ACK_CompAssign,
11310 };
11311
11312 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
11313 // operands and then handles various conversions that are common to binary
11314 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
11315 // routine returns the first non-arithmetic type found. The client is
11316 // responsible for emitting appropriate error diagnostics.
11317 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
11318 SourceLocation Loc, ArithConvKind ACK);
11319
11320 /// AssignConvertType - All of the 'assignment' semantic checks return this
11321 /// enum to indicate whether the assignment was allowed. These checks are
11322 /// done for simple assignments, as well as initialization, return from
11323 /// function, argument passing, etc. The query is phrased in terms of a
11324 /// source and destination type.
11325 enum AssignConvertType {
11326 /// Compatible - the types are compatible according to the standard.
11327 Compatible,
11328
11329 /// PointerToInt - The assignment converts a pointer to an int, which we
11330 /// accept as an extension.
11331 PointerToInt,
11332
11333 /// IntToPointer - The assignment converts an int to a pointer, which we
11334 /// accept as an extension.
11335 IntToPointer,
11336
11337 /// FunctionVoidPointer - The assignment is between a function pointer and
11338 /// void*, which the standard doesn't allow, but we accept as an extension.
11339 FunctionVoidPointer,
11340
11341 /// IncompatiblePointer - The assignment is between two pointers types that
11342 /// are not compatible, but we accept them as an extension.
11343 IncompatiblePointer,
11344
11345 /// IncompatibleFunctionPointer - The assignment is between two function
11346 /// pointers types that are not compatible, but we accept them as an
11347 /// extension.
11348 IncompatibleFunctionPointer,
11349
11350 /// IncompatiblePointerSign - The assignment is between two pointers types
11351 /// which point to integers which have a different sign, but are otherwise
11352 /// identical. This is a subset of the above, but broken out because it's by
11353 /// far the most common case of incompatible pointers.
11354 IncompatiblePointerSign,
11355
11356 /// CompatiblePointerDiscardsQualifiers - The assignment discards
11357 /// c/v/r qualifiers, which we accept as an extension.
11358 CompatiblePointerDiscardsQualifiers,
11359
11360 /// IncompatiblePointerDiscardsQualifiers - The assignment
11361 /// discards qualifiers that we don't permit to be discarded,
11362 /// like address spaces.
11363 IncompatiblePointerDiscardsQualifiers,
11364
11365 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
11366 /// changes address spaces in nested pointer types which is not allowed.
11367 /// For instance, converting __private int ** to __generic int ** is
11368 /// illegal even though __private could be converted to __generic.
11369 IncompatibleNestedPointerAddressSpaceMismatch,
11370
11371 /// IncompatibleNestedPointerQualifiers - The assignment is between two
11372 /// nested pointer types, and the qualifiers other than the first two
11373 /// levels differ e.g. char ** -> const char **, but we accept them as an
11374 /// extension.
11375 IncompatibleNestedPointerQualifiers,
11376
11377 /// IncompatibleVectors - The assignment is between two vector types that
11378 /// have the same size, which we accept as an extension.
11379 IncompatibleVectors,
11380
11381 /// IntToBlockPointer - The assignment converts an int to a block
11382 /// pointer. We disallow this.
11383 IntToBlockPointer,
11384
11385 /// IncompatibleBlockPointer - The assignment is between two block
11386 /// pointers types that are not compatible.
11387 IncompatibleBlockPointer,
11388
11389 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
11390 /// id type and something else (that is incompatible with it). For example,
11391 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
11392 IncompatibleObjCQualifiedId,
11393
11394 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
11395 /// object with __weak qualifier.
11396 IncompatibleObjCWeakRef,
11397
11398 /// Incompatible - We reject this conversion outright, it is invalid to
11399 /// represent it in the AST.
11400 Incompatible
11401 };
11402
11403 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
11404 /// assignment conversion type specified by ConvTy. This returns true if the
11405 /// conversion was invalid or false if the conversion was accepted.
11406 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
11407 SourceLocation Loc,
11408 QualType DstType, QualType SrcType,
11409 Expr *SrcExpr, AssignmentAction Action,
11410 bool *Complained = nullptr);
11411
11412 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
11413 /// enum. If AllowMask is true, then we also allow the complement of a valid
11414 /// value, to be used as a mask.
11415 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
11416 bool AllowMask) const;
11417
11418 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11419 /// integer not in the range of enum values.
11420 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11421 Expr *SrcExpr);
11422
11423 /// CheckAssignmentConstraints - Perform type checking for assignment,
11424 /// argument passing, variable initialization, and function return values.
11425 /// C99 6.5.16.
11426 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
11427 QualType LHSType,
11428 QualType RHSType);
11429
11430 /// Check assignment constraints and optionally prepare for a conversion of
11431 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
11432 /// is true.
11433 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
11434 ExprResult &RHS,
11435 CastKind &Kind,
11436 bool ConvertRHS = true);
11437
11438 /// Check assignment constraints for an assignment of RHS to LHSType.
11439 ///
11440 /// \param LHSType The destination type for the assignment.
11441 /// \param RHS The source expression for the assignment.
11442 /// \param Diagnose If \c true, diagnostics may be produced when checking
11443 /// for assignability. If a diagnostic is produced, \p RHS will be
11444 /// set to ExprError(). Note that this function may still return
11445 /// without producing a diagnostic, even for an invalid assignment.
11446 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
11447 /// in an audited Core Foundation API and does not need to be checked
11448 /// for ARC retain issues.
11449 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
11450 /// conversions necessary to perform the assignment. If \c false,
11451 /// \p Diagnose must also be \c false.
11452 AssignConvertType CheckSingleAssignmentConstraints(
11453 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
11454 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
11455
11456 // If the lhs type is a transparent union, check whether we
11457 // can initialize the transparent union with the given expression.
11458 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
11459 ExprResult &RHS);
11460
11461 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
11462
11463 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
11464
11465 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11466 AssignmentAction Action,
11467 bool AllowExplicit = false);
11468 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11469 const ImplicitConversionSequence& ICS,
11470 AssignmentAction Action,
11471 CheckedConversionKind CCK
11472 = CCK_ImplicitConversion);
11473 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11474 const StandardConversionSequence& SCS,
11475 AssignmentAction Action,
11476 CheckedConversionKind CCK);
11477
11478 ExprResult PerformQualificationConversion(
11479 Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
11480 CheckedConversionKind CCK = CCK_ImplicitConversion);
11481
11482 /// the following "Check" methods will return a valid/converted QualType
11483 /// or a null QualType (indicating an error diagnostic was issued).
11484
11485 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
11486 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
11487 ExprResult &RHS);
11488 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
11489 ExprResult &RHS);
11490 QualType CheckPointerToMemberOperands( // C++ 5.5
11491 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
11492 SourceLocation OpLoc, bool isIndirect);
11493 QualType CheckMultiplyDivideOperands( // C99 6.5.5
11494 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
11495 bool IsDivide);
11496 QualType CheckRemainderOperands( // C99 6.5.5
11497 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11498 bool IsCompAssign = false);
11499 QualType CheckAdditionOperands( // C99 6.5.6
11500 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11501 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
11502 QualType CheckSubtractionOperands( // C99 6.5.6
11503 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11504 QualType* CompLHSTy = nullptr);
11505 QualType CheckShiftOperands( // C99 6.5.7
11506 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11507 BinaryOperatorKind Opc, bool IsCompAssign = false);
11508 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
11509 QualType CheckCompareOperands( // C99 6.5.8/9
11510 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11511 BinaryOperatorKind Opc);
11512 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
11513 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11514 BinaryOperatorKind Opc);
11515 QualType CheckLogicalOperands( // C99 6.5.[13,14]
11516 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11517 BinaryOperatorKind Opc);
11518 // CheckAssignmentOperands is used for both simple and compound assignment.
11519 // For simple assignment, pass both expressions and a null converted type.
11520 // For compound assignment, pass both expressions and the converted type.
11521 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
11522 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
11523
11524 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
11525 UnaryOperatorKind Opcode, Expr *Op);
11526 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
11527 BinaryOperatorKind Opcode,
11528 Expr *LHS, Expr *RHS);
11529 ExprResult checkPseudoObjectRValue(Expr *E);
11530 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
11531
11532 QualType CheckConditionalOperands( // C99 6.5.15
11533 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
11534 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
11535 QualType CXXCheckConditionalOperands( // C++ 5.16
11536 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
11537 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
11538 QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
11539 ExprResult &RHS,
11540 SourceLocation QuestionLoc);
11541 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
11542 bool ConvertArgs = true);
11543 QualType FindCompositePointerType(SourceLocation Loc,
11544 ExprResult &E1, ExprResult &E2,
11545 bool ConvertArgs = true) {
11546 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
11547 QualType Composite =
11548 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
11549 E1 = E1Tmp;
11550 E2 = E2Tmp;
11551 return Composite;
11552 }
11553
11554 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
11555 SourceLocation QuestionLoc);
11556
11557 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
11558 SourceLocation QuestionLoc);
11559
11560 void DiagnoseAlwaysNonNullPointer(Expr *E,
11561 Expr::NullPointerConstantKind NullType,
11562 bool IsEqual, SourceRange Range);
11563
11564 /// type checking for vector binary operators.
11565 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11566 SourceLocation Loc, bool IsCompAssign,
11567 bool AllowBothBool, bool AllowBoolConversion);
11568 QualType GetSignedVectorType(QualType V);
11569 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11570 SourceLocation Loc,
11571 BinaryOperatorKind Opc);
11572 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11573 SourceLocation Loc);
11574
11575 /// Type checking for matrix binary operators.
11576 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
11577 SourceLocation Loc,
11578 bool IsCompAssign);
11579 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
11580 SourceLocation Loc, bool IsCompAssign);
11581
11582 bool isValidSveBitcast(QualType srcType, QualType destType);
11583
11584 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
11585 bool isLaxVectorConversion(QualType srcType, QualType destType);
11586
11587 /// type checking declaration initializers (C99 6.7.8)
11588 bool CheckForConstantInitializer(Expr *e, QualType t);
11589
11590 // type checking C++ declaration initializers (C++ [dcl.init]).
11591
11592 /// ReferenceCompareResult - Expresses the result of comparing two
11593 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
11594 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
11595 enum ReferenceCompareResult {
11596 /// Ref_Incompatible - The two types are incompatible, so direct
11597 /// reference binding is not possible.
11598 Ref_Incompatible = 0,
11599 /// Ref_Related - The two types are reference-related, which means
11600 /// that their unqualified forms (T1 and T2) are either the same
11601 /// or T1 is a base class of T2.
11602 Ref_Related,
11603 /// Ref_Compatible - The two types are reference-compatible.
11604 Ref_Compatible
11605 };
11606
11607 // Fake up a scoped enumeration that still contextually converts to bool.
11608 struct ReferenceConversionsScope {
11609 /// The conversions that would be performed on an lvalue of type T2 when
11610 /// binding a reference of type T1 to it, as determined when evaluating
11611 /// whether T1 is reference-compatible with T2.
11612 enum ReferenceConversions {
11613 Qualification = 0x1,
11614 NestedQualification = 0x2,
11615 Function = 0x4,
11616 DerivedToBase = 0x8,
11617 ObjC = 0x10,
11618 ObjCLifetime = 0x20,
11619
11620 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)LLVM_BITMASK_LARGEST_ENUMERATOR = ObjCLifetime
11621 };
11622 };
11623 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
11624
11625 ReferenceCompareResult
11626 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
11627 ReferenceConversions *Conv = nullptr);
11628
11629 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11630 Expr *CastExpr, CastKind &CastKind,
11631 ExprValueKind &VK, CXXCastPath &Path);
11632
11633 /// Force an expression with unknown-type to an expression of the
11634 /// given type.
11635 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
11636
11637 /// Type-check an expression that's being passed to an
11638 /// __unknown_anytype parameter.
11639 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
11640 Expr *result, QualType &paramType);
11641
11642 // CheckVectorCast - check type constraints for vectors.
11643 // Since vectors are an extension, there are no C standard reference for this.
11644 // We allow casting between vectors and integer datatypes of the same size.
11645 // returns true if the cast is invalid
11646 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
11647 CastKind &Kind);
11648
11649 /// Prepare `SplattedExpr` for a vector splat operation, adding
11650 /// implicit casts if necessary.
11651 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
11652
11653 // CheckExtVectorCast - check type constraints for extended vectors.
11654 // Since vectors are an extension, there are no C standard reference for this.
11655 // We allow casting between vectors and integer datatypes of the same size,
11656 // or vectors and the element type of that vector.
11657 // returns the cast expr
11658 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
11659 CastKind &Kind);
11660
11661 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
11662 SourceLocation LParenLoc,
11663 Expr *CastExpr,
11664 SourceLocation RParenLoc);
11665
11666 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
11667
11668 /// Checks for invalid conversions and casts between
11669 /// retainable pointers and other pointer kinds for ARC and Weak.
11670 ARCConversionResult CheckObjCConversion(SourceRange castRange,
11671 QualType castType, Expr *&op,
11672 CheckedConversionKind CCK,
11673 bool Diagnose = true,
11674 bool DiagnoseCFAudited = false,
11675 BinaryOperatorKind Opc = BO_PtrMemD
11676 );
11677
11678 Expr *stripARCUnbridgedCast(Expr *e);
11679 void diagnoseARCUnbridgedCast(Expr *e);
11680
11681 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
11682 QualType ExprType);
11683
11684 /// checkRetainCycles - Check whether an Objective-C message send
11685 /// might create an obvious retain cycle.
11686 void checkRetainCycles(ObjCMessageExpr *msg);
11687 void checkRetainCycles(Expr *receiver, Expr *argument);
11688 void checkRetainCycles(VarDecl *Var, Expr *Init);
11689
11690 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
11691 /// to weak/__unsafe_unretained type.
11692 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
11693
11694 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
11695 /// to weak/__unsafe_unretained expression.
11696 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
11697
11698 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
11699 /// \param Method - May be null.
11700 /// \param [out] ReturnType - The return type of the send.
11701 /// \return true iff there were any incompatible types.
11702 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
11703 MultiExprArg Args, Selector Sel,
11704 ArrayRef<SourceLocation> SelectorLocs,
11705 ObjCMethodDecl *Method, bool isClassMessage,
11706 bool isSuperMessage, SourceLocation lbrac,
11707 SourceLocation rbrac, SourceRange RecRange,
11708 QualType &ReturnType, ExprValueKind &VK);
11709
11710 /// Determine the result of a message send expression based on
11711 /// the type of the receiver, the method expected to receive the message,
11712 /// and the form of the message send.
11713 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
11714 ObjCMethodDecl *Method, bool isClassMessage,
11715 bool isSuperMessage);
11716
11717 /// If the given expression involves a message send to a method
11718 /// with a related result type, emit a note describing what happened.
11719 void EmitRelatedResultTypeNote(const Expr *E);
11720
11721 /// Given that we had incompatible pointer types in a return
11722 /// statement, check whether we're in a method with a related result
11723 /// type, and if so, emit a note describing what happened.
11724 void EmitRelatedResultTypeNoteForReturn(QualType destType);
11725
11726 class ConditionResult {
11727 Decl *ConditionVar;
11728 FullExprArg Condition;
11729 bool Invalid;
11730 bool HasKnownValue;
11731 bool KnownValue;
11732
11733 friend class Sema;
11734 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
11735 bool IsConstexpr)
11736 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
11737 HasKnownValue(IsConstexpr && Condition.get() &&
11738 !Condition.get()->isValueDependent()),
11739 KnownValue(HasKnownValue &&
11740 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
11741 explicit ConditionResult(bool Invalid)
11742 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
11743 HasKnownValue(false), KnownValue(false) {}
11744
11745 public:
11746 ConditionResult() : ConditionResult(false) {}
11747 bool isInvalid() const { return Invalid; }
11748 std::pair<VarDecl *, Expr *> get() const {
11749 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
11750 Condition.get());
11751 }
11752 llvm::Optional<bool> getKnownValue() const {
11753 if (!HasKnownValue)
11754 return None;
11755 return KnownValue;
11756 }
11757 };
11758 static ConditionResult ConditionError() { return ConditionResult(true); }
11759
11760 enum class ConditionKind {
11761 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
11762 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
11763 Switch ///< An integral condition for a 'switch' statement.
11764 };
11765
11766 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
11767 Expr *SubExpr, ConditionKind CK);
11768
11769 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
11770 SourceLocation StmtLoc,
11771 ConditionKind CK);
11772
11773 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
11774
11775 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
11776 SourceLocation StmtLoc,
11777 ConditionKind CK);
11778 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11779
11780 /// CheckBooleanCondition - Diagnose problems involving the use of
11781 /// the given expression as a boolean condition (e.g. in an if
11782 /// statement). Also performs the standard function and array
11783 /// decays, possibly changing the input variable.
11784 ///
11785 /// \param Loc - A location associated with the condition, e.g. the
11786 /// 'if' keyword.
11787 /// \return true iff there were any errors
11788 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
11789 bool IsConstexpr = false);
11790
11791 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
11792 /// found in an explicit(bool) specifier.
11793 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
11794
11795 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
11796 /// Returns true if the explicit specifier is now resolved.
11797 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
11798
11799 /// DiagnoseAssignmentAsCondition - Given that an expression is
11800 /// being used as a boolean condition, warn if it's an assignment.
11801 void DiagnoseAssignmentAsCondition(Expr *E);
11802
11803 /// Redundant parentheses over an equality comparison can indicate
11804 /// that the user intended an assignment used as condition.
11805 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
11806
11807 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
11808 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
11809
11810 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
11811 /// the specified width and sign. If an overflow occurs, detect it and emit
11812 /// the specified diagnostic.
11813 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
11814 unsigned NewWidth, bool NewSign,
11815 SourceLocation Loc, unsigned DiagID);
11816
11817 /// Checks that the Objective-C declaration is declared in the global scope.
11818 /// Emits an error and marks the declaration as invalid if it's not declared
11819 /// in the global scope.
11820 bool CheckObjCDeclScope(Decl *D);
11821
11822 /// Abstract base class used for diagnosing integer constant
11823 /// expression violations.
11824 class VerifyICEDiagnoser {
11825 public:
11826 bool Suppress;
11827
11828 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
11829
11830 virtual SemaDiagnosticBuilder
11831 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
11832 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
11833 SourceLocation Loc) = 0;
11834 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
11835 virtual ~VerifyICEDiagnoser() {}
11836 };
11837
11838 enum AllowFoldKind {
11839 NoFold,
11840 AllowFold,
11841 };
11842
11843 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
11844 /// and reports the appropriate diagnostics. Returns false on success.
11845 /// Can optionally return the value of the expression.
11846 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11847 VerifyICEDiagnoser &Diagnoser,
11848 AllowFoldKind CanFold = NoFold);
11849 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11850 unsigned DiagID,
11851 AllowFoldKind CanFold = NoFold);
11852 ExprResult VerifyIntegerConstantExpression(Expr *E,
11853 llvm::APSInt *Result = nullptr,
11854 AllowFoldKind CanFold = NoFold);
11855 ExprResult VerifyIntegerConstantExpression(Expr *E,
11856 AllowFoldKind CanFold = NoFold) {
11857 return VerifyIntegerConstantExpression(E, nullptr, CanFold);
11858 }
11859
11860 /// VerifyBitField - verifies that a bit field expression is an ICE and has
11861 /// the correct width, and that the field type is valid.
11862 /// Returns false on success.
11863 /// Can optionally return whether the bit-field is of width 0
11864 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
11865 QualType FieldTy, bool IsMsStruct,
11866 Expr *BitWidth, bool *ZeroWidth = nullptr);
11867
11868private:
11869 unsigned ForceCUDAHostDeviceDepth = 0;
11870
11871public:
11872 /// Increments our count of the number of times we've seen a pragma forcing
11873 /// functions to be __host__ __device__. So long as this count is greater
11874 /// than zero, all functions encountered will be __host__ __device__.
11875 void PushForceCUDAHostDevice();
11876
11877 /// Decrements our count of the number of times we've seen a pragma forcing
11878 /// functions to be __host__ __device__. Returns false if the count is 0
11879 /// before incrementing, so you can emit an error.
11880 bool PopForceCUDAHostDevice();
11881
11882 /// Diagnostics that are emitted only if we discover that the given function
11883 /// must be codegen'ed. Because handling these correctly adds overhead to
11884 /// compilation, this is currently only enabled for CUDA compilations.
11885 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
11886 std::vector<PartialDiagnosticAt>>
11887 DeviceDeferredDiags;
11888
11889 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
11890 /// key in a hashtable, both the FD and location are hashed.
11891 struct FunctionDeclAndLoc {
11892 CanonicalDeclPtr<FunctionDecl> FD;
11893 SourceLocation Loc;
11894 };
11895
11896 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
11897 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
11898 /// same deferred diag twice.
11899 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
11900
11901 /// An inverse call graph, mapping known-emitted functions to one of their
11902 /// known-emitted callers (plus the location of the call).
11903 ///
11904 /// Functions that we can tell a priori must be emitted aren't added to this
11905 /// map.
11906 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
11907 /* Caller = */ FunctionDeclAndLoc>
11908 DeviceKnownEmittedFns;
11909
11910 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
11911 /// context is "used as device code".
11912 ///
11913 /// - If CurContext is a __host__ function, does not emit any diagnostics
11914 /// unless \p EmitOnBothSides is true.
11915 /// - If CurContext is a __device__ or __global__ function, emits the
11916 /// diagnostics immediately.
11917 /// - If CurContext is a __host__ __device__ function and we are compiling for
11918 /// the device, creates a diagnostic which is emitted if and when we realize
11919 /// that the function will be codegen'ed.
11920 ///
11921 /// Example usage:
11922 ///
11923 /// // Variable-length arrays are not allowed in CUDA device code.
11924 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
11925 /// return ExprError();
11926 /// // Otherwise, continue parsing as normal.
11927 SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
11928 unsigned DiagID);
11929
11930 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
11931 /// context is "used as host code".
11932 ///
11933 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
11934 SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
11935
11936 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
11937 /// context is "used as device code".
11938 ///
11939 /// - If CurContext is a `declare target` function or it is known that the
11940 /// function is emitted for the device, emits the diagnostics immediately.
11941 /// - If CurContext is a non-`declare target` function and we are compiling
11942 /// for the device, creates a diagnostic which is emitted if and when we
11943 /// realize that the function will be codegen'ed.
11944 ///
11945 /// Example usage:
11946 ///
11947 /// // Variable-length arrays are not allowed in NVPTX device code.
11948 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
11949 /// return ExprError();
11950 /// // Otherwise, continue parsing as normal.
11951 SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc,
11952 unsigned DiagID);
11953
11954 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
11955 /// context is "used as host code".
11956 ///
11957 /// - If CurContext is a `declare target` function or it is known that the
11958 /// function is emitted for the host, emits the diagnostics immediately.
11959 /// - If CurContext is a non-host function, just ignore it.
11960 ///
11961 /// Example usage:
11962 ///
11963 /// // Variable-length arrays are not allowed in NVPTX device code.
11964 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
11965 /// return ExprError();
11966 /// // Otherwise, continue parsing as normal.
11967 SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
11968 unsigned DiagID);
11969
11970 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
11971 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
11972 const PartialDiagnostic &PD) {
11973 return targetDiag(Loc, PD.getDiagID()) << PD;
11974 }
11975
11976 /// Check if the expression is allowed to be used in expressions for the
11977 /// offloading devices.
11978 void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc);
11979
11980 enum CUDAFunctionTarget {
11981 CFT_Device,
11982 CFT_Global,
11983 CFT_Host,
11984 CFT_HostDevice,
11985 CFT_InvalidTarget
11986 };
11987
11988 /// Determines whether the given function is a CUDA device/host/kernel/etc.
11989 /// function.
11990 ///
11991 /// Use this rather than examining the function's attributes yourself -- you
11992 /// will get it wrong. Returns CFT_Host if D is null.
11993 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
11994 bool IgnoreImplicitHDAttr = false);
11995 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
11996
11997 /// Gets the CUDA target for the current context.
11998 CUDAFunctionTarget CurrentCUDATarget() {
11999 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
12000 }
12001
12002 static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
12003
12004 // CUDA function call preference. Must be ordered numerically from
12005 // worst to best.
12006 enum CUDAFunctionPreference {
12007 CFP_Never, // Invalid caller/callee combination.
12008 CFP_WrongSide, // Calls from host-device to host or device
12009 // function that do not match current compilation
12010 // mode.
12011 CFP_HostDevice, // Any calls to host/device functions.
12012 CFP_SameSide, // Calls from host-device to host or device
12013 // function matching current compilation mode.
12014 CFP_Native, // host-to-host or device-to-device calls.
12015 };
12016
12017 /// Identifies relative preference of a given Caller/Callee
12018 /// combination, based on their host/device attributes.
12019 /// \param Caller function which needs address of \p Callee.
12020 /// nullptr in case of global context.
12021 /// \param Callee target function
12022 ///
12023 /// \returns preference value for particular Caller/Callee combination.
12024 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
12025 const FunctionDecl *Callee);
12026
12027 /// Determines whether Caller may invoke Callee, based on their CUDA
12028 /// host/device attributes. Returns false if the call is not allowed.
12029 ///
12030 /// Note: Will return true for CFP_WrongSide calls. These may appear in
12031 /// semantically correct CUDA programs, but only if they're never codegen'ed.
12032 bool IsAllowedCUDACall(const FunctionDecl *Caller,
12033 const FunctionDecl *Callee) {
12034 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
12035 }
12036
12037 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
12038 /// depending on FD and the current compilation settings.
12039 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
12040 const LookupResult &Previous);
12041
12042 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
12043 /// and current compilation settings.
12044 void MaybeAddCUDAConstantAttr(VarDecl *VD);
12045
12046public:
12047 /// Check whether we're allowed to call Callee from the current context.
12048 ///
12049 /// - If the call is never allowed in a semantically-correct program
12050 /// (CFP_Never), emits an error and returns false.
12051 ///
12052 /// - If the call is allowed in semantically-correct programs, but only if
12053 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
12054 /// be emitted if and when the caller is codegen'ed, and returns true.
12055 ///
12056 /// Will only create deferred diagnostics for a given SourceLocation once,
12057 /// so you can safely call this multiple times without generating duplicate
12058 /// deferred errors.
12059 ///
12060 /// - Otherwise, returns true without emitting any diagnostics.
12061 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
12062
12063 void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
12064
12065 /// Set __device__ or __host__ __device__ attributes on the given lambda
12066 /// operator() method.
12067 ///
12068 /// CUDA lambdas by default is host device function unless it has explicit
12069 /// host or device attribute.
12070 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
12071
12072 /// Finds a function in \p Matches with highest calling priority
12073 /// from \p Caller context and erases all functions with lower
12074 /// calling priority.
12075 void EraseUnwantedCUDAMatches(
12076 const FunctionDecl *Caller,
12077 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
12078
12079 /// Given a implicit special member, infer its CUDA target from the
12080 /// calls it needs to make to underlying base/field special members.
12081 /// \param ClassDecl the class for which the member is being created.
12082 /// \param CSM the kind of special member.
12083 /// \param MemberDecl the special member itself.
12084 /// \param ConstRHS true if this is a copy operation with a const object on
12085 /// its RHS.
12086 /// \param Diagnose true if this call should emit diagnostics.
12087 /// \return true if there was an error inferring.
12088 /// The result of this call is implicit CUDA target attribute(s) attached to
12089 /// the member declaration.
12090 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
12091 CXXSpecialMember CSM,
12092 CXXMethodDecl *MemberDecl,
12093 bool ConstRHS,
12094 bool Diagnose);
12095
12096 /// \return true if \p CD can be considered empty according to CUDA
12097 /// (E.2.3.1 in CUDA 7.5 Programming guide).
12098 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
12099 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
12100
12101 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
12102 // case of error emits appropriate diagnostic and invalidates \p Var.
12103 //
12104 // \details CUDA allows only empty constructors as initializers for global
12105 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
12106 // __shared__ variables whether they are local or not (they all are implicitly
12107 // static in CUDA). One exception is that CUDA allows constant initializers
12108 // for __constant__ and __device__ variables.
12109 void checkAllowedCUDAInitializer(VarDecl *VD);
12110
12111 /// Check whether NewFD is a valid overload for CUDA. Emits
12112 /// diagnostics and invalidates NewFD if not.
12113 void checkCUDATargetOverload(FunctionDecl *NewFD,
12114 const LookupResult &Previous);
12115 /// Copies target attributes from the template TD to the function FD.
12116 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
12117
12118 /// Returns the name of the launch configuration function. This is the name
12119 /// of the function that will be called to configure kernel call, with the
12120 /// parameters specified via <<<>>>.
12121 std::string getCudaConfigureFuncName() const;
12122
12123 /// \name Code completion
12124 //@{
12125 /// Describes the context in which code completion occurs.
12126 enum ParserCompletionContext {
12127 /// Code completion occurs at top-level or namespace context.
12128 PCC_Namespace,
12129 /// Code completion occurs within a class, struct, or union.
12130 PCC_Class,
12131 /// Code completion occurs within an Objective-C interface, protocol,
12132 /// or category.
12133 PCC_ObjCInterface,
12134 /// Code completion occurs within an Objective-C implementation or
12135 /// category implementation
12136 PCC_ObjCImplementation,
12137 /// Code completion occurs within the list of instance variables
12138 /// in an Objective-C interface, protocol, category, or implementation.
12139 PCC_ObjCInstanceVariableList,
12140 /// Code completion occurs following one or more template
12141 /// headers.
12142 PCC_Template,
12143 /// Code completion occurs following one or more template
12144 /// headers within a class.
12145 PCC_MemberTemplate,
12146 /// Code completion occurs within an expression.
12147 PCC_Expression,
12148 /// Code completion occurs within a statement, which may
12149 /// also be an expression or a declaration.
12150 PCC_Statement,
12151 /// Code completion occurs at the beginning of the
12152 /// initialization statement (or expression) in a for loop.
12153 PCC_ForInit,
12154 /// Code completion occurs within the condition of an if,
12155 /// while, switch, or for statement.
12156 PCC_Condition,
12157 /// Code completion occurs within the body of a function on a
12158 /// recovery path, where we do not have a specific handle on our position
12159 /// in the grammar.
12160 PCC_RecoveryInFunction,
12161 /// Code completion occurs where only a type is permitted.
12162 PCC_Type,
12163 /// Code completion occurs in a parenthesized expression, which
12164 /// might also be a type cast.
12165 PCC_ParenthesizedExpression,
12166 /// Code completion occurs within a sequence of declaration
12167 /// specifiers within a function, method, or block.
12168 PCC_LocalDeclarationSpecifiers
12169 };
12170
12171 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
12172 void CodeCompleteOrdinaryName(Scope *S,
12173 ParserCompletionContext CompletionContext);
12174 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
12175 bool AllowNonIdentifiers,
12176 bool AllowNestedNameSpecifiers);
12177
12178 struct CodeCompleteExpressionData;
12179 void CodeCompleteExpression(Scope *S,
12180 const CodeCompleteExpressionData &Data);
12181 void CodeCompleteExpression(Scope *S, QualType PreferredType,
12182 bool IsParenthesized = false);
12183 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
12184 SourceLocation OpLoc, bool IsArrow,
12185 bool IsBaseExprStatement,
12186 QualType PreferredType);
12187 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
12188 QualType PreferredType);
12189 void CodeCompleteTag(Scope *S, unsigned TagSpec);
12190 void CodeCompleteTypeQualifiers(DeclSpec &DS);
12191 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
12192 const VirtSpecifiers *VS = nullptr);
12193 void CodeCompleteBracketDeclarator(Scope *S);
12194 void CodeCompleteCase(Scope *S);
12195 /// Reports signatures for a call to CodeCompleteConsumer and returns the
12196 /// preferred type for the current argument. Returned type can be null.
12197 QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
12198 SourceLocation OpenParLoc);
12199 QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
12200 SourceLocation Loc,
12201 ArrayRef<Expr *> Args,
12202 SourceLocation OpenParLoc);
12203 QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
12204 CXXScopeSpec SS,
12205 ParsedType TemplateTypeTy,
12206 ArrayRef<Expr *> ArgExprs,
12207 IdentifierInfo *II,
12208 SourceLocation OpenParLoc);
12209 void CodeCompleteInitializer(Scope *S, Decl *D);
12210 /// Trigger code completion for a record of \p BaseType. \p InitExprs are
12211 /// expressions in the initializer list seen so far and \p D is the current
12212 /// Designation being parsed.
12213 void CodeCompleteDesignator(const QualType BaseType,
12214 llvm::ArrayRef<Expr *> InitExprs,
12215 const Designation &D);
12216 void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
12217
12218 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
12219 bool IsUsingDeclaration, QualType BaseType,
12220 QualType PreferredType);
12221 void CodeCompleteUsing(Scope *S);
12222 void CodeCompleteUsingDirective(Scope *S);
12223 void CodeCompleteNamespaceDecl(Scope *S);
12224 void CodeCompleteNamespaceAliasDecl(Scope *S);
12225 void CodeCompleteOperatorName(Scope *S);
12226 void CodeCompleteConstructorInitializer(
12227 Decl *Constructor,
12228 ArrayRef<CXXCtorInitializer *> Initializers);
12229
12230 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
12231 bool AfterAmpersand);
12232 void CodeCompleteAfterFunctionEquals(Declarator &D);
12233
12234 void CodeCompleteObjCAtDirective(Scope *S);
12235 void CodeCompleteObjCAtVisibility(Scope *S);
12236 void CodeCompleteObjCAtStatement(Scope *S);
12237 void CodeCompleteObjCAtExpression(Scope *S);
12238 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
12239 void CodeCompleteObjCPropertyGetter(Scope *S);
12240 void CodeCompleteObjCPropertySetter(Scope *S);
12241 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
12242 bool IsParameter);
12243 void CodeCompleteObjCMessageReceiver(Scope *S);
12244 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
12245 ArrayRef<IdentifierInfo *> SelIdents,
12246 bool AtArgumentExpression);
12247 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
12248 ArrayRef<IdentifierInfo *> SelIdents,
12249 bool AtArgumentExpression,
12250 bool IsSuper = false);
12251 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
12252 ArrayRef<IdentifierInfo *> SelIdents,
12253 bool AtArgumentExpression,
12254 ObjCInterfaceDecl *Super = nullptr);
12255 void CodeCompleteObjCForCollection(Scope *S,
12256 DeclGroupPtrTy IterationVar);
12257 void CodeCompleteObjCSelector(Scope *S,
12258 ArrayRef<IdentifierInfo *> SelIdents);
12259 void CodeCompleteObjCProtocolReferences(
12260 ArrayRef<IdentifierLocPair> Protocols);
12261 void CodeCompleteObjCProtocolDecl(Scope *S);
12262 void CodeCompleteObjCInterfaceDecl(Scope *S);
12263 void CodeCompleteObjCSuperclass(Scope *S,
12264 IdentifierInfo *ClassName,
12265 SourceLocation ClassNameLoc);
12266 void CodeCompleteObjCImplementationDecl(Scope *S);
12267 void CodeCompleteObjCInterfaceCategory(Scope *S,
12268 IdentifierInfo *ClassName,
12269 SourceLocation ClassNameLoc);
12270 void CodeCompleteObjCImplementationCategory(Scope *S,
12271 IdentifierInfo *ClassName,
12272 SourceLocation ClassNameLoc);
12273 void CodeCompleteObjCPropertyDefinition(Scope *S);
12274 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
12275 IdentifierInfo *PropertyName);
12276 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
12277 ParsedType ReturnType);
12278 void CodeCompleteObjCMethodDeclSelector(Scope *S,
12279 bool IsInstanceMethod,
12280 bool AtParameterName,
12281 ParsedType ReturnType,
12282 ArrayRef<IdentifierInfo *> SelIdents);
12283 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
12284 SourceLocation ClassNameLoc,
12285 bool IsBaseExprStatement);
12286 void CodeCompletePreprocessorDirective(bool InConditional);
12287 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
12288 void CodeCompletePreprocessorMacroName(bool IsDefinition);
12289 void CodeCompletePreprocessorExpression();
12290 void CodeCompletePreprocessorMacroArgument(Scope *S,
12291 IdentifierInfo *Macro,
12292 MacroInfo *MacroInfo,
12293 unsigned Argument);
12294 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
12295 void CodeCompleteNaturalLanguage();
12296 void CodeCompleteAvailabilityPlatformName();
12297 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
12298 CodeCompletionTUInfo &CCTUInfo,
12299 SmallVectorImpl<CodeCompletionResult> &Results);
12300 //@}
12301
12302 //===--------------------------------------------------------------------===//
12303 // Extra semantic analysis beyond the C type system
12304
12305public:
12306 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
12307 unsigned ByteNo) const;
12308
12309private:
12310 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12311 const ArraySubscriptExpr *ASE=nullptr,
12312 bool AllowOnePastEnd=true, bool IndexNegated=false);
12313 void CheckArrayAccess(const Expr *E);
12314 // Used to grab the relevant information from a FormatAttr and a
12315 // FunctionDeclaration.
12316 struct FormatStringInfo {
12317 unsigned FormatIdx;
12318 unsigned FirstDataArg;
12319 bool HasVAListArg;
12320 };
12321
12322 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
12323 FormatStringInfo *FSI);
12324 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
12325 const FunctionProtoType *Proto);
12326 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
12327 ArrayRef<const Expr *> Args);
12328 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
12329 const FunctionProtoType *Proto);
12330 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
12331 void CheckConstructorCall(FunctionDecl *FDecl,
12332 ArrayRef<const Expr *> Args,
12333 const FunctionProtoType *Proto,
12334 SourceLocation Loc);
12335
12336 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
12337 const Expr *ThisArg, ArrayRef<const Expr *> Args,
12338 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
12339 VariadicCallType CallType);
12340
12341 bool CheckObjCString(Expr *Arg);
12342 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
12343
12344 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
12345 unsigned BuiltinID, CallExpr *TheCall);
12346
12347 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12348 CallExpr *TheCall);
12349
12350 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
12351
12352 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
12353 unsigned MaxWidth);
12354 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12355 CallExpr *TheCall);
12356 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12357 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12358 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12359 CallExpr *TheCall);
12360 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
12361 bool WantCDE);
12362 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12363 CallExpr *TheCall);
12364
12365 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12366 CallExpr *TheCall);
12367 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12368 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12369 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12370 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12371 CallExpr *TheCall);
12372 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
12373 CallExpr *TheCall);
12374 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12375 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12376 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
12377 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
12378 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
12379 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
12380 ArrayRef<int> ArgNums);
12381 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
12382 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
12383 ArrayRef<int> ArgNums);
12384 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12385 CallExpr *TheCall);
12386 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12387 CallExpr *TheCall);
12388 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12389
12390 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
12391 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
12392 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
12393 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
12394 bool SemaBuiltinComplex(CallExpr *TheCall);
12395 bool SemaBuiltinVSX(CallExpr *TheCall);
12396 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
12397
12398public:
12399 // Used by C++ template instantiation.
12400 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
12401 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
12402 SourceLocation BuiltinLoc,
12403 SourceLocation RParenLoc);
12404
12405private:
12406 bool SemaBuiltinPrefetch(CallExpr *TheCall);
12407 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
12408 bool SemaBuiltinAssume(CallExpr *TheCall);
12409 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
12410 bool SemaBuiltinLongjmp(CallExpr *TheCall);
12411 bool SemaBuiltinSetjmp(CallExpr *TheCall);
12412 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
12413 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
12414 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
12415 AtomicExpr::AtomicOp Op);
12416 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
12417 bool IsDelete);
12418 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
12419 llvm::APSInt &Result);
12420 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
12421 int High, bool RangeIsError = true);
12422 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
12423 unsigned Multiple);
12424 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
12425 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
12426 unsigned ArgBits);
12427 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
12428 unsigned ArgBits);
12429 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
12430 int ArgNum, unsigned ExpectedFieldNum,
12431 bool AllowName);
12432 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
12433 bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc);
12434
12435 bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
12436
12437 // Matrix builtin handling.
12438 ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
12439 ExprResult CallResult);
12440 ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
12441 ExprResult CallResult);
12442 ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
12443 ExprResult CallResult);
12444
12445public:
12446 enum FormatStringType {
12447 FST_Scanf,
12448 FST_Printf,
12449 FST_NSString,
12450 FST_Strftime,
12451 FST_Strfmon,
12452 FST_Kprintf,
12453 FST_FreeBSDKPrintf,
12454 FST_OSTrace,
12455 FST_OSLog,
12456 FST_Unknown
12457 };
12458 static FormatStringType GetFormatStringType(const FormatAttr *Format);
12459
12460 bool FormatStringHasSArg(const StringLiteral *FExpr);
12461
12462 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
12463
12464private:
12465 bool CheckFormatArguments(const FormatAttr *Format,
12466 ArrayRef<const Expr *> Args,
12467 bool IsCXXMember,
12468 VariadicCallType CallType,
12469 SourceLocation Loc, SourceRange Range,
12470 llvm::SmallBitVector &CheckedVarArgs);
12471 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
12472 bool HasVAListArg, unsigned format_idx,
12473 unsigned firstDataArg, FormatStringType Type,
12474 VariadicCallType CallType,
12475 SourceLocation Loc, SourceRange range,
12476 llvm::SmallBitVector &CheckedVarArgs);
12477
12478 void CheckAbsoluteValueFunction(const CallExpr *Call,
12479 const FunctionDecl *FDecl);
12480
12481 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
12482
12483 void CheckMemaccessArguments(const CallExpr *Call,
12484 unsigned BId,
12485 IdentifierInfo *FnName);
12486
12487 void CheckStrlcpycatArguments(const CallExpr *Call,
12488 IdentifierInfo *FnName);
12489
12490 void CheckStrncatArguments(const CallExpr *Call,
12491 IdentifierInfo *FnName);
12492
12493 void CheckFreeArguments(const CallExpr *E);
12494
12495 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
12496 SourceLocation ReturnLoc,
12497 bool isObjCMethod = false,
12498 const AttrVec *Attrs = nullptr,
12499 const FunctionDecl *FD = nullptr);
12500
12501public:
12502 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
12503
12504private:
12505 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
12506 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
12507 void CheckForIntOverflow(Expr *E);
12508 void CheckUnsequencedOperations(const Expr *E);
12509
12510 /// Perform semantic checks on a completed expression. This will either
12511 /// be a full-expression or a default argument expression.
12512 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
12513 bool IsConstexpr = false);
12514
12515 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
12516 Expr *Init);
12517
12518 /// Check if there is a field shadowing.
12519 void CheckShadowInheritedFields(const SourceLocation &Loc,
12520 DeclarationName FieldName,
12521 const CXXRecordDecl *RD,
12522 bool DeclIsField = true);
12523
12524 /// Check if the given expression contains 'break' or 'continue'
12525 /// statement that produces control flow different from GCC.
12526 void CheckBreakContinueBinding(Expr *E);
12527
12528 /// Check whether receiver is mutable ObjC container which
12529 /// attempts to add itself into the container
12530 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
12531
12532 void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee);
12533
12534 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
12535 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
12536 bool DeleteWasArrayForm);
12537public:
12538 /// Register a magic integral constant to be used as a type tag.
12539 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12540 uint64_t MagicValue, QualType Type,
12541 bool LayoutCompatible, bool MustBeNull);
12542
12543 struct TypeTagData {
12544 TypeTagData() {}
12545
12546 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
12547 Type(Type), LayoutCompatible(LayoutCompatible),
12548 MustBeNull(MustBeNull)
12549 {}
12550
12551 QualType Type;
12552
12553 /// If true, \c Type should be compared with other expression's types for
12554 /// layout-compatibility.
12555 unsigned LayoutCompatible : 1;
12556 unsigned MustBeNull : 1;
12557 };
12558
12559 /// A pair of ArgumentKind identifier and magic value. This uniquely
12560 /// identifies the magic value.
12561 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
12562
12563private:
12564 /// A map from magic value to type information.
12565 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
12566 TypeTagForDatatypeMagicValues;
12567
12568 /// Peform checks on a call of a function with argument_with_type_tag
12569 /// or pointer_with_type_tag attributes.
12570 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12571 const ArrayRef<const Expr *> ExprArgs,
12572 SourceLocation CallSiteLoc);
12573
12574 /// Check if we are taking the address of a packed field
12575 /// as this may be a problem if the pointer value is dereferenced.
12576 void CheckAddressOfPackedMember(Expr *rhs);
12577
12578 /// The parser's current scope.
12579 ///
12580 /// The parser maintains this state here.
12581 Scope *CurScope;
12582
12583 mutable IdentifierInfo *Ident_super;
12584 mutable IdentifierInfo *Ident___float128;
12585
12586 /// Nullability type specifiers.
12587 IdentifierInfo *Ident__Nonnull = nullptr;
12588 IdentifierInfo *Ident__Nullable = nullptr;
12589 IdentifierInfo *Ident__Nullable_result = nullptr;
12590 IdentifierInfo *Ident__Null_unspecified = nullptr;
12591
12592 IdentifierInfo *Ident_NSError = nullptr;
12593
12594 /// The handler for the FileChanged preprocessor events.
12595 ///
12596 /// Used for diagnostics that implement custom semantic analysis for #include
12597 /// directives, like -Wpragma-pack.
12598 sema::SemaPPCallbacks *SemaPPCallbackHandler;
12599
12600protected:
12601 friend class Parser;
12602 friend class InitializationSequence;
12603 friend class ASTReader;
12604 friend class ASTDeclReader;
12605 friend class ASTWriter;
12606
12607public:
12608 /// Retrieve the keyword associated
12609 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
12610
12611 /// The struct behind the CFErrorRef pointer.
12612 RecordDecl *CFError = nullptr;
12613 bool isCFError(RecordDecl *D);
12614
12615 /// Retrieve the identifier "NSError".
12616 IdentifierInfo *getNSErrorIdent();
12617
12618 /// Retrieve the parser's current scope.
12619 ///
12620 /// This routine must only be used when it is certain that semantic analysis
12621 /// and the parser are in precisely the same context, which is not the case
12622 /// when, e.g., we are performing any kind of template instantiation.
12623 /// Therefore, the only safe places to use this scope are in the parser
12624 /// itself and in routines directly invoked from the parser and *never* from
12625 /// template substitution or instantiation.
12626 Scope *getCurScope() const { return CurScope; }
12627
12628 void incrementMSManglingNumber() const {
12629 return CurScope->incrementMSManglingNumber();
12630 }
12631
12632 IdentifierInfo *getSuperIdentifier() const;
12633 IdentifierInfo *getFloat128Identifier() const;
12634
12635 Decl *getObjCDeclContext() const;
12636
12637 DeclContext *getCurLexicalContext() const {
12638 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
12639 }
12640
12641 const DeclContext *getCurObjCLexicalContext() const {
12642 const DeclContext *DC = getCurLexicalContext();
12643 // A category implicitly has the attribute of the interface.
12644 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
12645 DC = CatD->getClassInterface();
12646 return DC;
12647 }
12648
12649 /// Determine the number of levels of enclosing template parameters. This is
12650 /// only usable while parsing. Note that this does not include dependent
12651 /// contexts in which no template parameters have yet been declared, such as
12652 /// in a terse function template or generic lambda before the first 'auto' is
12653 /// encountered.
12654 unsigned getTemplateDepth(Scope *S) const;
12655
12656 /// To be used for checking whether the arguments being passed to
12657 /// function exceeds the number of parameters expected for it.
12658 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
12659 bool PartialOverloading = false) {
12660 // We check whether we're just after a comma in code-completion.
12661 if (NumArgs > 0 && PartialOverloading)
12662 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
12663 return NumArgs > NumParams;
12664 }
12665
12666 // Emitting members of dllexported classes is delayed until the class
12667 // (including field initializers) is fully parsed.
12668 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
12669 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
12670
12671private:
12672 int ParsingClassDepth = 0;
12673
12674 class SavePendingParsedClassStateRAII {
12675 public:
12676 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
12677
12678 ~SavePendingParsedClassStateRAII() {
12679 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 12680, __PRETTY_FUNCTION__))
12680 "there shouldn't be any pending delayed exception spec checks")((S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 12680, __PRETTY_FUNCTION__))
;
12681 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 12682, __PRETTY_FUNCTION__))
12682 "there shouldn't be any pending delayed exception spec checks")((S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "/build/llvm-toolchain-snapshot-12~++20210125100614+2cdb34efdac5/clang/include/clang/Sema/Sema.h"
, 12682, __PRETTY_FUNCTION__))
;
12683 swapSavedState();
12684 }
12685
12686 private:
12687 Sema &S;
12688 decltype(DelayedOverridingExceptionSpecChecks)
12689 SavedOverridingExceptionSpecChecks;
12690 decltype(DelayedEquivalentExceptionSpecChecks)
12691 SavedEquivalentExceptionSpecChecks;
12692
12693 void swapSavedState() {
12694 SavedOverridingExceptionSpecChecks.swap(
12695 S.DelayedOverridingExceptionSpecChecks);
12696 SavedEquivalentExceptionSpecChecks.swap(
12697 S.DelayedEquivalentExceptionSpecChecks);
12698 }
12699 };
12700
12701 /// Helper class that collects misaligned member designations and
12702 /// their location info for delayed diagnostics.
12703 struct MisalignedMember {
12704 Expr *E;
12705 RecordDecl *RD;
12706 ValueDecl *MD;
12707 CharUnits Alignment;
12708
12709 MisalignedMember() : E(), RD(), MD(), Alignment() {}
12710 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
12711 CharUnits Alignment)
12712 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
12713 explicit MisalignedMember(Expr *E)
12714 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
12715
12716 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
12717 };
12718 /// Small set of gathered accesses to potentially misaligned members
12719 /// due to the packed attribute.
12720 SmallVector<MisalignedMember, 4> MisalignedMembers;
12721
12722 /// Adds an expression to the set of gathered misaligned members.
12723 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12724 CharUnits Alignment);
12725
12726public:
12727 /// Diagnoses the current set of gathered accesses. This typically
12728 /// happens at full expression level. The set is cleared after emitting the
12729 /// diagnostics.
12730 void DiagnoseMisalignedMembers();
12731
12732 /// This function checks if the expression is in the sef of potentially
12733 /// misaligned members and it is converted to some pointer type T with lower
12734 /// or equal alignment requirements. If so it removes it. This is used when
12735 /// we do not want to diagnose such misaligned access (e.g. in conversions to
12736 /// void*).
12737 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
12738
12739 /// This function calls Action when it determines that E designates a
12740 /// misaligned member due to the packed attribute. This is used to emit
12741 /// local diagnostics like in reference binding.
12742 void RefersToMemberWithReducedAlignment(
12743 Expr *E,
12744 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12745 Action);
12746
12747 /// Describes the reason a calling convention specification was ignored, used
12748 /// for diagnostics.
12749 enum class CallingConventionIgnoredReason {
12750 ForThisTarget = 0,
12751 VariadicFunction,
12752 ConstructorDestructor,
12753 BuiltinFunction
12754 };
12755 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12756 /// context is "used as device code".
12757 ///
12758 /// - If CurLexicalContext is a kernel function or it is known that the
12759 /// function will be emitted for the device, emits the diagnostics
12760 /// immediately.
12761 /// - If CurLexicalContext is a function and we are compiling
12762 /// for the device, but we don't know that this function will be codegen'ed
12763 /// for devive yet, creates a diagnostic which is emitted if and when we
12764 /// realize that the function will be codegen'ed.
12765 ///
12766 /// Example usage:
12767 ///
12768 /// Diagnose __float128 type usage only from SYCL device code if the current
12769 /// target doesn't support it
12770 /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
12771 /// S.getLangOpts().SYCLIsDevice)
12772 /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
12773 SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
12774 unsigned DiagID);
12775
12776 /// Check whether we're allowed to call Callee from the current context.
12777 ///
12778 /// - If the call is never allowed in a semantically-correct program
12779 /// emits an error and returns false.
12780 ///
12781 /// - If the call is allowed in semantically-correct programs, but only if
12782 /// it's never codegen'ed, creates a deferred diagnostic to be emitted if
12783 /// and when the caller is codegen'ed, and returns true.
12784 ///
12785 /// - Otherwise, returns true without emitting any diagnostics.
12786 ///
12787 /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
12788 /// codegen'ed yet.
12789 bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
12790};
12791
12792/// RAII object that enters a new expression evaluation context.
12793class EnterExpressionEvaluationContext {
12794 Sema &Actions;
12795 bool Entered = true;
12796
12797public:
12798 EnterExpressionEvaluationContext(
12799 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12800 Decl *LambdaContextDecl = nullptr,
12801 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12802 Sema::ExpressionEvaluationContextRecord::EK_Other,
12803 bool ShouldEnter = true)
12804 : Actions(Actions), Entered(ShouldEnter) {
12805 if (Entered)
12806 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
12807 ExprContext);
12808 }
12809 EnterExpressionEvaluationContext(
12810 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12811 Sema::ReuseLambdaContextDecl_t,
12812 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12813 Sema::ExpressionEvaluationContextRecord::EK_Other)
12814 : Actions(Actions) {
12815 Actions.PushExpressionEvaluationContext(
12816 NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
12817 }
12818
12819 enum InitListTag { InitList };
12820 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
12821 bool ShouldEnter = true)
12822 : Actions(Actions), Entered(false) {
12823 // In C++11 onwards, narrowing checks are performed on the contents of
12824 // braced-init-lists, even when they occur within unevaluated operands.
12825 // Therefore we still need to instantiate constexpr functions used in such
12826 // a context.
12827 if (ShouldEnter && Actions.isUnevaluatedContext() &&
12828 Actions.getLangOpts().CPlusPlus11) {
12829 Actions.PushExpressionEvaluationContext(
12830 Sema::ExpressionEvaluationContext::UnevaluatedList);
12831 Entered = true;
12832 }
12833 }
12834
12835 ~EnterExpressionEvaluationContext() {
12836 if (Entered)
12837 Actions.PopExpressionEvaluationContext();
12838 }
12839};
12840
12841DeductionFailureInfo
12842MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
12843 sema::TemplateDeductionInfo &Info);
12844
12845/// Contains a late templated function.
12846/// Will be parsed at the end of the translation unit, used by Sema & Parser.
12847struct LateParsedTemplate {
12848 CachedTokens Toks;
12849 /// The template function declaration to be late parsed.
12850 Decl *D;
12851};
12852
12853template <>
12854void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
12855 PragmaMsStackAction Action,
12856 llvm::StringRef StackSlotLabel,
12857 AlignPackInfo Value);
12858
12859} // end namespace clang
12860
12861namespace llvm {
12862// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
12863// SourceLocation.
12864template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
12865 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
12866 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
12867
12868 static FunctionDeclAndLoc getEmptyKey() {
12869 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
12870 }
12871
12872 static FunctionDeclAndLoc getTombstoneKey() {
12873 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
12874 }
12875
12876 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
12877 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
12878 FDL.Loc.getHashValue());
12879 }
12880
12881 static bool isEqual(const FunctionDeclAndLoc &LHS,
12882 const FunctionDeclAndLoc &RHS) {
12883 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
12884 }
12885};
12886} // namespace llvm
12887
12888#endif