Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp

1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Sema/Overload.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeOrdering.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/DiagnosticOptions.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/Optional.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallString.h"
35#include <algorithm>
36#include <cstdlib>
37
38using namespace clang;
39using namespace sema;
40
41static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
44 });
45}
46
47/// A convenience routine for creating a decayed reference to a function.
48static ExprResult
49CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 const Expr *Base, bool HadMultipleCandidates,
51 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54 return ExprError();
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
57 // called on both.
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60 // being used.
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62 return ExprError();
63 DeclRefExpr *DRE = new (S.Context)
64 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
65 if (HadMultipleCandidates)
66 DRE->setHadMultipleCandidates(true);
67
68 S.MarkDeclRefReferenced(DRE, Base);
69 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
70 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
71 S.ResolveExceptionSpec(Loc, FPT);
72 DRE->setType(Fn->getType());
73 }
74 }
75 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
76 CK_FunctionToPointerDecay);
77}
78
79static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
82 bool CStyle,
83 bool AllowObjCWritebackConversion);
84
85static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
86 QualType &ToType,
87 bool InOverloadResolution,
88 StandardConversionSequence &SCS,
89 bool CStyle);
90static OverloadingResult
91IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
92 UserDefinedConversionSequence& User,
93 OverloadCandidateSet& Conversions,
94 bool AllowExplicit,
95 bool AllowObjCConversionOnExplicit);
96
97
98static ImplicitConversionSequence::CompareKind
99CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
100 const StandardConversionSequence& SCS1,
101 const StandardConversionSequence& SCS2);
102
103static ImplicitConversionSequence::CompareKind
104CompareQualificationConversions(Sema &S,
105 const StandardConversionSequence& SCS1,
106 const StandardConversionSequence& SCS2);
107
108static ImplicitConversionSequence::CompareKind
109CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
110 const StandardConversionSequence& SCS1,
111 const StandardConversionSequence& SCS2);
112
113/// GetConversionRank - Retrieve the implicit conversion rank
114/// corresponding to the given implicit conversion kind.
115ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
116 static const ImplicitConversionRank
117 Rank[(int)ICK_Num_Conversion_Kinds] = {
118 ICR_Exact_Match,
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
124 ICR_Promotion,
125 ICR_Promotion,
126 ICR_Promotion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_OCL_Scalar_Widening,
138 ICR_Complex_Real_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Writeback_Conversion,
142 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
143 // it was omitted by the patch that added
144 // ICK_Zero_Event_Conversion
145 ICR_C_Conversion,
146 ICR_C_Conversion_Extension
147 };
148 return Rank[(int)Kind];
149}
150
151/// GetImplicitConversionName - Return the name of this kind of
152/// implicit conversion.
153static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
155 "No conversion",
156 "Lvalue-to-rvalue",
157 "Array-to-pointer",
158 "Function-to-pointer",
159 "Function pointer conversion",
160 "Qualification",
161 "Integral promotion",
162 "Floating point promotion",
163 "Complex promotion",
164 "Integral conversion",
165 "Floating conversion",
166 "Complex conversion",
167 "Floating-integral conversion",
168 "Pointer conversion",
169 "Pointer-to-member conversion",
170 "Boolean conversion",
171 "Compatible-types conversion",
172 "Derived-to-base conversion",
173 "Vector conversion",
174 "Vector splat",
175 "Complex-real conversion",
176 "Block Pointer conversion",
177 "Transparent Union Conversion",
178 "Writeback conversion",
179 "OpenCL Zero Event Conversion",
180 "C specific type conversion",
181 "Incompatible pointer conversion"
182 };
183 return Name[Kind];
184}
185
186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
192 DeprecatedStringLiteralToCharPtr = false;
193 QualificationIncludesObjCLifetime = false;
194 ReferenceBinding = false;
195 DirectBinding = false;
196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
200 ObjCLifetimeConversionBinding = false;
201 CopyConstructor = nullptr;
202}
203
204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
220/// used as part of the ranking of standard conversion sequences
221/// (C++ 13.3.3.2p4).
222bool StandardConversionSequence::isPointerConversionToBool() const {
223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
227 if (getToType(1)->isBooleanType() &&
228 (getFromType()->isPointerType() ||
229 getFromType()->isMemberPointerType() ||
230 getFromType()->isObjCObjectPointerType() ||
231 getFromType()->isBlockPointerType() ||
232 getFromType()->isNullPtrType() ||
233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234 return true;
235
236 return false;
237}
238
239/// isPointerConversionToVoidPointer - Determines whether this
240/// conversion is a conversion of a pointer to a void pointer. This is
241/// used as part of the ranking of standard conversion sequences (C++
242/// 13.3.3.2p4).
243bool
244StandardConversionSequence::
245isPointerConversionToVoidPointer(ASTContext& Context) const {
246 QualType FromType = getFromType();
247 QualType ToType = getToType(1);
248
249 // Note that FromType has not necessarily been transformed by the
250 // array-to-pointer implicit conversion, so check for its presence
251 // and redo the conversion to get a pointer.
252 if (First == ICK_Array_To_Pointer)
253 FromType = Context.getArrayDecayedType(FromType);
254
255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
257 return ToPtrType->getPointeeType()->isVoidType();
258
259 return false;
260}
261
262/// Skip any implicit casts which could be either part of a narrowing conversion
263/// or after one in an implicit conversion.
264static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
265 const Expr *Converted) {
266 // We can have cleanups wrapping the converted expression; these need to be
267 // preserved so that destructors run if necessary.
268 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
269 Expr *Inner =
270 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
271 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
272 EWC->getObjects());
273 }
274
275 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
276 switch (ICE->getCastKind()) {
277 case CK_NoOp:
278 case CK_IntegralCast:
279 case CK_IntegralToBoolean:
280 case CK_IntegralToFloating:
281 case CK_BooleanToSignedIntegral:
282 case CK_FloatingToIntegral:
283 case CK_FloatingToBoolean:
284 case CK_FloatingCast:
285 Converted = ICE->getSubExpr();
286 continue;
287
288 default:
289 return Converted;
290 }
291 }
292
293 return Converted;
294}
295
296/// Check if this standard conversion sequence represents a narrowing
297/// conversion, according to C++11 [dcl.init.list]p7.
298///
299/// \param Ctx The AST context.
300/// \param Converted The result of applying this standard conversion sequence.
301/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
302/// value of the expression prior to the narrowing conversion.
303/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
304/// type of the expression prior to the narrowing conversion.
305/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
306/// from floating point types to integral types should be ignored.
307NarrowingKind StandardConversionSequence::getNarrowingKind(
308 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
309 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
310 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")((Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"
) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 310, __PRETTY_FUNCTION__))
;
311
312 // C++11 [dcl.init.list]p7:
313 // A narrowing conversion is an implicit conversion ...
314 QualType FromType = getToType(0);
315 QualType ToType = getToType(1);
316
317 // A conversion to an enumeration type is narrowing if the conversion to
318 // the underlying type is narrowing. This only arises for expressions of
319 // the form 'Enum{init}'.
320 if (auto *ET = ToType->getAs<EnumType>())
321 ToType = ET->getDecl()->getIntegerType();
322
323 switch (Second) {
324 // 'bool' is an integral type; dispatch to the right place to handle it.
325 case ICK_Boolean_Conversion:
326 if (FromType->isRealFloatingType())
327 goto FloatingIntegralConversion;
328 if (FromType->isIntegralOrUnscopedEnumerationType())
329 goto IntegralConversion;
330 // Boolean conversions can be from pointers and pointers to members
331 // [conv.bool], and those aren't considered narrowing conversions.
332 return NK_Not_Narrowing;
333
334 // -- from a floating-point type to an integer type, or
335 //
336 // -- from an integer type or unscoped enumeration type to a floating-point
337 // type, except where the source is a constant expression and the actual
338 // value after conversion will fit into the target type and will produce
339 // the original value when converted back to the original type, or
340 case ICK_Floating_Integral:
341 FloatingIntegralConversion:
342 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
343 return NK_Type_Narrowing;
344 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
345 ToType->isRealFloatingType()) {
346 if (IgnoreFloatToIntegralConversion)
347 return NK_Not_Narrowing;
348 llvm::APSInt IntConstantValue;
349 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
350 assert(Initializer && "Unknown conversion expression")((Initializer && "Unknown conversion expression") ? static_cast
<void> (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 350, __PRETTY_FUNCTION__))
;
351
352 // If it's value-dependent, we can't tell whether it's narrowing.
353 if (Initializer->isValueDependent())
354 return NK_Dependent_Narrowing;
355
356 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
357 // Convert the integer to the floating type.
358 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
359 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
360 llvm::APFloat::rmNearestTiesToEven);
361 // And back.
362 llvm::APSInt ConvertedValue = IntConstantValue;
363 bool ignored;
364 Result.convertToInteger(ConvertedValue,
365 llvm::APFloat::rmTowardZero, &ignored);
366 // If the resulting value is different, this was a narrowing conversion.
367 if (IntConstantValue != ConvertedValue) {
368 ConstantValue = APValue(IntConstantValue);
369 ConstantType = Initializer->getType();
370 return NK_Constant_Narrowing;
371 }
372 } else {
373 // Variables are always narrowings.
374 return NK_Variable_Narrowing;
375 }
376 }
377 return NK_Not_Narrowing;
378
379 // -- from long double to double or float, or from double to float, except
380 // where the source is a constant expression and the actual value after
381 // conversion is within the range of values that can be represented (even
382 // if it cannot be represented exactly), or
383 case ICK_Floating_Conversion:
384 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
385 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
386 // FromType is larger than ToType.
387 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
388
389 // If it's value-dependent, we can't tell whether it's narrowing.
390 if (Initializer->isValueDependent())
391 return NK_Dependent_Narrowing;
392
393 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
394 // Constant!
395 assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail
("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 395, __PRETTY_FUNCTION__))
;
396 llvm::APFloat FloatVal = ConstantValue.getFloat();
397 // Convert the source value into the target type.
398 bool ignored;
399 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
400 Ctx.getFloatTypeSemantics(ToType),
401 llvm::APFloat::rmNearestTiesToEven, &ignored);
402 // If there was no overflow, the source value is within the range of
403 // values that can be represented.
404 if (ConvertStatus & llvm::APFloat::opOverflow) {
405 ConstantType = Initializer->getType();
406 return NK_Constant_Narrowing;
407 }
408 } else {
409 return NK_Variable_Narrowing;
410 }
411 }
412 return NK_Not_Narrowing;
413
414 // -- from an integer type or unscoped enumeration type to an integer type
415 // that cannot represent all the values of the original type, except where
416 // the source is a constant expression and the actual value after
417 // conversion will fit into the target type and will produce the original
418 // value when converted back to the original type.
419 case ICK_Integral_Conversion:
420 IntegralConversion: {
421 assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 421, __PRETTY_FUNCTION__))
;
422 assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 422, __PRETTY_FUNCTION__))
;
423 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
424 const unsigned FromWidth = Ctx.getIntWidth(FromType);
425 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
426 const unsigned ToWidth = Ctx.getIntWidth(ToType);
427
428 if (FromWidth > ToWidth ||
429 (FromWidth == ToWidth && FromSigned != ToSigned) ||
430 (FromSigned && !ToSigned)) {
431 // Not all values of FromType can be represented in ToType.
432 llvm::APSInt InitializerValue;
433 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
434
435 // If it's value-dependent, we can't tell whether it's narrowing.
436 if (Initializer->isValueDependent())
437 return NK_Dependent_Narrowing;
438
439 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
440 // Such conversions on variables are always narrowing.
441 return NK_Variable_Narrowing;
442 }
443 bool Narrowing = false;
444 if (FromWidth < ToWidth) {
445 // Negative -> unsigned is narrowing. Otherwise, more bits is never
446 // narrowing.
447 if (InitializerValue.isSigned() && InitializerValue.isNegative())
448 Narrowing = true;
449 } else {
450 // Add a bit to the InitializerValue so we don't have to worry about
451 // signed vs. unsigned comparisons.
452 InitializerValue = InitializerValue.extend(
453 InitializerValue.getBitWidth() + 1);
454 // Convert the initializer to and from the target width and signed-ness.
455 llvm::APSInt ConvertedValue = InitializerValue;
456 ConvertedValue = ConvertedValue.trunc(ToWidth);
457 ConvertedValue.setIsSigned(ToSigned);
458 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
459 ConvertedValue.setIsSigned(InitializerValue.isSigned());
460 // If the result is different, this was a narrowing conversion.
461 if (ConvertedValue != InitializerValue)
462 Narrowing = true;
463 }
464 if (Narrowing) {
465 ConstantType = Initializer->getType();
466 ConstantValue = APValue(InitializerValue);
467 return NK_Constant_Narrowing;
468 }
469 }
470 return NK_Not_Narrowing;
471 }
472
473 default:
474 // Other kinds of conversions are not narrowings.
475 return NK_Not_Narrowing;
476 }
477}
478
479/// dump - Print this standard conversion sequence to standard
480/// error. Useful for debugging overloading issues.
481LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
482 raw_ostream &OS = llvm::errs();
483 bool PrintedSomething = false;
484 if (First != ICK_Identity) {
485 OS << GetImplicitConversionName(First);
486 PrintedSomething = true;
487 }
488
489 if (Second != ICK_Identity) {
490 if (PrintedSomething) {
491 OS << " -> ";
492 }
493 OS << GetImplicitConversionName(Second);
494
495 if (CopyConstructor) {
496 OS << " (by copy constructor)";
497 } else if (DirectBinding) {
498 OS << " (direct reference binding)";
499 } else if (ReferenceBinding) {
500 OS << " (reference binding)";
501 }
502 PrintedSomething = true;
503 }
504
505 if (Third != ICK_Identity) {
506 if (PrintedSomething) {
507 OS << " -> ";
508 }
509 OS << GetImplicitConversionName(Third);
510 PrintedSomething = true;
511 }
512
513 if (!PrintedSomething) {
514 OS << "No conversions required";
515 }
516}
517
518/// dump - Print this user-defined conversion sequence to standard
519/// error. Useful for debugging overloading issues.
520void UserDefinedConversionSequence::dump() const {
521 raw_ostream &OS = llvm::errs();
522 if (Before.First || Before.Second || Before.Third) {
523 Before.dump();
524 OS << " -> ";
525 }
526 if (ConversionFunction)
527 OS << '\'' << *ConversionFunction << '\'';
528 else
529 OS << "aggregate initialization";
530 if (After.First || After.Second || After.Third) {
531 OS << " -> ";
532 After.dump();
533 }
534}
535
536/// dump - Print this implicit conversion sequence to standard
537/// error. Useful for debugging overloading issues.
538void ImplicitConversionSequence::dump() const {
539 raw_ostream &OS = llvm::errs();
540 if (isStdInitializerListElement())
541 OS << "Worst std::initializer_list element conversion: ";
542 switch (ConversionKind) {
543 case StandardConversion:
544 OS << "Standard conversion: ";
545 Standard.dump();
546 break;
547 case UserDefinedConversion:
548 OS << "User-defined conversion: ";
549 UserDefined.dump();
550 break;
551 case EllipsisConversion:
552 OS << "Ellipsis conversion";
553 break;
554 case AmbiguousConversion:
555 OS << "Ambiguous conversion";
556 break;
557 case BadConversion:
558 OS << "Bad conversion";
559 break;
560 }
561
562 OS << "\n";
563}
564
565void AmbiguousConversionSequence::construct() {
566 new (&conversions()) ConversionSet();
567}
568
569void AmbiguousConversionSequence::destruct() {
570 conversions().~ConversionSet();
571}
572
573void
574AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
575 FromTypePtr = O.FromTypePtr;
576 ToTypePtr = O.ToTypePtr;
577 new (&conversions()) ConversionSet(O.conversions());
578}
579
580namespace {
581 // Structure used by DeductionFailureInfo to store
582 // template argument information.
583 struct DFIArguments {
584 TemplateArgument FirstArg;
585 TemplateArgument SecondArg;
586 };
587 // Structure used by DeductionFailureInfo to store
588 // template parameter and template argument information.
589 struct DFIParamWithArguments : DFIArguments {
590 TemplateParameter Param;
591 };
592 // Structure used by DeductionFailureInfo to store template argument
593 // information and the index of the problematic call argument.
594 struct DFIDeducedMismatchArgs : DFIArguments {
595 TemplateArgumentList *TemplateArgs;
596 unsigned CallArgIndex;
597 };
598 // Structure used by DeductionFailureInfo to store information about
599 // unsatisfied constraints.
600 struct CNSInfo {
601 TemplateArgumentList *TemplateArgs;
602 ConstraintSatisfaction Satisfaction;
603 };
604}
605
606/// Convert from Sema's representation of template deduction information
607/// to the form used in overload-candidate information.
608DeductionFailureInfo
609clang::MakeDeductionFailureInfo(ASTContext &Context,
610 Sema::TemplateDeductionResult TDK,
611 TemplateDeductionInfo &Info) {
612 DeductionFailureInfo Result;
613 Result.Result = static_cast<unsigned>(TDK);
614 Result.HasDiagnostic = false;
615 switch (TDK) {
616 case Sema::TDK_Invalid:
617 case Sema::TDK_InstantiationDepth:
618 case Sema::TDK_TooManyArguments:
619 case Sema::TDK_TooFewArguments:
620 case Sema::TDK_MiscellaneousDeductionFailure:
621 case Sema::TDK_CUDATargetMismatch:
622 Result.Data = nullptr;
623 break;
624
625 case Sema::TDK_Incomplete:
626 case Sema::TDK_InvalidExplicitArguments:
627 Result.Data = Info.Param.getOpaqueValue();
628 break;
629
630 case Sema::TDK_DeducedMismatch:
631 case Sema::TDK_DeducedMismatchNested: {
632 // FIXME: Should allocate from normal heap so that we can free this later.
633 auto *Saved = new (Context) DFIDeducedMismatchArgs;
634 Saved->FirstArg = Info.FirstArg;
635 Saved->SecondArg = Info.SecondArg;
636 Saved->TemplateArgs = Info.take();
637 Saved->CallArgIndex = Info.CallArgIndex;
638 Result.Data = Saved;
639 break;
640 }
641
642 case Sema::TDK_NonDeducedMismatch: {
643 // FIXME: Should allocate from normal heap so that we can free this later.
644 DFIArguments *Saved = new (Context) DFIArguments;
645 Saved->FirstArg = Info.FirstArg;
646 Saved->SecondArg = Info.SecondArg;
647 Result.Data = Saved;
648 break;
649 }
650
651 case Sema::TDK_IncompletePack:
652 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
653 case Sema::TDK_Inconsistent:
654 case Sema::TDK_Underqualified: {
655 // FIXME: Should allocate from normal heap so that we can free this later.
656 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
657 Saved->Param = Info.Param;
658 Saved->FirstArg = Info.FirstArg;
659 Saved->SecondArg = Info.SecondArg;
660 Result.Data = Saved;
661 break;
662 }
663
664 case Sema::TDK_SubstitutionFailure:
665 Result.Data = Info.take();
666 if (Info.hasSFINAEDiagnostic()) {
667 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
668 SourceLocation(), PartialDiagnostic::NullDiagnostic());
669 Info.takeSFINAEDiagnostic(*Diag);
670 Result.HasDiagnostic = true;
671 }
672 break;
673
674 case Sema::TDK_ConstraintsNotSatisfied: {
675 CNSInfo *Saved = new (Context) CNSInfo;
676 Saved->TemplateArgs = Info.take();
677 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
678 Result.Data = Saved;
679 break;
680 }
681
682 case Sema::TDK_Success:
683 case Sema::TDK_NonDependentConversionFailure:
684 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 684)
;
685 }
686
687 return Result;
688}
689
690void DeductionFailureInfo::Destroy() {
691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
692 case Sema::TDK_Success:
693 case Sema::TDK_Invalid:
694 case Sema::TDK_InstantiationDepth:
695 case Sema::TDK_Incomplete:
696 case Sema::TDK_TooManyArguments:
697 case Sema::TDK_TooFewArguments:
698 case Sema::TDK_InvalidExplicitArguments:
699 case Sema::TDK_CUDATargetMismatch:
700 case Sema::TDK_NonDependentConversionFailure:
701 break;
702
703 case Sema::TDK_IncompletePack:
704 case Sema::TDK_Inconsistent:
705 case Sema::TDK_Underqualified:
706 case Sema::TDK_DeducedMismatch:
707 case Sema::TDK_DeducedMismatchNested:
708 case Sema::TDK_NonDeducedMismatch:
709 // FIXME: Destroy the data?
710 Data = nullptr;
711 break;
712
713 case Sema::TDK_SubstitutionFailure:
714 // FIXME: Destroy the template argument list?
715 Data = nullptr;
716 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
717 Diag->~PartialDiagnosticAt();
718 HasDiagnostic = false;
719 }
720 break;
721
722 case Sema::TDK_ConstraintsNotSatisfied:
723 // FIXME: Destroy the template argument list?
724 Data = nullptr;
725 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
726 Diag->~PartialDiagnosticAt();
727 HasDiagnostic = false;
728 }
729 break;
730
731 // Unhandled
732 case Sema::TDK_MiscellaneousDeductionFailure:
733 break;
734 }
735}
736
737PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
738 if (HasDiagnostic)
739 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
740 return nullptr;
741}
742
743TemplateParameter DeductionFailureInfo::getTemplateParameter() {
744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745 case Sema::TDK_Success:
746 case Sema::TDK_Invalid:
747 case Sema::TDK_InstantiationDepth:
748 case Sema::TDK_TooManyArguments:
749 case Sema::TDK_TooFewArguments:
750 case Sema::TDK_SubstitutionFailure:
751 case Sema::TDK_DeducedMismatch:
752 case Sema::TDK_DeducedMismatchNested:
753 case Sema::TDK_NonDeducedMismatch:
754 case Sema::TDK_CUDATargetMismatch:
755 case Sema::TDK_NonDependentConversionFailure:
756 case Sema::TDK_ConstraintsNotSatisfied:
757 return TemplateParameter();
758
759 case Sema::TDK_Incomplete:
760 case Sema::TDK_InvalidExplicitArguments:
761 return TemplateParameter::getFromOpaqueValue(Data);
762
763 case Sema::TDK_IncompletePack:
764 case Sema::TDK_Inconsistent:
765 case Sema::TDK_Underqualified:
766 return static_cast<DFIParamWithArguments*>(Data)->Param;
767
768 // Unhandled
769 case Sema::TDK_MiscellaneousDeductionFailure:
770 break;
771 }
772
773 return TemplateParameter();
774}
775
776TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
777 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
778 case Sema::TDK_Success:
779 case Sema::TDK_Invalid:
780 case Sema::TDK_InstantiationDepth:
781 case Sema::TDK_TooManyArguments:
782 case Sema::TDK_TooFewArguments:
783 case Sema::TDK_Incomplete:
784 case Sema::TDK_IncompletePack:
785 case Sema::TDK_InvalidExplicitArguments:
786 case Sema::TDK_Inconsistent:
787 case Sema::TDK_Underqualified:
788 case Sema::TDK_NonDeducedMismatch:
789 case Sema::TDK_CUDATargetMismatch:
790 case Sema::TDK_NonDependentConversionFailure:
791 return nullptr;
792
793 case Sema::TDK_DeducedMismatch:
794 case Sema::TDK_DeducedMismatchNested:
795 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
796
797 case Sema::TDK_SubstitutionFailure:
798 return static_cast<TemplateArgumentList*>(Data);
799
800 case Sema::TDK_ConstraintsNotSatisfied:
801 return static_cast<CNSInfo*>(Data)->TemplateArgs;
802
803 // Unhandled
804 case Sema::TDK_MiscellaneousDeductionFailure:
805 break;
806 }
807
808 return nullptr;
809}
810
811const TemplateArgument *DeductionFailureInfo::getFirstArg() {
812 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
813 case Sema::TDK_Success:
814 case Sema::TDK_Invalid:
815 case Sema::TDK_InstantiationDepth:
816 case Sema::TDK_Incomplete:
817 case Sema::TDK_TooManyArguments:
818 case Sema::TDK_TooFewArguments:
819 case Sema::TDK_InvalidExplicitArguments:
820 case Sema::TDK_SubstitutionFailure:
821 case Sema::TDK_CUDATargetMismatch:
822 case Sema::TDK_NonDependentConversionFailure:
823 case Sema::TDK_ConstraintsNotSatisfied:
824 return nullptr;
825
826 case Sema::TDK_IncompletePack:
827 case Sema::TDK_Inconsistent:
828 case Sema::TDK_Underqualified:
829 case Sema::TDK_DeducedMismatch:
830 case Sema::TDK_DeducedMismatchNested:
831 case Sema::TDK_NonDeducedMismatch:
832 return &static_cast<DFIArguments*>(Data)->FirstArg;
833
834 // Unhandled
835 case Sema::TDK_MiscellaneousDeductionFailure:
836 break;
837 }
838
839 return nullptr;
840}
841
842const TemplateArgument *DeductionFailureInfo::getSecondArg() {
843 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
844 case Sema::TDK_Success:
845 case Sema::TDK_Invalid:
846 case Sema::TDK_InstantiationDepth:
847 case Sema::TDK_Incomplete:
848 case Sema::TDK_IncompletePack:
849 case Sema::TDK_TooManyArguments:
850 case Sema::TDK_TooFewArguments:
851 case Sema::TDK_InvalidExplicitArguments:
852 case Sema::TDK_SubstitutionFailure:
853 case Sema::TDK_CUDATargetMismatch:
854 case Sema::TDK_NonDependentConversionFailure:
855 case Sema::TDK_ConstraintsNotSatisfied:
856 return nullptr;
857
858 case Sema::TDK_Inconsistent:
859 case Sema::TDK_Underqualified:
860 case Sema::TDK_DeducedMismatch:
861 case Sema::TDK_DeducedMismatchNested:
862 case Sema::TDK_NonDeducedMismatch:
863 return &static_cast<DFIArguments*>(Data)->SecondArg;
864
865 // Unhandled
866 case Sema::TDK_MiscellaneousDeductionFailure:
867 break;
868 }
869
870 return nullptr;
871}
872
873llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
874 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
875 case Sema::TDK_DeducedMismatch:
876 case Sema::TDK_DeducedMismatchNested:
877 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
878
879 default:
880 return llvm::None;
881 }
882}
883
884bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
885 OverloadedOperatorKind Op) {
886 if (!AllowRewrittenCandidates)
887 return false;
888 return Op == OO_EqualEqual || Op == OO_Spaceship;
889}
890
891bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
892 ASTContext &Ctx, const FunctionDecl *FD) {
893 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
894 return false;
895 // Don't bother adding a reversed candidate that can never be a better
896 // match than the non-reversed version.
897 return FD->getNumParams() != 2 ||
898 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
899 FD->getParamDecl(1)->getType()) ||
900 FD->hasAttr<EnableIfAttr>();
901}
902
903void OverloadCandidateSet::destroyCandidates() {
904 for (iterator i = begin(), e = end(); i != e; ++i) {
905 for (auto &C : i->Conversions)
906 C.~ImplicitConversionSequence();
907 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
908 i->DeductionFailure.Destroy();
909 }
910}
911
912void OverloadCandidateSet::clear(CandidateSetKind CSK) {
913 destroyCandidates();
914 SlabAllocator.Reset();
915 NumInlineBytesUsed = 0;
916 Candidates.clear();
917 Functions.clear();
918 Kind = CSK;
919}
920
921namespace {
922 class UnbridgedCastsSet {
923 struct Entry {
924 Expr **Addr;
925 Expr *Saved;
926 };
927 SmallVector<Entry, 2> Entries;
928
929 public:
930 void save(Sema &S, Expr *&E) {
931 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 931, __PRETTY_FUNCTION__))
;
932 Entry entry = { &E, E };
933 Entries.push_back(entry);
934 E = S.stripARCUnbridgedCast(E);
935 }
936
937 void restore() {
938 for (SmallVectorImpl<Entry>::iterator
939 i = Entries.begin(), e = Entries.end(); i != e; ++i)
940 *i->Addr = i->Saved;
941 }
942 };
943}
944
945/// checkPlaceholderForOverload - Do any interesting placeholder-like
946/// preprocessing on the given expression.
947///
948/// \param unbridgedCasts a collection to which to add unbridged casts;
949/// without this, they will be immediately diagnosed as errors
950///
951/// Return true on unrecoverable error.
952static bool
953checkPlaceholderForOverload(Sema &S, Expr *&E,
954 UnbridgedCastsSet *unbridgedCasts = nullptr) {
955 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
956 // We can't handle overloaded expressions here because overload
957 // resolution might reasonably tweak them.
958 if (placeholder->getKind() == BuiltinType::Overload) return false;
959
960 // If the context potentially accepts unbridged ARC casts, strip
961 // the unbridged cast and add it to the collection for later restoration.
962 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
963 unbridgedCasts) {
964 unbridgedCasts->save(S, E);
965 return false;
966 }
967
968 // Go ahead and check everything else.
969 ExprResult result = S.CheckPlaceholderExpr(E);
970 if (result.isInvalid())
971 return true;
972
973 E = result.get();
974 return false;
975 }
976
977 // Nothing to do.
978 return false;
979}
980
981/// checkArgPlaceholdersForOverload - Check a set of call operands for
982/// placeholders.
983static bool checkArgPlaceholdersForOverload(Sema &S,
984 MultiExprArg Args,
985 UnbridgedCastsSet &unbridged) {
986 for (unsigned i = 0, e = Args.size(); i != e; ++i)
987 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
988 return true;
989
990 return false;
991}
992
993/// Determine whether the given New declaration is an overload of the
994/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
995/// New and Old cannot be overloaded, e.g., if New has the same signature as
996/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
997/// functions (or function templates) at all. When it does return Ovl_Match or
998/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
999/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1000/// declaration.
1001///
1002/// Example: Given the following input:
1003///
1004/// void f(int, float); // #1
1005/// void f(int, int); // #2
1006/// int f(int, int); // #3
1007///
1008/// When we process #1, there is no previous declaration of "f", so IsOverload
1009/// will not be used.
1010///
1011/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1012/// the parameter types, we see that #1 and #2 are overloaded (since they have
1013/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1014/// unchanged.
1015///
1016/// When we process #3, Old is an overload set containing #1 and #2. We compare
1017/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1018/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1019/// functions are not part of the signature), IsOverload returns Ovl_Match and
1020/// MatchedDecl will be set to point to the FunctionDecl for #2.
1021///
1022/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1023/// by a using declaration. The rules for whether to hide shadow declarations
1024/// ignore some properties which otherwise figure into a function template's
1025/// signature.
1026Sema::OverloadKind
1027Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1028 NamedDecl *&Match, bool NewIsUsingDecl) {
1029 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1030 I != E; ++I) {
1031 NamedDecl *OldD = *I;
1032
1033 bool OldIsUsingDecl = false;
1034 if (isa<UsingShadowDecl>(OldD)) {
1035 OldIsUsingDecl = true;
1036
1037 // We can always introduce two using declarations into the same
1038 // context, even if they have identical signatures.
1039 if (NewIsUsingDecl) continue;
1040
1041 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1042 }
1043
1044 // A using-declaration does not conflict with another declaration
1045 // if one of them is hidden.
1046 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1047 continue;
1048
1049 // If either declaration was introduced by a using declaration,
1050 // we'll need to use slightly different rules for matching.
1051 // Essentially, these rules are the normal rules, except that
1052 // function templates hide function templates with different
1053 // return types or template parameter lists.
1054 bool UseMemberUsingDeclRules =
1055 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1056 !New->getFriendObjectKind();
1057
1058 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1059 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1060 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1061 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1062 continue;
1063 }
1064
1065 if (!isa<FunctionTemplateDecl>(OldD) &&
1066 !shouldLinkPossiblyHiddenDecl(*I, New))
1067 continue;
1068
1069 Match = *I;
1070 return Ovl_Match;
1071 }
1072
1073 // Builtins that have custom typechecking or have a reference should
1074 // not be overloadable or redeclarable.
1075 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1076 Match = *I;
1077 return Ovl_NonFunction;
1078 }
1079 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1080 // We can overload with these, which can show up when doing
1081 // redeclaration checks for UsingDecls.
1082 assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast<
void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1082, __PRETTY_FUNCTION__))
;
1083 } else if (isa<TagDecl>(OldD)) {
1084 // We can always overload with tags by hiding them.
1085 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1086 // Optimistically assume that an unresolved using decl will
1087 // overload; if it doesn't, we'll have to diagnose during
1088 // template instantiation.
1089 //
1090 // Exception: if the scope is dependent and this is not a class
1091 // member, the using declaration can only introduce an enumerator.
1092 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1093 Match = *I;
1094 return Ovl_NonFunction;
1095 }
1096 } else {
1097 // (C++ 13p1):
1098 // Only function declarations can be overloaded; object and type
1099 // declarations cannot be overloaded.
1100 Match = *I;
1101 return Ovl_NonFunction;
1102 }
1103 }
1104
1105 // C++ [temp.friend]p1:
1106 // For a friend function declaration that is not a template declaration:
1107 // -- if the name of the friend is a qualified or unqualified template-id,
1108 // [...], otherwise
1109 // -- if the name of the friend is a qualified-id and a matching
1110 // non-template function is found in the specified class or namespace,
1111 // the friend declaration refers to that function, otherwise,
1112 // -- if the name of the friend is a qualified-id and a matching function
1113 // template is found in the specified class or namespace, the friend
1114 // declaration refers to the deduced specialization of that function
1115 // template, otherwise
1116 // -- the name shall be an unqualified-id [...]
1117 // If we get here for a qualified friend declaration, we've just reached the
1118 // third bullet. If the type of the friend is dependent, skip this lookup
1119 // until instantiation.
1120 if (New->getFriendObjectKind() && New->getQualifier() &&
1121 !New->getDescribedFunctionTemplate() &&
1122 !New->getDependentSpecializationInfo() &&
1123 !New->getType()->isDependentType()) {
1124 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1125 TemplateSpecResult.addAllDecls(Old);
1126 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1127 /*QualifiedFriend*/true)) {
1128 New->setInvalidDecl();
1129 return Ovl_Overload;
1130 }
1131
1132 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1133 return Ovl_Match;
1134 }
1135
1136 return Ovl_Overload;
1137}
1138
1139bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1140 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1141 bool ConsiderRequiresClauses) {
1142 // C++ [basic.start.main]p2: This function shall not be overloaded.
1143 if (New->isMain())
1144 return false;
1145
1146 // MSVCRT user defined entry points cannot be overloaded.
1147 if (New->isMSVCRTEntryPoint())
1148 return false;
1149
1150 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1151 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1152
1153 // C++ [temp.fct]p2:
1154 // A function template can be overloaded with other function templates
1155 // and with normal (non-template) functions.
1156 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1157 return true;
1158
1159 // Is the function New an overload of the function Old?
1160 QualType OldQType = Context.getCanonicalType(Old->getType());
1161 QualType NewQType = Context.getCanonicalType(New->getType());
1162
1163 // Compare the signatures (C++ 1.3.10) of the two functions to
1164 // determine whether they are overloads. If we find any mismatch
1165 // in the signature, they are overloads.
1166
1167 // If either of these functions is a K&R-style function (no
1168 // prototype), then we consider them to have matching signatures.
1169 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1170 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1171 return false;
1172
1173 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1174 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1175
1176 // The signature of a function includes the types of its
1177 // parameters (C++ 1.3.10), which includes the presence or absence
1178 // of the ellipsis; see C++ DR 357).
1179 if (OldQType != NewQType &&
1180 (OldType->getNumParams() != NewType->getNumParams() ||
1181 OldType->isVariadic() != NewType->isVariadic() ||
1182 !FunctionParamTypesAreEqual(OldType, NewType)))
1183 return true;
1184
1185 // C++ [temp.over.link]p4:
1186 // The signature of a function template consists of its function
1187 // signature, its return type and its template parameter list. The names
1188 // of the template parameters are significant only for establishing the
1189 // relationship between the template parameters and the rest of the
1190 // signature.
1191 //
1192 // We check the return type and template parameter lists for function
1193 // templates first; the remaining checks follow.
1194 //
1195 // However, we don't consider either of these when deciding whether
1196 // a member introduced by a shadow declaration is hidden.
1197 if (!UseMemberUsingDeclRules && NewTemplate &&
1198 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1199 OldTemplate->getTemplateParameters(),
1200 false, TPL_TemplateMatch) ||
1201 !Context.hasSameType(Old->getDeclaredReturnType(),
1202 New->getDeclaredReturnType())))
1203 return true;
1204
1205 // If the function is a class member, its signature includes the
1206 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1207 //
1208 // As part of this, also check whether one of the member functions
1209 // is static, in which case they are not overloads (C++
1210 // 13.1p2). While not part of the definition of the signature,
1211 // this check is important to determine whether these functions
1212 // can be overloaded.
1213 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1214 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1215 if (OldMethod && NewMethod &&
1216 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1217 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1218 if (!UseMemberUsingDeclRules &&
1219 (OldMethod->getRefQualifier() == RQ_None ||
1220 NewMethod->getRefQualifier() == RQ_None)) {
1221 // C++0x [over.load]p2:
1222 // - Member function declarations with the same name and the same
1223 // parameter-type-list as well as member function template
1224 // declarations with the same name, the same parameter-type-list, and
1225 // the same template parameter lists cannot be overloaded if any of
1226 // them, but not all, have a ref-qualifier (8.3.5).
1227 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1228 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1229 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1230 }
1231 return true;
1232 }
1233
1234 // We may not have applied the implicit const for a constexpr member
1235 // function yet (because we haven't yet resolved whether this is a static
1236 // or non-static member function). Add it now, on the assumption that this
1237 // is a redeclaration of OldMethod.
1238 auto OldQuals = OldMethod->getMethodQualifiers();
1239 auto NewQuals = NewMethod->getMethodQualifiers();
1240 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1241 !isa<CXXConstructorDecl>(NewMethod))
1242 NewQuals.addConst();
1243 // We do not allow overloading based off of '__restrict'.
1244 OldQuals.removeRestrict();
1245 NewQuals.removeRestrict();
1246 if (OldQuals != NewQuals)
1247 return true;
1248 }
1249
1250 // Though pass_object_size is placed on parameters and takes an argument, we
1251 // consider it to be a function-level modifier for the sake of function
1252 // identity. Either the function has one or more parameters with
1253 // pass_object_size or it doesn't.
1254 if (functionHasPassObjectSizeParams(New) !=
1255 functionHasPassObjectSizeParams(Old))
1256 return true;
1257
1258 // enable_if attributes are an order-sensitive part of the signature.
1259 for (specific_attr_iterator<EnableIfAttr>
1260 NewI = New->specific_attr_begin<EnableIfAttr>(),
1261 NewE = New->specific_attr_end<EnableIfAttr>(),
1262 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1263 OldE = Old->specific_attr_end<EnableIfAttr>();
1264 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1265 if (NewI == NewE || OldI == OldE)
1266 return true;
1267 llvm::FoldingSetNodeID NewID, OldID;
1268 NewI->getCond()->Profile(NewID, Context, true);
1269 OldI->getCond()->Profile(OldID, Context, true);
1270 if (NewID != OldID)
1271 return true;
1272 }
1273
1274 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1275 // Don't allow overloading of destructors. (In theory we could, but it
1276 // would be a giant change to clang.)
1277 if (!isa<CXXDestructorDecl>(New)) {
1278 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1279 OldTarget = IdentifyCUDATarget(Old);
1280 if (NewTarget != CFT_InvalidTarget) {
1281 assert((OldTarget != CFT_InvalidTarget) &&(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1282, __PRETTY_FUNCTION__))
1282 "Unexpected invalid target.")(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1282, __PRETTY_FUNCTION__))
;
1283
1284 // Allow overloading of functions with same signature and different CUDA
1285 // target attributes.
1286 if (NewTarget != OldTarget)
1287 return true;
1288 }
1289 }
1290 }
1291
1292 if (ConsiderRequiresClauses) {
1293 Expr *NewRC = New->getTrailingRequiresClause(),
1294 *OldRC = Old->getTrailingRequiresClause();
1295 if ((NewRC != nullptr) != (OldRC != nullptr))
1296 // RC are most certainly different - these are overloads.
1297 return true;
1298
1299 if (NewRC) {
1300 llvm::FoldingSetNodeID NewID, OldID;
1301 NewRC->Profile(NewID, Context, /*Canonical=*/true);
1302 OldRC->Profile(OldID, Context, /*Canonical=*/true);
1303 if (NewID != OldID)
1304 // RCs are not equivalent - these are overloads.
1305 return true;
1306 }
1307 }
1308
1309 // The signatures match; this is not an overload.
1310 return false;
1311}
1312
1313/// Tries a user-defined conversion from From to ToType.
1314///
1315/// Produces an implicit conversion sequence for when a standard conversion
1316/// is not an option. See TryImplicitConversion for more information.
1317static ImplicitConversionSequence
1318TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1319 bool SuppressUserConversions,
1320 bool AllowExplicit,
1321 bool InOverloadResolution,
1322 bool CStyle,
1323 bool AllowObjCWritebackConversion,
1324 bool AllowObjCConversionOnExplicit) {
1325 ImplicitConversionSequence ICS;
1326
1327 if (SuppressUserConversions) {
1328 // We're not in the case above, so there is no conversion that
1329 // we can perform.
1330 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1331 return ICS;
1332 }
1333
1334 // Attempt user-defined conversion.
1335 OverloadCandidateSet Conversions(From->getExprLoc(),
1336 OverloadCandidateSet::CSK_Normal);
1337 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1338 Conversions, AllowExplicit,
1339 AllowObjCConversionOnExplicit)) {
1340 case OR_Success:
1341 case OR_Deleted:
1342 ICS.setUserDefined();
1343 // C++ [over.ics.user]p4:
1344 // A conversion of an expression of class type to the same class
1345 // type is given Exact Match rank, and a conversion of an
1346 // expression of class type to a base class of that type is
1347 // given Conversion rank, in spite of the fact that a copy
1348 // constructor (i.e., a user-defined conversion function) is
1349 // called for those cases.
1350 if (CXXConstructorDecl *Constructor
1351 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1352 QualType FromCanon
1353 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1354 QualType ToCanon
1355 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1356 if (Constructor->isCopyConstructor() &&
1357 (FromCanon == ToCanon ||
1358 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1359 // Turn this into a "standard" conversion sequence, so that it
1360 // gets ranked with standard conversion sequences.
1361 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1362 ICS.setStandard();
1363 ICS.Standard.setAsIdentityConversion();
1364 ICS.Standard.setFromType(From->getType());
1365 ICS.Standard.setAllToTypes(ToType);
1366 ICS.Standard.CopyConstructor = Constructor;
1367 ICS.Standard.FoundCopyConstructor = Found;
1368 if (ToCanon != FromCanon)
1369 ICS.Standard.Second = ICK_Derived_To_Base;
1370 }
1371 }
1372 break;
1373
1374 case OR_Ambiguous:
1375 ICS.setAmbiguous();
1376 ICS.Ambiguous.setFromType(From->getType());
1377 ICS.Ambiguous.setToType(ToType);
1378 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1379 Cand != Conversions.end(); ++Cand)
1380 if (Cand->Best)
1381 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1382 break;
1383
1384 // Fall through.
1385 case OR_No_Viable_Function:
1386 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1387 break;
1388 }
1389
1390 return ICS;
1391}
1392
1393/// TryImplicitConversion - Attempt to perform an implicit conversion
1394/// from the given expression (Expr) to the given type (ToType). This
1395/// function returns an implicit conversion sequence that can be used
1396/// to perform the initialization. Given
1397///
1398/// void f(float f);
1399/// void g(int i) { f(i); }
1400///
1401/// this routine would produce an implicit conversion sequence to
1402/// describe the initialization of f from i, which will be a standard
1403/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1404/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1405//
1406/// Note that this routine only determines how the conversion can be
1407/// performed; it does not actually perform the conversion. As such,
1408/// it will not produce any diagnostics if no conversion is available,
1409/// but will instead return an implicit conversion sequence of kind
1410/// "BadConversion".
1411///
1412/// If @p SuppressUserConversions, then user-defined conversions are
1413/// not permitted.
1414/// If @p AllowExplicit, then explicit user-defined conversions are
1415/// permitted.
1416///
1417/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1418/// writeback conversion, which allows __autoreleasing id* parameters to
1419/// be initialized with __strong id* or __weak id* arguments.
1420static ImplicitConversionSequence
1421TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1422 bool SuppressUserConversions,
1423 bool AllowExplicit,
1424 bool InOverloadResolution,
1425 bool CStyle,
1426 bool AllowObjCWritebackConversion,
1427 bool AllowObjCConversionOnExplicit) {
1428 ImplicitConversionSequence ICS;
1429 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1430 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1431 ICS.setStandard();
1432 return ICS;
1433 }
1434
1435 if (!S.getLangOpts().CPlusPlus) {
1436 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1437 return ICS;
1438 }
1439
1440 // C++ [over.ics.user]p4:
1441 // A conversion of an expression of class type to the same class
1442 // type is given Exact Match rank, and a conversion of an
1443 // expression of class type to a base class of that type is
1444 // given Conversion rank, in spite of the fact that a copy/move
1445 // constructor (i.e., a user-defined conversion function) is
1446 // called for those cases.
1447 QualType FromType = From->getType();
1448 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1449 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1450 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1451 ICS.setStandard();
1452 ICS.Standard.setAsIdentityConversion();
1453 ICS.Standard.setFromType(FromType);
1454 ICS.Standard.setAllToTypes(ToType);
1455
1456 // We don't actually check at this point whether there is a valid
1457 // copy/move constructor, since overloading just assumes that it
1458 // exists. When we actually perform initialization, we'll find the
1459 // appropriate constructor to copy the returned object, if needed.
1460 ICS.Standard.CopyConstructor = nullptr;
1461
1462 // Determine whether this is considered a derived-to-base conversion.
1463 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1464 ICS.Standard.Second = ICK_Derived_To_Base;
1465
1466 return ICS;
1467 }
1468
1469 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1470 AllowExplicit, InOverloadResolution, CStyle,
1471 AllowObjCWritebackConversion,
1472 AllowObjCConversionOnExplicit);
1473}
1474
1475ImplicitConversionSequence
1476Sema::TryImplicitConversion(Expr *From, QualType ToType,
1477 bool SuppressUserConversions,
1478 bool AllowExplicit,
1479 bool InOverloadResolution,
1480 bool CStyle,
1481 bool AllowObjCWritebackConversion) {
1482 return ::TryImplicitConversion(*this, From, ToType,
1483 SuppressUserConversions, AllowExplicit,
1484 InOverloadResolution, CStyle,
1485 AllowObjCWritebackConversion,
1486 /*AllowObjCConversionOnExplicit=*/false);
1487}
1488
1489/// PerformImplicitConversion - Perform an implicit conversion of the
1490/// expression From to the type ToType. Returns the
1491/// converted expression. Flavor is the kind of conversion we're
1492/// performing, used in the error message. If @p AllowExplicit,
1493/// explicit user-defined conversions are permitted.
1494ExprResult
1495Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496 AssignmentAction Action, bool AllowExplicit) {
1497 ImplicitConversionSequence ICS;
1498 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1499}
1500
1501ExprResult
1502Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1503 AssignmentAction Action, bool AllowExplicit,
1504 ImplicitConversionSequence& ICS) {
1505 if (checkPlaceholderForOverload(*this, From))
1506 return ExprError();
1507
1508 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1509 bool AllowObjCWritebackConversion
1510 = getLangOpts().ObjCAutoRefCount &&
1511 (Action == AA_Passing || Action == AA_Sending);
1512 if (getLangOpts().ObjC)
1513 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1514 From->getType(), From);
1515 ICS = ::TryImplicitConversion(*this, From, ToType,
1516 /*SuppressUserConversions=*/false,
1517 AllowExplicit,
1518 /*InOverloadResolution=*/false,
1519 /*CStyle=*/false,
1520 AllowObjCWritebackConversion,
1521 /*AllowObjCConversionOnExplicit=*/false);
1522 return PerformImplicitConversion(From, ToType, ICS, Action);
1523}
1524
1525/// Determine whether the conversion from FromType to ToType is a valid
1526/// conversion that strips "noexcept" or "noreturn" off the nested function
1527/// type.
1528bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1529 QualType &ResultTy) {
1530 if (Context.hasSameUnqualifiedType(FromType, ToType))
1531 return false;
1532
1533 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1534 // or F(t noexcept) -> F(t)
1535 // where F adds one of the following at most once:
1536 // - a pointer
1537 // - a member pointer
1538 // - a block pointer
1539 // Changes here need matching changes in FindCompositePointerType.
1540 CanQualType CanTo = Context.getCanonicalType(ToType);
1541 CanQualType CanFrom = Context.getCanonicalType(FromType);
1542 Type::TypeClass TyClass = CanTo->getTypeClass();
1543 if (TyClass != CanFrom->getTypeClass()) return false;
1544 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1545 if (TyClass == Type::Pointer) {
1546 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1547 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1548 } else if (TyClass == Type::BlockPointer) {
1549 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1550 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1551 } else if (TyClass == Type::MemberPointer) {
1552 auto ToMPT = CanTo.castAs<MemberPointerType>();
1553 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1554 // A function pointer conversion cannot change the class of the function.
1555 if (ToMPT->getClass() != FromMPT->getClass())
1556 return false;
1557 CanTo = ToMPT->getPointeeType();
1558 CanFrom = FromMPT->getPointeeType();
1559 } else {
1560 return false;
1561 }
1562
1563 TyClass = CanTo->getTypeClass();
1564 if (TyClass != CanFrom->getTypeClass()) return false;
1565 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1566 return false;
1567 }
1568
1569 const auto *FromFn = cast<FunctionType>(CanFrom);
1570 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1571
1572 const auto *ToFn = cast<FunctionType>(CanTo);
1573 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1574
1575 bool Changed = false;
1576
1577 // Drop 'noreturn' if not present in target type.
1578 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1579 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1580 Changed = true;
1581 }
1582
1583 // Drop 'noexcept' if not present in target type.
1584 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1585 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1586 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1587 FromFn = cast<FunctionType>(
1588 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1589 EST_None)
1590 .getTypePtr());
1591 Changed = true;
1592 }
1593
1594 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1595 // only if the ExtParameterInfo lists of the two function prototypes can be
1596 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1597 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1598 bool CanUseToFPT, CanUseFromFPT;
1599 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1600 CanUseFromFPT, NewParamInfos) &&
1601 CanUseToFPT && !CanUseFromFPT) {
1602 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1603 ExtInfo.ExtParameterInfos =
1604 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1605 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1606 FromFPT->getParamTypes(), ExtInfo);
1607 FromFn = QT->getAs<FunctionType>();
1608 Changed = true;
1609 }
1610 }
1611
1612 if (!Changed)
1613 return false;
1614
1615 assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void>
(0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1615, __PRETTY_FUNCTION__))
;
1616 if (QualType(FromFn, 0) != CanTo) return false;
1617
1618 ResultTy = ToType;
1619 return true;
1620}
1621
1622/// Determine whether the conversion from FromType to ToType is a valid
1623/// vector conversion.
1624///
1625/// \param ICK Will be set to the vector conversion kind, if this is a vector
1626/// conversion.
1627static bool IsVectorConversion(Sema &S, QualType FromType,
1628 QualType ToType, ImplicitConversionKind &ICK) {
1629 // We need at least one of these types to be a vector type to have a vector
1630 // conversion.
1631 if (!ToType->isVectorType() && !FromType->isVectorType())
1632 return false;
1633
1634 // Identical types require no conversions.
1635 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1636 return false;
1637
1638 // There are no conversions between extended vector types, only identity.
1639 if (ToType->isExtVectorType()) {
1640 // There are no conversions between extended vector types other than the
1641 // identity conversion.
1642 if (FromType->isExtVectorType())
1643 return false;
1644
1645 // Vector splat from any arithmetic type to a vector.
1646 if (FromType->isArithmeticType()) {
1647 ICK = ICK_Vector_Splat;
1648 return true;
1649 }
1650 }
1651
1652 // We can perform the conversion between vector types in the following cases:
1653 // 1)vector types are equivalent AltiVec and GCC vector types
1654 // 2)lax vector conversions are permitted and the vector types are of the
1655 // same size
1656 if (ToType->isVectorType() && FromType->isVectorType()) {
1657 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1658 S.isLaxVectorConversion(FromType, ToType)) {
1659 ICK = ICK_Vector_Conversion;
1660 return true;
1661 }
1662 }
1663
1664 return false;
1665}
1666
1667static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1668 bool InOverloadResolution,
1669 StandardConversionSequence &SCS,
1670 bool CStyle);
1671
1672/// IsStandardConversion - Determines whether there is a standard
1673/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1674/// expression From to the type ToType. Standard conversion sequences
1675/// only consider non-class types; for conversions that involve class
1676/// types, use TryImplicitConversion. If a conversion exists, SCS will
1677/// contain the standard conversion sequence required to perform this
1678/// conversion and this routine will return true. Otherwise, this
1679/// routine will return false and the value of SCS is unspecified.
1680static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1681 bool InOverloadResolution,
1682 StandardConversionSequence &SCS,
1683 bool CStyle,
1684 bool AllowObjCWritebackConversion) {
1685 QualType FromType = From->getType();
1686
1687 // Standard conversions (C++ [conv])
1688 SCS.setAsIdentityConversion();
1689 SCS.IncompatibleObjC = false;
1690 SCS.setFromType(FromType);
1691 SCS.CopyConstructor = nullptr;
1692
1693 // There are no standard conversions for class types in C++, so
1694 // abort early. When overloading in C, however, we do permit them.
1695 if (S.getLangOpts().CPlusPlus &&
1696 (FromType->isRecordType() || ToType->isRecordType()))
1697 return false;
1698
1699 // The first conversion can be an lvalue-to-rvalue conversion,
1700 // array-to-pointer conversion, or function-to-pointer conversion
1701 // (C++ 4p1).
1702
1703 if (FromType == S.Context.OverloadTy) {
1704 DeclAccessPair AccessPair;
1705 if (FunctionDecl *Fn
1706 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1707 AccessPair)) {
1708 // We were able to resolve the address of the overloaded function,
1709 // so we can convert to the type of that function.
1710 FromType = Fn->getType();
1711 SCS.setFromType(FromType);
1712
1713 // we can sometimes resolve &foo<int> regardless of ToType, so check
1714 // if the type matches (identity) or we are converting to bool
1715 if (!S.Context.hasSameUnqualifiedType(
1716 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1717 QualType resultTy;
1718 // if the function type matches except for [[noreturn]], it's ok
1719 if (!S.IsFunctionConversion(FromType,
1720 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1721 // otherwise, only a boolean conversion is standard
1722 if (!ToType->isBooleanType())
1723 return false;
1724 }
1725
1726 // Check if the "from" expression is taking the address of an overloaded
1727 // function and recompute the FromType accordingly. Take advantage of the
1728 // fact that non-static member functions *must* have such an address-of
1729 // expression.
1730 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1731 if (Method && !Method->isStatic()) {
1732 assert(isa<UnaryOperator>(From->IgnoreParens()) &&((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1733, __PRETTY_FUNCTION__))
1733 "Non-unary operator on non-static member address")((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1733, __PRETTY_FUNCTION__))
;
1734 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1736, __PRETTY_FUNCTION__))
1735 == UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1736, __PRETTY_FUNCTION__))
1736 "Non-address-of operator on non-static member address")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1736, __PRETTY_FUNCTION__))
;
1737 const Type *ClassType
1738 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1739 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1740 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1741 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1743, __PRETTY_FUNCTION__))
1742 UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1743, __PRETTY_FUNCTION__))
1743 "Non-address-of operator for overloaded function expression")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1743, __PRETTY_FUNCTION__))
;
1744 FromType = S.Context.getPointerType(FromType);
1745 }
1746
1747 // Check that we've computed the proper type after overload resolution.
1748 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1749 // be calling it from within an NDEBUG block.
1750 assert(S.Context.hasSameType(((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1752, __PRETTY_FUNCTION__))
1751 FromType,((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1752, __PRETTY_FUNCTION__))
1752 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 1752, __PRETTY_FUNCTION__))
;
1753 } else {
1754 return false;
1755 }
1756 }
1757 // Lvalue-to-rvalue conversion (C++11 4.1):
1758 // A glvalue (3.10) of a non-function, non-array type T can
1759 // be converted to a prvalue.
1760 bool argIsLValue = From->isGLValue();
1761 if (argIsLValue &&
1762 !FromType->isFunctionType() && !FromType->isArrayType() &&
1763 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1764 SCS.First = ICK_Lvalue_To_Rvalue;
1765
1766 // C11 6.3.2.1p2:
1767 // ... if the lvalue has atomic type, the value has the non-atomic version
1768 // of the type of the lvalue ...
1769 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1770 FromType = Atomic->getValueType();
1771
1772 // If T is a non-class type, the type of the rvalue is the
1773 // cv-unqualified version of T. Otherwise, the type of the rvalue
1774 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1775 // just strip the qualifiers because they don't matter.
1776 FromType = FromType.getUnqualifiedType();
1777 } else if (FromType->isArrayType()) {
1778 // Array-to-pointer conversion (C++ 4.2)
1779 SCS.First = ICK_Array_To_Pointer;
1780
1781 // An lvalue or rvalue of type "array of N T" or "array of unknown
1782 // bound of T" can be converted to an rvalue of type "pointer to
1783 // T" (C++ 4.2p1).
1784 FromType = S.Context.getArrayDecayedType(FromType);
1785
1786 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1787 // This conversion is deprecated in C++03 (D.4)
1788 SCS.DeprecatedStringLiteralToCharPtr = true;
1789
1790 // For the purpose of ranking in overload resolution
1791 // (13.3.3.1.1), this conversion is considered an
1792 // array-to-pointer conversion followed by a qualification
1793 // conversion (4.4). (C++ 4.2p2)
1794 SCS.Second = ICK_Identity;
1795 SCS.Third = ICK_Qualification;
1796 SCS.QualificationIncludesObjCLifetime = false;
1797 SCS.setAllToTypes(FromType);
1798 return true;
1799 }
1800 } else if (FromType->isFunctionType() && argIsLValue) {
1801 // Function-to-pointer conversion (C++ 4.3).
1802 SCS.First = ICK_Function_To_Pointer;
1803
1804 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1805 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1806 if (!S.checkAddressOfFunctionIsAvailable(FD))
1807 return false;
1808
1809 // An lvalue of function type T can be converted to an rvalue of
1810 // type "pointer to T." The result is a pointer to the
1811 // function. (C++ 4.3p1).
1812 FromType = S.Context.getPointerType(FromType);
1813 } else {
1814 // We don't require any conversions for the first step.
1815 SCS.First = ICK_Identity;
1816 }
1817 SCS.setToType(0, FromType);
1818
1819 // The second conversion can be an integral promotion, floating
1820 // point promotion, integral conversion, floating point conversion,
1821 // floating-integral conversion, pointer conversion,
1822 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1823 // For overloading in C, this can also be a "compatible-type"
1824 // conversion.
1825 bool IncompatibleObjC = false;
1826 ImplicitConversionKind SecondICK = ICK_Identity;
1827 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1828 // The unqualified versions of the types are the same: there's no
1829 // conversion to do.
1830 SCS.Second = ICK_Identity;
1831 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1832 // Integral promotion (C++ 4.5).
1833 SCS.Second = ICK_Integral_Promotion;
1834 FromType = ToType.getUnqualifiedType();
1835 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1836 // Floating point promotion (C++ 4.6).
1837 SCS.Second = ICK_Floating_Promotion;
1838 FromType = ToType.getUnqualifiedType();
1839 } else if (S.IsComplexPromotion(FromType, ToType)) {
1840 // Complex promotion (Clang extension)
1841 SCS.Second = ICK_Complex_Promotion;
1842 FromType = ToType.getUnqualifiedType();
1843 } else if (ToType->isBooleanType() &&
1844 (FromType->isArithmeticType() ||
1845 FromType->isAnyPointerType() ||
1846 FromType->isBlockPointerType() ||
1847 FromType->isMemberPointerType() ||
1848 FromType->isNullPtrType())) {
1849 // Boolean conversions (C++ 4.12).
1850 SCS.Second = ICK_Boolean_Conversion;
1851 FromType = S.Context.BoolTy;
1852 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1853 ToType->isIntegralType(S.Context)) {
1854 // Integral conversions (C++ 4.7).
1855 SCS.Second = ICK_Integral_Conversion;
1856 FromType = ToType.getUnqualifiedType();
1857 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1858 // Complex conversions (C99 6.3.1.6)
1859 SCS.Second = ICK_Complex_Conversion;
1860 FromType = ToType.getUnqualifiedType();
1861 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1862 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1863 // Complex-real conversions (C99 6.3.1.7)
1864 SCS.Second = ICK_Complex_Real;
1865 FromType = ToType.getUnqualifiedType();
1866 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1867 // FIXME: disable conversions between long double and __float128 if
1868 // their representation is different until there is back end support
1869 // We of course allow this conversion if long double is really double.
1870 if (&S.Context.getFloatTypeSemantics(FromType) !=
1871 &S.Context.getFloatTypeSemantics(ToType)) {
1872 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1873 ToType == S.Context.LongDoubleTy) ||
1874 (FromType == S.Context.LongDoubleTy &&
1875 ToType == S.Context.Float128Ty));
1876 if (Float128AndLongDouble &&
1877 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1878 &llvm::APFloat::PPCDoubleDouble()))
1879 return false;
1880 }
1881 // Floating point conversions (C++ 4.8).
1882 SCS.Second = ICK_Floating_Conversion;
1883 FromType = ToType.getUnqualifiedType();
1884 } else if ((FromType->isRealFloatingType() &&
1885 ToType->isIntegralType(S.Context)) ||
1886 (FromType->isIntegralOrUnscopedEnumerationType() &&
1887 ToType->isRealFloatingType())) {
1888 // Floating-integral conversions (C++ 4.9).
1889 SCS.Second = ICK_Floating_Integral;
1890 FromType = ToType.getUnqualifiedType();
1891 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1892 SCS.Second = ICK_Block_Pointer_Conversion;
1893 } else if (AllowObjCWritebackConversion &&
1894 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1895 SCS.Second = ICK_Writeback_Conversion;
1896 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1897 FromType, IncompatibleObjC)) {
1898 // Pointer conversions (C++ 4.10).
1899 SCS.Second = ICK_Pointer_Conversion;
1900 SCS.IncompatibleObjC = IncompatibleObjC;
1901 FromType = FromType.getUnqualifiedType();
1902 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1903 InOverloadResolution, FromType)) {
1904 // Pointer to member conversions (4.11).
1905 SCS.Second = ICK_Pointer_Member;
1906 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1907 SCS.Second = SecondICK;
1908 FromType = ToType.getUnqualifiedType();
1909 } else if (!S.getLangOpts().CPlusPlus &&
1910 S.Context.typesAreCompatible(ToType, FromType)) {
1911 // Compatible conversions (Clang extension for C function overloading)
1912 SCS.Second = ICK_Compatible_Conversion;
1913 FromType = ToType.getUnqualifiedType();
1914 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1915 InOverloadResolution,
1916 SCS, CStyle)) {
1917 SCS.Second = ICK_TransparentUnionConversion;
1918 FromType = ToType;
1919 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1920 CStyle)) {
1921 // tryAtomicConversion has updated the standard conversion sequence
1922 // appropriately.
1923 return true;
1924 } else if (ToType->isEventT() &&
1925 From->isIntegerConstantExpr(S.getASTContext()) &&
1926 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1927 SCS.Second = ICK_Zero_Event_Conversion;
1928 FromType = ToType;
1929 } else if (ToType->isQueueT() &&
1930 From->isIntegerConstantExpr(S.getASTContext()) &&
1931 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1932 SCS.Second = ICK_Zero_Queue_Conversion;
1933 FromType = ToType;
1934 } else if (ToType->isSamplerT() &&
1935 From->isIntegerConstantExpr(S.getASTContext())) {
1936 SCS.Second = ICK_Compatible_Conversion;
1937 FromType = ToType;
1938 } else {
1939 // No second conversion required.
1940 SCS.Second = ICK_Identity;
1941 }
1942 SCS.setToType(1, FromType);
1943
1944 // The third conversion can be a function pointer conversion or a
1945 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1946 bool ObjCLifetimeConversion;
1947 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1948 // Function pointer conversions (removing 'noexcept') including removal of
1949 // 'noreturn' (Clang extension).
1950 SCS.Third = ICK_Function_Conversion;
1951 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1952 ObjCLifetimeConversion)) {
1953 SCS.Third = ICK_Qualification;
1954 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1955 FromType = ToType;
1956 } else {
1957 // No conversion required
1958 SCS.Third = ICK_Identity;
1959 }
1960
1961 // C++ [over.best.ics]p6:
1962 // [...] Any difference in top-level cv-qualification is
1963 // subsumed by the initialization itself and does not constitute
1964 // a conversion. [...]
1965 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1966 QualType CanonTo = S.Context.getCanonicalType(ToType);
1967 if (CanonFrom.getLocalUnqualifiedType()
1968 == CanonTo.getLocalUnqualifiedType() &&
1969 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1970 FromType = ToType;
1971 CanonFrom = CanonTo;
1972 }
1973
1974 SCS.setToType(2, FromType);
1975
1976 if (CanonFrom == CanonTo)
1977 return true;
1978
1979 // If we have not converted the argument type to the parameter type,
1980 // this is a bad conversion sequence, unless we're resolving an overload in C.
1981 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1982 return false;
1983
1984 ExprResult ER = ExprResult{From};
1985 Sema::AssignConvertType Conv =
1986 S.CheckSingleAssignmentConstraints(ToType, ER,
1987 /*Diagnose=*/false,
1988 /*DiagnoseCFAudited=*/false,
1989 /*ConvertRHS=*/false);
1990 ImplicitConversionKind SecondConv;
1991 switch (Conv) {
1992 case Sema::Compatible:
1993 SecondConv = ICK_C_Only_Conversion;
1994 break;
1995 // For our purposes, discarding qualifiers is just as bad as using an
1996 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1997 // qualifiers, as well.
1998 case Sema::CompatiblePointerDiscardsQualifiers:
1999 case Sema::IncompatiblePointer:
2000 case Sema::IncompatiblePointerSign:
2001 SecondConv = ICK_Incompatible_Pointer_Conversion;
2002 break;
2003 default:
2004 return false;
2005 }
2006
2007 // First can only be an lvalue conversion, so we pretend that this was the
2008 // second conversion. First should already be valid from earlier in the
2009 // function.
2010 SCS.Second = SecondConv;
2011 SCS.setToType(1, ToType);
2012
2013 // Third is Identity, because Second should rank us worse than any other
2014 // conversion. This could also be ICK_Qualification, but it's simpler to just
2015 // lump everything in with the second conversion, and we don't gain anything
2016 // from making this ICK_Qualification.
2017 SCS.Third = ICK_Identity;
2018 SCS.setToType(2, ToType);
2019 return true;
2020}
2021
2022static bool
2023IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2024 QualType &ToType,
2025 bool InOverloadResolution,
2026 StandardConversionSequence &SCS,
2027 bool CStyle) {
2028
2029 const RecordType *UT = ToType->getAsUnionType();
2030 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2031 return false;
2032 // The field to initialize within the transparent union.
2033 RecordDecl *UD = UT->getDecl();
2034 // It's compatible if the expression matches any of the fields.
2035 for (const auto *it : UD->fields()) {
2036 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2037 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2038 ToType = it->getType();
2039 return true;
2040 }
2041 }
2042 return false;
2043}
2044
2045/// IsIntegralPromotion - Determines whether the conversion from the
2046/// expression From (whose potentially-adjusted type is FromType) to
2047/// ToType is an integral promotion (C++ 4.5). If so, returns true and
2048/// sets PromotedType to the promoted type.
2049bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2050 const BuiltinType *To = ToType->getAs<BuiltinType>();
2051 // All integers are built-in.
2052 if (!To) {
2053 return false;
2054 }
2055
2056 // An rvalue of type char, signed char, unsigned char, short int, or
2057 // unsigned short int can be converted to an rvalue of type int if
2058 // int can represent all the values of the source type; otherwise,
2059 // the source rvalue can be converted to an rvalue of type unsigned
2060 // int (C++ 4.5p1).
2061 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2062 !FromType->isEnumeralType()) {
2063 if (// We can promote any signed, promotable integer type to an int
2064 (FromType->isSignedIntegerType() ||
2065 // We can promote any unsigned integer type whose size is
2066 // less than int to an int.
2067 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2068 return To->getKind() == BuiltinType::Int;
2069 }
2070
2071 return To->getKind() == BuiltinType::UInt;
2072 }
2073
2074 // C++11 [conv.prom]p3:
2075 // A prvalue of an unscoped enumeration type whose underlying type is not
2076 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2077 // following types that can represent all the values of the enumeration
2078 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2079 // unsigned int, long int, unsigned long int, long long int, or unsigned
2080 // long long int. If none of the types in that list can represent all the
2081 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2082 // type can be converted to an rvalue a prvalue of the extended integer type
2083 // with lowest integer conversion rank (4.13) greater than the rank of long
2084 // long in which all the values of the enumeration can be represented. If
2085 // there are two such extended types, the signed one is chosen.
2086 // C++11 [conv.prom]p4:
2087 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2088 // can be converted to a prvalue of its underlying type. Moreover, if
2089 // integral promotion can be applied to its underlying type, a prvalue of an
2090 // unscoped enumeration type whose underlying type is fixed can also be
2091 // converted to a prvalue of the promoted underlying type.
2092 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2093 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2094 // provided for a scoped enumeration.
2095 if (FromEnumType->getDecl()->isScoped())
2096 return false;
2097
2098 // We can perform an integral promotion to the underlying type of the enum,
2099 // even if that's not the promoted type. Note that the check for promoting
2100 // the underlying type is based on the type alone, and does not consider
2101 // the bitfield-ness of the actual source expression.
2102 if (FromEnumType->getDecl()->isFixed()) {
2103 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2104 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2105 IsIntegralPromotion(nullptr, Underlying, ToType);
2106 }
2107
2108 // We have already pre-calculated the promotion type, so this is trivial.
2109 if (ToType->isIntegerType() &&
2110 isCompleteType(From->getBeginLoc(), FromType))
2111 return Context.hasSameUnqualifiedType(
2112 ToType, FromEnumType->getDecl()->getPromotionType());
2113
2114 // C++ [conv.prom]p5:
2115 // If the bit-field has an enumerated type, it is treated as any other
2116 // value of that type for promotion purposes.
2117 //
2118 // ... so do not fall through into the bit-field checks below in C++.
2119 if (getLangOpts().CPlusPlus)
2120 return false;
2121 }
2122
2123 // C++0x [conv.prom]p2:
2124 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2125 // to an rvalue a prvalue of the first of the following types that can
2126 // represent all the values of its underlying type: int, unsigned int,
2127 // long int, unsigned long int, long long int, or unsigned long long int.
2128 // If none of the types in that list can represent all the values of its
2129 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2130 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2131 // type.
2132 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2133 ToType->isIntegerType()) {
2134 // Determine whether the type we're converting from is signed or
2135 // unsigned.
2136 bool FromIsSigned = FromType->isSignedIntegerType();
2137 uint64_t FromSize = Context.getTypeSize(FromType);
2138
2139 // The types we'll try to promote to, in the appropriate
2140 // order. Try each of these types.
2141 QualType PromoteTypes[6] = {
2142 Context.IntTy, Context.UnsignedIntTy,
2143 Context.LongTy, Context.UnsignedLongTy ,
2144 Context.LongLongTy, Context.UnsignedLongLongTy
2145 };
2146 for (int Idx = 0; Idx < 6; ++Idx) {
2147 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2148 if (FromSize < ToSize ||
2149 (FromSize == ToSize &&
2150 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2151 // We found the type that we can promote to. If this is the
2152 // type we wanted, we have a promotion. Otherwise, no
2153 // promotion.
2154 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2155 }
2156 }
2157 }
2158
2159 // An rvalue for an integral bit-field (9.6) can be converted to an
2160 // rvalue of type int if int can represent all the values of the
2161 // bit-field; otherwise, it can be converted to unsigned int if
2162 // unsigned int can represent all the values of the bit-field. If
2163 // the bit-field is larger yet, no integral promotion applies to
2164 // it. If the bit-field has an enumerated type, it is treated as any
2165 // other value of that type for promotion purposes (C++ 4.5p3).
2166 // FIXME: We should delay checking of bit-fields until we actually perform the
2167 // conversion.
2168 //
2169 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2170 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2171 // bit-fields and those whose underlying type is larger than int) for GCC
2172 // compatibility.
2173 if (From) {
2174 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2175 llvm::APSInt BitWidth;
2176 if (FromType->isIntegralType(Context) &&
2177 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2178 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2179 ToSize = Context.getTypeSize(ToType);
2180
2181 // Are we promoting to an int from a bitfield that fits in an int?
2182 if (BitWidth < ToSize ||
2183 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2184 return To->getKind() == BuiltinType::Int;
2185 }
2186
2187 // Are we promoting to an unsigned int from an unsigned bitfield
2188 // that fits into an unsigned int?
2189 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2190 return To->getKind() == BuiltinType::UInt;
2191 }
2192
2193 return false;
2194 }
2195 }
2196 }
2197
2198 // An rvalue of type bool can be converted to an rvalue of type int,
2199 // with false becoming zero and true becoming one (C++ 4.5p4).
2200 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2201 return true;
2202 }
2203
2204 return false;
2205}
2206
2207/// IsFloatingPointPromotion - Determines whether the conversion from
2208/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2209/// returns true and sets PromotedType to the promoted type.
2210bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2211 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2212 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2213 /// An rvalue of type float can be converted to an rvalue of type
2214 /// double. (C++ 4.6p1).
2215 if (FromBuiltin->getKind() == BuiltinType::Float &&
2216 ToBuiltin->getKind() == BuiltinType::Double)
2217 return true;
2218
2219 // C99 6.3.1.5p1:
2220 // When a float is promoted to double or long double, or a
2221 // double is promoted to long double [...].
2222 if (!getLangOpts().CPlusPlus &&
2223 (FromBuiltin->getKind() == BuiltinType::Float ||
2224 FromBuiltin->getKind() == BuiltinType::Double) &&
2225 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2226 ToBuiltin->getKind() == BuiltinType::Float128))
2227 return true;
2228
2229 // Half can be promoted to float.
2230 if (!getLangOpts().NativeHalfType &&
2231 FromBuiltin->getKind() == BuiltinType::Half &&
2232 ToBuiltin->getKind() == BuiltinType::Float)
2233 return true;
2234 }
2235
2236 return false;
2237}
2238
2239/// Determine if a conversion is a complex promotion.
2240///
2241/// A complex promotion is defined as a complex -> complex conversion
2242/// where the conversion between the underlying real types is a
2243/// floating-point or integral promotion.
2244bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2245 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2246 if (!FromComplex)
2247 return false;
2248
2249 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2250 if (!ToComplex)
2251 return false;
2252
2253 return IsFloatingPointPromotion(FromComplex->getElementType(),
2254 ToComplex->getElementType()) ||
2255 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2256 ToComplex->getElementType());
2257}
2258
2259/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2260/// the pointer type FromPtr to a pointer to type ToPointee, with the
2261/// same type qualifiers as FromPtr has on its pointee type. ToType,
2262/// if non-empty, will be a pointer to ToType that may or may not have
2263/// the right set of qualifiers on its pointee.
2264///
2265static QualType
2266BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2267 QualType ToPointee, QualType ToType,
2268 ASTContext &Context,
2269 bool StripObjCLifetime = false) {
2270 assert((FromPtr->getTypeClass() == Type::Pointer ||(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 2272, __PRETTY_FUNCTION__))
2271 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 2272, __PRETTY_FUNCTION__))
2272 "Invalid similarly-qualified pointer type")(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 2272, __PRETTY_FUNCTION__))
;
2273
2274 /// Conversions to 'id' subsume cv-qualifier conversions.
2275 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2276 return ToType.getUnqualifiedType();
2277
2278 QualType CanonFromPointee
2279 = Context.getCanonicalType(FromPtr->getPointeeType());
2280 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2281 Qualifiers Quals = CanonFromPointee.getQualifiers();
2282
2283 if (StripObjCLifetime)
2284 Quals.removeObjCLifetime();
2285
2286 // Exact qualifier match -> return the pointer type we're converting to.
2287 if (CanonToPointee.getLocalQualifiers() == Quals) {
2288 // ToType is exactly what we need. Return it.
2289 if (!ToType.isNull())
2290 return ToType.getUnqualifiedType();
2291
2292 // Build a pointer to ToPointee. It has the right qualifiers
2293 // already.
2294 if (isa<ObjCObjectPointerType>(ToType))
2295 return Context.getObjCObjectPointerType(ToPointee);
2296 return Context.getPointerType(ToPointee);
2297 }
2298
2299 // Just build a canonical type that has the right qualifiers.
2300 QualType QualifiedCanonToPointee
2301 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2302
2303 if (isa<ObjCObjectPointerType>(ToType))
2304 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2305 return Context.getPointerType(QualifiedCanonToPointee);
2306}
2307
2308static bool isNullPointerConstantForConversion(Expr *Expr,
2309 bool InOverloadResolution,
2310 ASTContext &Context) {
2311 // Handle value-dependent integral null pointer constants correctly.
2312 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2313 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2314 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2315 return !InOverloadResolution;
2316
2317 return Expr->isNullPointerConstant(Context,
2318 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2319 : Expr::NPC_ValueDependentIsNull);
2320}
2321
2322/// IsPointerConversion - Determines whether the conversion of the
2323/// expression From, which has the (possibly adjusted) type FromType,
2324/// can be converted to the type ToType via a pointer conversion (C++
2325/// 4.10). If so, returns true and places the converted type (that
2326/// might differ from ToType in its cv-qualifiers at some level) into
2327/// ConvertedType.
2328///
2329/// This routine also supports conversions to and from block pointers
2330/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2331/// pointers to interfaces. FIXME: Once we've determined the
2332/// appropriate overloading rules for Objective-C, we may want to
2333/// split the Objective-C checks into a different routine; however,
2334/// GCC seems to consider all of these conversions to be pointer
2335/// conversions, so for now they live here. IncompatibleObjC will be
2336/// set if the conversion is an allowed Objective-C conversion that
2337/// should result in a warning.
2338bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2339 bool InOverloadResolution,
2340 QualType& ConvertedType,
2341 bool &IncompatibleObjC) {
2342 IncompatibleObjC = false;
2343 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2344 IncompatibleObjC))
2345 return true;
2346
2347 // Conversion from a null pointer constant to any Objective-C pointer type.
2348 if (ToType->isObjCObjectPointerType() &&
2349 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2350 ConvertedType = ToType;
2351 return true;
2352 }
2353
2354 // Blocks: Block pointers can be converted to void*.
2355 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2356 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2357 ConvertedType = ToType;
2358 return true;
2359 }
2360 // Blocks: A null pointer constant can be converted to a block
2361 // pointer type.
2362 if (ToType->isBlockPointerType() &&
2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2364 ConvertedType = ToType;
2365 return true;
2366 }
2367
2368 // If the left-hand-side is nullptr_t, the right side can be a null
2369 // pointer constant.
2370 if (ToType->isNullPtrType() &&
2371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2372 ConvertedType = ToType;
2373 return true;
2374 }
2375
2376 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2377 if (!ToTypePtr)
2378 return false;
2379
2380 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2381 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2382 ConvertedType = ToType;
2383 return true;
2384 }
2385
2386 // Beyond this point, both types need to be pointers
2387 // , including objective-c pointers.
2388 QualType ToPointeeType = ToTypePtr->getPointeeType();
2389 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2390 !getLangOpts().ObjCAutoRefCount) {
2391 ConvertedType = BuildSimilarlyQualifiedPointerType(
2392 FromType->getAs<ObjCObjectPointerType>(),
2393 ToPointeeType,
2394 ToType, Context);
2395 return true;
2396 }
2397 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2398 if (!FromTypePtr)
2399 return false;
2400
2401 QualType FromPointeeType = FromTypePtr->getPointeeType();
2402
2403 // If the unqualified pointee types are the same, this can't be a
2404 // pointer conversion, so don't do all of the work below.
2405 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2406 return false;
2407
2408 // An rvalue of type "pointer to cv T," where T is an object type,
2409 // can be converted to an rvalue of type "pointer to cv void" (C++
2410 // 4.10p2).
2411 if (FromPointeeType->isIncompleteOrObjectType() &&
2412 ToPointeeType->isVoidType()) {
2413 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2414 ToPointeeType,
2415 ToType, Context,
2416 /*StripObjCLifetime=*/true);
2417 return true;
2418 }
2419
2420 // MSVC allows implicit function to void* type conversion.
2421 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2422 ToPointeeType->isVoidType()) {
2423 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2424 ToPointeeType,
2425 ToType, Context);
2426 return true;
2427 }
2428
2429 // When we're overloading in C, we allow a special kind of pointer
2430 // conversion for compatible-but-not-identical pointee types.
2431 if (!getLangOpts().CPlusPlus &&
2432 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2433 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2434 ToPointeeType,
2435 ToType, Context);
2436 return true;
2437 }
2438
2439 // C++ [conv.ptr]p3:
2440 //
2441 // An rvalue of type "pointer to cv D," where D is a class type,
2442 // can be converted to an rvalue of type "pointer to cv B," where
2443 // B is a base class (clause 10) of D. If B is an inaccessible
2444 // (clause 11) or ambiguous (10.2) base class of D, a program that
2445 // necessitates this conversion is ill-formed. The result of the
2446 // conversion is a pointer to the base class sub-object of the
2447 // derived class object. The null pointer value is converted to
2448 // the null pointer value of the destination type.
2449 //
2450 // Note that we do not check for ambiguity or inaccessibility
2451 // here. That is handled by CheckPointerConversion.
2452 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2453 ToPointeeType->isRecordType() &&
2454 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2455 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2456 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2457 ToPointeeType,
2458 ToType, Context);
2459 return true;
2460 }
2461
2462 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2463 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2464 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2465 ToPointeeType,
2466 ToType, Context);
2467 return true;
2468 }
2469
2470 return false;
2471}
2472
2473/// Adopt the given qualifiers for the given type.
2474static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2475 Qualifiers TQs = T.getQualifiers();
2476
2477 // Check whether qualifiers already match.
2478 if (TQs == Qs)
2479 return T;
2480
2481 if (Qs.compatiblyIncludes(TQs))
2482 return Context.getQualifiedType(T, Qs);
2483
2484 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2485}
2486
2487/// isObjCPointerConversion - Determines whether this is an
2488/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2489/// with the same arguments and return values.
2490bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2491 QualType& ConvertedType,
2492 bool &IncompatibleObjC) {
2493 if (!getLangOpts().ObjC)
2494 return false;
2495
2496 // The set of qualifiers on the type we're converting from.
2497 Qualifiers FromQualifiers = FromType.getQualifiers();
2498
2499 // First, we handle all conversions on ObjC object pointer types.
2500 const ObjCObjectPointerType* ToObjCPtr =
2501 ToType->getAs<ObjCObjectPointerType>();
2502 const ObjCObjectPointerType *FromObjCPtr =
2503 FromType->getAs<ObjCObjectPointerType>();
2504
2505 if (ToObjCPtr && FromObjCPtr) {
2506 // If the pointee types are the same (ignoring qualifications),
2507 // then this is not a pointer conversion.
2508 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2509 FromObjCPtr->getPointeeType()))
2510 return false;
2511
2512 // Conversion between Objective-C pointers.
2513 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2514 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2515 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2516 if (getLangOpts().CPlusPlus && LHS && RHS &&
2517 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2518 FromObjCPtr->getPointeeType()))
2519 return false;
2520 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2521 ToObjCPtr->getPointeeType(),
2522 ToType, Context);
2523 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2524 return true;
2525 }
2526
2527 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2528 // Okay: this is some kind of implicit downcast of Objective-C
2529 // interfaces, which is permitted. However, we're going to
2530 // complain about it.
2531 IncompatibleObjC = true;
2532 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2533 ToObjCPtr->getPointeeType(),
2534 ToType, Context);
2535 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2536 return true;
2537 }
2538 }
2539 // Beyond this point, both types need to be C pointers or block pointers.
2540 QualType ToPointeeType;
2541 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2542 ToPointeeType = ToCPtr->getPointeeType();
2543 else if (const BlockPointerType *ToBlockPtr =
2544 ToType->getAs<BlockPointerType>()) {
2545 // Objective C++: We're able to convert from a pointer to any object
2546 // to a block pointer type.
2547 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2548 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2549 return true;
2550 }
2551 ToPointeeType = ToBlockPtr->getPointeeType();
2552 }
2553 else if (FromType->getAs<BlockPointerType>() &&
2554 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2555 // Objective C++: We're able to convert from a block pointer type to a
2556 // pointer to any object.
2557 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2558 return true;
2559 }
2560 else
2561 return false;
2562
2563 QualType FromPointeeType;
2564 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2565 FromPointeeType = FromCPtr->getPointeeType();
2566 else if (const BlockPointerType *FromBlockPtr =
2567 FromType->getAs<BlockPointerType>())
2568 FromPointeeType = FromBlockPtr->getPointeeType();
2569 else
2570 return false;
2571
2572 // If we have pointers to pointers, recursively check whether this
2573 // is an Objective-C conversion.
2574 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2575 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2576 IncompatibleObjC)) {
2577 // We always complain about this conversion.
2578 IncompatibleObjC = true;
2579 ConvertedType = Context.getPointerType(ConvertedType);
2580 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2581 return true;
2582 }
2583 // Allow conversion of pointee being objective-c pointer to another one;
2584 // as in I* to id.
2585 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2586 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2587 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2588 IncompatibleObjC)) {
2589
2590 ConvertedType = Context.getPointerType(ConvertedType);
2591 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2592 return true;
2593 }
2594
2595 // If we have pointers to functions or blocks, check whether the only
2596 // differences in the argument and result types are in Objective-C
2597 // pointer conversions. If so, we permit the conversion (but
2598 // complain about it).
2599 const FunctionProtoType *FromFunctionType
2600 = FromPointeeType->getAs<FunctionProtoType>();
2601 const FunctionProtoType *ToFunctionType
2602 = ToPointeeType->getAs<FunctionProtoType>();
2603 if (FromFunctionType && ToFunctionType) {
2604 // If the function types are exactly the same, this isn't an
2605 // Objective-C pointer conversion.
2606 if (Context.getCanonicalType(FromPointeeType)
2607 == Context.getCanonicalType(ToPointeeType))
2608 return false;
2609
2610 // Perform the quick checks that will tell us whether these
2611 // function types are obviously different.
2612 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2613 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2614 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2615 return false;
2616
2617 bool HasObjCConversion = false;
2618 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2619 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2620 // Okay, the types match exactly. Nothing to do.
2621 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2622 ToFunctionType->getReturnType(),
2623 ConvertedType, IncompatibleObjC)) {
2624 // Okay, we have an Objective-C pointer conversion.
2625 HasObjCConversion = true;
2626 } else {
2627 // Function types are too different. Abort.
2628 return false;
2629 }
2630
2631 // Check argument types.
2632 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2633 ArgIdx != NumArgs; ++ArgIdx) {
2634 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2635 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2636 if (Context.getCanonicalType(FromArgType)
2637 == Context.getCanonicalType(ToArgType)) {
2638 // Okay, the types match exactly. Nothing to do.
2639 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2640 ConvertedType, IncompatibleObjC)) {
2641 // Okay, we have an Objective-C pointer conversion.
2642 HasObjCConversion = true;
2643 } else {
2644 // Argument types are too different. Abort.
2645 return false;
2646 }
2647 }
2648
2649 if (HasObjCConversion) {
2650 // We had an Objective-C conversion. Allow this pointer
2651 // conversion, but complain about it.
2652 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2653 IncompatibleObjC = true;
2654 return true;
2655 }
2656 }
2657
2658 return false;
2659}
2660
2661/// Determine whether this is an Objective-C writeback conversion,
2662/// used for parameter passing when performing automatic reference counting.
2663///
2664/// \param FromType The type we're converting form.
2665///
2666/// \param ToType The type we're converting to.
2667///
2668/// \param ConvertedType The type that will be produced after applying
2669/// this conversion.
2670bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2671 QualType &ConvertedType) {
2672 if (!getLangOpts().ObjCAutoRefCount ||
2673 Context.hasSameUnqualifiedType(FromType, ToType))
2674 return false;
2675
2676 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2677 QualType ToPointee;
2678 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2679 ToPointee = ToPointer->getPointeeType();
2680 else
2681 return false;
2682
2683 Qualifiers ToQuals = ToPointee.getQualifiers();
2684 if (!ToPointee->isObjCLifetimeType() ||
2685 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2686 !ToQuals.withoutObjCLifetime().empty())
2687 return false;
2688
2689 // Argument must be a pointer to __strong to __weak.
2690 QualType FromPointee;
2691 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2692 FromPointee = FromPointer->getPointeeType();
2693 else
2694 return false;
2695
2696 Qualifiers FromQuals = FromPointee.getQualifiers();
2697 if (!FromPointee->isObjCLifetimeType() ||
2698 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2699 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2700 return false;
2701
2702 // Make sure that we have compatible qualifiers.
2703 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2704 if (!ToQuals.compatiblyIncludes(FromQuals))
2705 return false;
2706
2707 // Remove qualifiers from the pointee type we're converting from; they
2708 // aren't used in the compatibility check belong, and we'll be adding back
2709 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2710 FromPointee = FromPointee.getUnqualifiedType();
2711
2712 // The unqualified form of the pointee types must be compatible.
2713 ToPointee = ToPointee.getUnqualifiedType();
2714 bool IncompatibleObjC;
2715 if (Context.typesAreCompatible(FromPointee, ToPointee))
2716 FromPointee = ToPointee;
2717 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2718 IncompatibleObjC))
2719 return false;
2720
2721 /// Construct the type we're converting to, which is a pointer to
2722 /// __autoreleasing pointee.
2723 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2724 ConvertedType = Context.getPointerType(FromPointee);
2725 return true;
2726}
2727
2728bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2729 QualType& ConvertedType) {
2730 QualType ToPointeeType;
2731 if (const BlockPointerType *ToBlockPtr =
2732 ToType->getAs<BlockPointerType>())
2733 ToPointeeType = ToBlockPtr->getPointeeType();
2734 else
2735 return false;
2736
2737 QualType FromPointeeType;
2738 if (const BlockPointerType *FromBlockPtr =
2739 FromType->getAs<BlockPointerType>())
2740 FromPointeeType = FromBlockPtr->getPointeeType();
2741 else
2742 return false;
2743 // We have pointer to blocks, check whether the only
2744 // differences in the argument and result types are in Objective-C
2745 // pointer conversions. If so, we permit the conversion.
2746
2747 const FunctionProtoType *FromFunctionType
2748 = FromPointeeType->getAs<FunctionProtoType>();
2749 const FunctionProtoType *ToFunctionType
2750 = ToPointeeType->getAs<FunctionProtoType>();
2751
2752 if (!FromFunctionType || !ToFunctionType)
2753 return false;
2754
2755 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2756 return true;
2757
2758 // Perform the quick checks that will tell us whether these
2759 // function types are obviously different.
2760 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2761 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2762 return false;
2763
2764 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2765 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2766 if (FromEInfo != ToEInfo)
2767 return false;
2768
2769 bool IncompatibleObjC = false;
2770 if (Context.hasSameType(FromFunctionType->getReturnType(),
2771 ToFunctionType->getReturnType())) {
2772 // Okay, the types match exactly. Nothing to do.
2773 } else {
2774 QualType RHS = FromFunctionType->getReturnType();
2775 QualType LHS = ToFunctionType->getReturnType();
2776 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2777 !RHS.hasQualifiers() && LHS.hasQualifiers())
2778 LHS = LHS.getUnqualifiedType();
2779
2780 if (Context.hasSameType(RHS,LHS)) {
2781 // OK exact match.
2782 } else if (isObjCPointerConversion(RHS, LHS,
2783 ConvertedType, IncompatibleObjC)) {
2784 if (IncompatibleObjC)
2785 return false;
2786 // Okay, we have an Objective-C pointer conversion.
2787 }
2788 else
2789 return false;
2790 }
2791
2792 // Check argument types.
2793 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2794 ArgIdx != NumArgs; ++ArgIdx) {
2795 IncompatibleObjC = false;
2796 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2797 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2798 if (Context.hasSameType(FromArgType, ToArgType)) {
2799 // Okay, the types match exactly. Nothing to do.
2800 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2801 ConvertedType, IncompatibleObjC)) {
2802 if (IncompatibleObjC)
2803 return false;
2804 // Okay, we have an Objective-C pointer conversion.
2805 } else
2806 // Argument types are too different. Abort.
2807 return false;
2808 }
2809
2810 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2811 bool CanUseToFPT, CanUseFromFPT;
2812 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2813 CanUseToFPT, CanUseFromFPT,
2814 NewParamInfos))
2815 return false;
2816
2817 ConvertedType = ToType;
2818 return true;
2819}
2820
2821enum {
2822 ft_default,
2823 ft_different_class,
2824 ft_parameter_arity,
2825 ft_parameter_mismatch,
2826 ft_return_type,
2827 ft_qualifer_mismatch,
2828 ft_noexcept
2829};
2830
2831/// Attempts to get the FunctionProtoType from a Type. Handles
2832/// MemberFunctionPointers properly.
2833static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2834 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2835 return FPT;
2836
2837 if (auto *MPT = FromType->getAs<MemberPointerType>())
2838 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2839
2840 return nullptr;
2841}
2842
2843/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2844/// function types. Catches different number of parameter, mismatch in
2845/// parameter types, and different return types.
2846void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2847 QualType FromType, QualType ToType) {
2848 // If either type is not valid, include no extra info.
2849 if (FromType.isNull() || ToType.isNull()) {
2850 PDiag << ft_default;
2851 return;
2852 }
2853
2854 // Get the function type from the pointers.
2855 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2856 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2857 *ToMember = ToType->getAs<MemberPointerType>();
2858 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2859 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2860 << QualType(FromMember->getClass(), 0);
2861 return;
2862 }
2863 FromType = FromMember->getPointeeType();
2864 ToType = ToMember->getPointeeType();
2865 }
2866
2867 if (FromType->isPointerType())
2868 FromType = FromType->getPointeeType();
2869 if (ToType->isPointerType())
2870 ToType = ToType->getPointeeType();
2871
2872 // Remove references.
2873 FromType = FromType.getNonReferenceType();
2874 ToType = ToType.getNonReferenceType();
2875
2876 // Don't print extra info for non-specialized template functions.
2877 if (FromType->isInstantiationDependentType() &&
2878 !FromType->getAs<TemplateSpecializationType>()) {
2879 PDiag << ft_default;
2880 return;
2881 }
2882
2883 // No extra info for same types.
2884 if (Context.hasSameType(FromType, ToType)) {
2885 PDiag << ft_default;
2886 return;
2887 }
2888
2889 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2890 *ToFunction = tryGetFunctionProtoType(ToType);
2891
2892 // Both types need to be function types.
2893 if (!FromFunction || !ToFunction) {
2894 PDiag << ft_default;
2895 return;
2896 }
2897
2898 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2899 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2900 << FromFunction->getNumParams();
2901 return;
2902 }
2903
2904 // Handle different parameter types.
2905 unsigned ArgPos;
2906 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2907 PDiag << ft_parameter_mismatch << ArgPos + 1
2908 << ToFunction->getParamType(ArgPos)
2909 << FromFunction->getParamType(ArgPos);
2910 return;
2911 }
2912
2913 // Handle different return type.
2914 if (!Context.hasSameType(FromFunction->getReturnType(),
2915 ToFunction->getReturnType())) {
2916 PDiag << ft_return_type << ToFunction->getReturnType()
2917 << FromFunction->getReturnType();
2918 return;
2919 }
2920
2921 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2922 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2923 << FromFunction->getMethodQuals();
2924 return;
2925 }
2926
2927 // Handle exception specification differences on canonical type (in C++17
2928 // onwards).
2929 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2930 ->isNothrow() !=
2931 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2932 ->isNothrow()) {
2933 PDiag << ft_noexcept;
2934 return;
2935 }
2936
2937 // Unable to find a difference, so add no extra info.
2938 PDiag << ft_default;
2939}
2940
2941/// FunctionParamTypesAreEqual - This routine checks two function proto types
2942/// for equality of their argument types. Caller has already checked that
2943/// they have same number of arguments. If the parameters are different,
2944/// ArgPos will have the parameter index of the first different parameter.
2945bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2946 const FunctionProtoType *NewType,
2947 unsigned *ArgPos) {
2948 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2949 N = NewType->param_type_begin(),
2950 E = OldType->param_type_end();
2951 O && (O != E); ++O, ++N) {
2952 // Ignore address spaces in pointee type. This is to disallow overloading
2953 // on __ptr32/__ptr64 address spaces.
2954 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2955 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2956
2957 if (!Context.hasSameType(Old, New)) {
2958 if (ArgPos)
2959 *ArgPos = O - OldType->param_type_begin();
2960 return false;
2961 }
2962 }
2963 return true;
2964}
2965
2966/// CheckPointerConversion - Check the pointer conversion from the
2967/// expression From to the type ToType. This routine checks for
2968/// ambiguous or inaccessible derived-to-base pointer
2969/// conversions for which IsPointerConversion has already returned
2970/// true. It returns true and produces a diagnostic if there was an
2971/// error, or returns false otherwise.
2972bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2973 CastKind &Kind,
2974 CXXCastPath& BasePath,
2975 bool IgnoreBaseAccess,
2976 bool Diagnose) {
2977 QualType FromType = From->getType();
2978 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2979
2980 Kind = CK_BitCast;
2981
2982 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2983 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2984 Expr::NPCK_ZeroExpression) {
2985 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2986 DiagRuntimeBehavior(From->getExprLoc(), From,
2987 PDiag(diag::warn_impcast_bool_to_null_pointer)
2988 << ToType << From->getSourceRange());
2989 else if (!isUnevaluatedContext())
2990 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2991 << ToType << From->getSourceRange();
2992 }
2993 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2994 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2995 QualType FromPointeeType = FromPtrType->getPointeeType(),
2996 ToPointeeType = ToPtrType->getPointeeType();
2997
2998 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2999 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3000 // We must have a derived-to-base conversion. Check an
3001 // ambiguous or inaccessible conversion.
3002 unsigned InaccessibleID = 0;
3003 unsigned AmbigiousID = 0;
3004 if (Diagnose) {
3005 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3006 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
3007 }
3008 if (CheckDerivedToBaseConversion(
3009 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
3010 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3011 &BasePath, IgnoreBaseAccess))
3012 return true;
3013
3014 // The conversion was successful.
3015 Kind = CK_DerivedToBase;
3016 }
3017
3018 if (Diagnose && !IsCStyleOrFunctionalCast &&
3019 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3020 assert(getLangOpts().MSVCCompat &&((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3021, __PRETTY_FUNCTION__))
3021 "this should only be possible with MSVCCompat!")((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3021, __PRETTY_FUNCTION__))
;
3022 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3023 << From->getSourceRange();
3024 }
3025 }
3026 } else if (const ObjCObjectPointerType *ToPtrType =
3027 ToType->getAs<ObjCObjectPointerType>()) {
3028 if (const ObjCObjectPointerType *FromPtrType =
3029 FromType->getAs<ObjCObjectPointerType>()) {
3030 // Objective-C++ conversions are always okay.
3031 // FIXME: We should have a different class of conversions for the
3032 // Objective-C++ implicit conversions.
3033 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3034 return false;
3035 } else if (FromType->isBlockPointerType()) {
3036 Kind = CK_BlockPointerToObjCPointerCast;
3037 } else {
3038 Kind = CK_CPointerToObjCPointerCast;
3039 }
3040 } else if (ToType->isBlockPointerType()) {
3041 if (!FromType->isBlockPointerType())
3042 Kind = CK_AnyPointerToBlockPointerCast;
3043 }
3044
3045 // We shouldn't fall into this case unless it's valid for other
3046 // reasons.
3047 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3048 Kind = CK_NullToPointer;
3049
3050 return false;
3051}
3052
3053/// IsMemberPointerConversion - Determines whether the conversion of the
3054/// expression From, which has the (possibly adjusted) type FromType, can be
3055/// converted to the type ToType via a member pointer conversion (C++ 4.11).
3056/// If so, returns true and places the converted type (that might differ from
3057/// ToType in its cv-qualifiers at some level) into ConvertedType.
3058bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3059 QualType ToType,
3060 bool InOverloadResolution,
3061 QualType &ConvertedType) {
3062 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3063 if (!ToTypePtr)
3064 return false;
3065
3066 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3067 if (From->isNullPointerConstant(Context,
3068 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3069 : Expr::NPC_ValueDependentIsNull)) {
3070 ConvertedType = ToType;
3071 return true;
3072 }
3073
3074 // Otherwise, both types have to be member pointers.
3075 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3076 if (!FromTypePtr)
3077 return false;
3078
3079 // A pointer to member of B can be converted to a pointer to member of D,
3080 // where D is derived from B (C++ 4.11p2).
3081 QualType FromClass(FromTypePtr->getClass(), 0);
3082 QualType ToClass(ToTypePtr->getClass(), 0);
3083
3084 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3085 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3086 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3087 ToClass.getTypePtr());
3088 return true;
3089 }
3090
3091 return false;
3092}
3093
3094/// CheckMemberPointerConversion - Check the member pointer conversion from the
3095/// expression From to the type ToType. This routine checks for ambiguous or
3096/// virtual or inaccessible base-to-derived member pointer conversions
3097/// for which IsMemberPointerConversion has already returned true. It returns
3098/// true and produces a diagnostic if there was an error, or returns false
3099/// otherwise.
3100bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3101 CastKind &Kind,
3102 CXXCastPath &BasePath,
3103 bool IgnoreBaseAccess) {
3104 QualType FromType = From->getType();
3105 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3106 if (!FromPtrType) {
3107 // This must be a null pointer to member pointer conversion
3108 assert(From->isNullPointerConstant(Context,((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3110, __PRETTY_FUNCTION__))
3109 Expr::NPC_ValueDependentIsNull) &&((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3110, __PRETTY_FUNCTION__))
3110 "Expr must be null pointer constant!")((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3110, __PRETTY_FUNCTION__))
;
3111 Kind = CK_NullToMemberPointer;
3112 return false;
3113 }
3114
3115 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3116 assert(ToPtrType && "No member pointer cast has a target type "((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3117, __PRETTY_FUNCTION__))
3117 "that is not a member pointer.")((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3117, __PRETTY_FUNCTION__))
;
3118
3119 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3120 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3121
3122 // FIXME: What about dependent types?
3123 assert(FromClass->isRecordType() && "Pointer into non-class.")((FromClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3123, __PRETTY_FUNCTION__))
;
3124 assert(ToClass->isRecordType() && "Pointer into non-class.")((ToClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3124, __PRETTY_FUNCTION__))
;
3125
3126 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3127 /*DetectVirtual=*/true);
3128 bool DerivationOkay =
3129 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3130 assert(DerivationOkay &&((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
3131 "Should not have been called if derivation isn't OK.")((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3131, __PRETTY_FUNCTION__))
;
3132 (void)DerivationOkay;
3133
3134 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3135 getUnqualifiedType())) {
3136 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3137 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3138 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3139 return true;
3140 }
3141
3142 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3143 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3144 << FromClass << ToClass << QualType(VBase, 0)
3145 << From->getSourceRange();
3146 return true;
3147 }
3148
3149 if (!IgnoreBaseAccess)
3150 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3151 Paths.front(),
3152 diag::err_downcast_from_inaccessible_base);
3153
3154 // Must be a base to derived member conversion.
3155 BuildBasePathArray(Paths, BasePath);
3156 Kind = CK_BaseToDerivedMemberPointer;
3157 return false;
3158}
3159
3160/// Determine whether the lifetime conversion between the two given
3161/// qualifiers sets is nontrivial.
3162static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3163 Qualifiers ToQuals) {
3164 // Converting anything to const __unsafe_unretained is trivial.
3165 if (ToQuals.hasConst() &&
3166 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3167 return false;
3168
3169 return true;
3170}
3171
3172/// Perform a single iteration of the loop for checking if a qualification
3173/// conversion is valid.
3174///
3175/// Specifically, check whether any change between the qualifiers of \p
3176/// FromType and \p ToType is permissible, given knowledge about whether every
3177/// outer layer is const-qualified.
3178static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3179 bool CStyle,
3180 bool &PreviousToQualsIncludeConst,
3181 bool &ObjCLifetimeConversion) {
3182 Qualifiers FromQuals = FromType.getQualifiers();
3183 Qualifiers ToQuals = ToType.getQualifiers();
3184
3185 // Ignore __unaligned qualifier if this type is void.
3186 if (ToType.getUnqualifiedType()->isVoidType())
3187 FromQuals.removeUnaligned();
3188
3189 // Objective-C ARC:
3190 // Check Objective-C lifetime conversions.
3191 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3192 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3193 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3194 ObjCLifetimeConversion = true;
3195 FromQuals.removeObjCLifetime();
3196 ToQuals.removeObjCLifetime();
3197 } else {
3198 // Qualification conversions cannot cast between different
3199 // Objective-C lifetime qualifiers.
3200 return false;
3201 }
3202 }
3203
3204 // Allow addition/removal of GC attributes but not changing GC attributes.
3205 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3206 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3207 FromQuals.removeObjCGCAttr();
3208 ToQuals.removeObjCGCAttr();
3209 }
3210
3211 // -- for every j > 0, if const is in cv 1,j then const is in cv
3212 // 2,j, and similarly for volatile.
3213 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3214 return false;
3215
3216 // For a C-style cast, just require the address spaces to overlap.
3217 // FIXME: Does "superset" also imply the representation of a pointer is the
3218 // same? We're assuming that it does here and in compatiblyIncludes.
3219 if (CStyle && !ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3220 !FromQuals.isAddressSpaceSupersetOf(ToQuals))
3221 return false;
3222
3223 // -- if the cv 1,j and cv 2,j are different, then const is in
3224 // every cv for 0 < k < j.
3225 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3226 !PreviousToQualsIncludeConst)
3227 return false;
3228
3229 // Keep track of whether all prior cv-qualifiers in the "to" type
3230 // include const.
3231 PreviousToQualsIncludeConst =
3232 PreviousToQualsIncludeConst && ToQuals.hasConst();
3233 return true;
3234}
3235
3236/// IsQualificationConversion - Determines whether the conversion from
3237/// an rvalue of type FromType to ToType is a qualification conversion
3238/// (C++ 4.4).
3239///
3240/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3241/// when the qualification conversion involves a change in the Objective-C
3242/// object lifetime.
3243bool
3244Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3245 bool CStyle, bool &ObjCLifetimeConversion) {
3246 FromType = Context.getCanonicalType(FromType);
3247 ToType = Context.getCanonicalType(ToType);
3248 ObjCLifetimeConversion = false;
3249
3250 // If FromType and ToType are the same type, this is not a
3251 // qualification conversion.
3252 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3253 return false;
3254
3255 // (C++ 4.4p4):
3256 // A conversion can add cv-qualifiers at levels other than the first
3257 // in multi-level pointers, subject to the following rules: [...]
3258 bool PreviousToQualsIncludeConst = true;
3259 bool UnwrappedAnyPointer = false;
3260 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3261 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3262 PreviousToQualsIncludeConst,
3263 ObjCLifetimeConversion))
3264 return false;
3265 UnwrappedAnyPointer = true;
3266 }
3267
3268 // We are left with FromType and ToType being the pointee types
3269 // after unwrapping the original FromType and ToType the same number
3270 // of times. If we unwrapped any pointers, and if FromType and
3271 // ToType have the same unqualified type (since we checked
3272 // qualifiers above), then this is a qualification conversion.
3273 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3274}
3275
3276/// - Determine whether this is a conversion from a scalar type to an
3277/// atomic type.
3278///
3279/// If successful, updates \c SCS's second and third steps in the conversion
3280/// sequence to finish the conversion.
3281static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3282 bool InOverloadResolution,
3283 StandardConversionSequence &SCS,
3284 bool CStyle) {
3285 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3286 if (!ToAtomic)
3287 return false;
3288
3289 StandardConversionSequence InnerSCS;
3290 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3291 InOverloadResolution, InnerSCS,
3292 CStyle, /*AllowObjCWritebackConversion=*/false))
3293 return false;
3294
3295 SCS.Second = InnerSCS.Second;
3296 SCS.setToType(1, InnerSCS.getToType(1));
3297 SCS.Third = InnerSCS.Third;
3298 SCS.QualificationIncludesObjCLifetime
3299 = InnerSCS.QualificationIncludesObjCLifetime;
3300 SCS.setToType(2, InnerSCS.getToType(2));
3301 return true;
3302}
3303
3304static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3305 CXXConstructorDecl *Constructor,
3306 QualType Type) {
3307 const FunctionProtoType *CtorType =
3308 Constructor->getType()->getAs<FunctionProtoType>();
3309 if (CtorType->getNumParams() > 0) {
3310 QualType FirstArg = CtorType->getParamType(0);
3311 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3312 return true;
3313 }
3314 return false;
3315}
3316
3317static OverloadingResult
3318IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3319 CXXRecordDecl *To,
3320 UserDefinedConversionSequence &User,
3321 OverloadCandidateSet &CandidateSet,
3322 bool AllowExplicit) {
3323 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3324 for (auto *D : S.LookupConstructors(To)) {
3325 auto Info = getConstructorInfo(D);
3326 if (!Info)
3327 continue;
3328
3329 bool Usable = !Info.Constructor->isInvalidDecl() &&
3330 S.isInitListConstructor(Info.Constructor);
3331 if (Usable) {
3332 // If the first argument is (a reference to) the target type,
3333 // suppress conversions.
3334 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3335 S.Context, Info.Constructor, ToType);
3336 if (Info.ConstructorTmpl)
3337 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3338 /*ExplicitArgs*/ nullptr, From,
3339 CandidateSet, SuppressUserConversions,
3340 /*PartialOverloading*/ false,
3341 AllowExplicit);
3342 else
3343 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3344 CandidateSet, SuppressUserConversions,
3345 /*PartialOverloading*/ false, AllowExplicit);
3346 }
3347 }
3348
3349 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3350
3351 OverloadCandidateSet::iterator Best;
3352 switch (auto Result =
3353 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3354 case OR_Deleted:
3355 case OR_Success: {
3356 // Record the standard conversion we used and the conversion function.
3357 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3358 QualType ThisType = Constructor->getThisType();
3359 // Initializer lists don't have conversions as such.
3360 User.Before.setAsIdentityConversion();
3361 User.HadMultipleCandidates = HadMultipleCandidates;
3362 User.ConversionFunction = Constructor;
3363 User.FoundConversionFunction = Best->FoundDecl;
3364 User.After.setAsIdentityConversion();
3365 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3366 User.After.setAllToTypes(ToType);
3367 return Result;
3368 }
3369
3370 case OR_No_Viable_Function:
3371 return OR_No_Viable_Function;
3372 case OR_Ambiguous:
3373 return OR_Ambiguous;
3374 }
3375
3376 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3376)
;
3377}
3378
3379/// Determines whether there is a user-defined conversion sequence
3380/// (C++ [over.ics.user]) that converts expression From to the type
3381/// ToType. If such a conversion exists, User will contain the
3382/// user-defined conversion sequence that performs such a conversion
3383/// and this routine will return true. Otherwise, this routine returns
3384/// false and User is unspecified.
3385///
3386/// \param AllowExplicit true if the conversion should consider C++0x
3387/// "explicit" conversion functions as well as non-explicit conversion
3388/// functions (C++0x [class.conv.fct]p2).
3389///
3390/// \param AllowObjCConversionOnExplicit true if the conversion should
3391/// allow an extra Objective-C pointer conversion on uses of explicit
3392/// constructors. Requires \c AllowExplicit to also be set.
3393static OverloadingResult
3394IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3395 UserDefinedConversionSequence &User,
3396 OverloadCandidateSet &CandidateSet,
3397 bool AllowExplicit,
3398 bool AllowObjCConversionOnExplicit) {
3399 assert(AllowExplicit || !AllowObjCConversionOnExplicit)((AllowExplicit || !AllowObjCConversionOnExplicit) ? static_cast
<void> (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3399, __PRETTY_FUNCTION__))
;
3400 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3401
3402 // Whether we will only visit constructors.
3403 bool ConstructorsOnly = false;
3404
3405 // If the type we are conversion to is a class type, enumerate its
3406 // constructors.
3407 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3408 // C++ [over.match.ctor]p1:
3409 // When objects of class type are direct-initialized (8.5), or
3410 // copy-initialized from an expression of the same or a
3411 // derived class type (8.5), overload resolution selects the
3412 // constructor. [...] For copy-initialization, the candidate
3413 // functions are all the converting constructors (12.3.1) of
3414 // that class. The argument list is the expression-list within
3415 // the parentheses of the initializer.
3416 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3417 (From->getType()->getAs<RecordType>() &&
3418 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3419 ConstructorsOnly = true;
3420
3421 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3422 // We're not going to find any constructors.
3423 } else if (CXXRecordDecl *ToRecordDecl
3424 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3425
3426 Expr **Args = &From;
3427 unsigned NumArgs = 1;
3428 bool ListInitializing = false;
3429 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3430 // But first, see if there is an init-list-constructor that will work.
3431 OverloadingResult Result = IsInitializerListConstructorConversion(
3432 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3433 if (Result != OR_No_Viable_Function)
3434 return Result;
3435 // Never mind.
3436 CandidateSet.clear(
3437 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3438
3439 // If we're list-initializing, we pass the individual elements as
3440 // arguments, not the entire list.
3441 Args = InitList->getInits();
3442 NumArgs = InitList->getNumInits();
3443 ListInitializing = true;
3444 }
3445
3446 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3447 auto Info = getConstructorInfo(D);
3448 if (!Info)
3449 continue;
3450
3451 bool Usable = !Info.Constructor->isInvalidDecl();
3452 if (!ListInitializing)
3453 Usable = Usable && Info.Constructor->isConvertingConstructor(
3454 /*AllowExplicit*/ true);
3455 if (Usable) {
3456 bool SuppressUserConversions = !ConstructorsOnly;
3457 if (SuppressUserConversions && ListInitializing) {
3458 SuppressUserConversions = false;
3459 if (NumArgs == 1) {
3460 // If the first argument is (a reference to) the target type,
3461 // suppress conversions.
3462 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3463 S.Context, Info.Constructor, ToType);
3464 }
3465 }
3466 if (Info.ConstructorTmpl)
3467 S.AddTemplateOverloadCandidate(
3468 Info.ConstructorTmpl, Info.FoundDecl,
3469 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3470 CandidateSet, SuppressUserConversions,
3471 /*PartialOverloading*/ false, AllowExplicit);
3472 else
3473 // Allow one user-defined conversion when user specifies a
3474 // From->ToType conversion via an static cast (c-style, etc).
3475 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3476 llvm::makeArrayRef(Args, NumArgs),
3477 CandidateSet, SuppressUserConversions,
3478 /*PartialOverloading*/ false, AllowExplicit);
3479 }
3480 }
3481 }
3482 }
3483
3484 // Enumerate conversion functions, if we're allowed to.
3485 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3486 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3487 // No conversion functions from incomplete types.
3488 } else if (const RecordType *FromRecordType =
3489 From->getType()->getAs<RecordType>()) {
3490 if (CXXRecordDecl *FromRecordDecl
3491 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3492 // Add all of the conversion functions as candidates.
3493 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3494 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3495 DeclAccessPair FoundDecl = I.getPair();
3496 NamedDecl *D = FoundDecl.getDecl();
3497 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3498 if (isa<UsingShadowDecl>(D))
3499 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3500
3501 CXXConversionDecl *Conv;
3502 FunctionTemplateDecl *ConvTemplate;
3503 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3504 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3505 else
3506 Conv = cast<CXXConversionDecl>(D);
3507
3508 if (ConvTemplate)
3509 S.AddTemplateConversionCandidate(
3510 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3511 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3512 else
3513 S.AddConversionCandidate(
3514 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3515 AllowObjCConversionOnExplicit, AllowExplicit);
3516 }
3517 }
3518 }
3519
3520 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3521
3522 OverloadCandidateSet::iterator Best;
3523 switch (auto Result =
3524 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3525 case OR_Success:
3526 case OR_Deleted:
3527 // Record the standard conversion we used and the conversion function.
3528 if (CXXConstructorDecl *Constructor
3529 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3530 // C++ [over.ics.user]p1:
3531 // If the user-defined conversion is specified by a
3532 // constructor (12.3.1), the initial standard conversion
3533 // sequence converts the source type to the type required by
3534 // the argument of the constructor.
3535 //
3536 QualType ThisType = Constructor->getThisType();
3537 if (isa<InitListExpr>(From)) {
3538 // Initializer lists don't have conversions as such.
3539 User.Before.setAsIdentityConversion();
3540 } else {
3541 if (Best->Conversions[0].isEllipsis())
3542 User.EllipsisConversion = true;
3543 else {
3544 User.Before = Best->Conversions[0].Standard;
3545 User.EllipsisConversion = false;
3546 }
3547 }
3548 User.HadMultipleCandidates = HadMultipleCandidates;
3549 User.ConversionFunction = Constructor;
3550 User.FoundConversionFunction = Best->FoundDecl;
3551 User.After.setAsIdentityConversion();
3552 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3553 User.After.setAllToTypes(ToType);
3554 return Result;
3555 }
3556 if (CXXConversionDecl *Conversion
3557 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3558 // C++ [over.ics.user]p1:
3559 //
3560 // [...] If the user-defined conversion is specified by a
3561 // conversion function (12.3.2), the initial standard
3562 // conversion sequence converts the source type to the
3563 // implicit object parameter of the conversion function.
3564 User.Before = Best->Conversions[0].Standard;
3565 User.HadMultipleCandidates = HadMultipleCandidates;
3566 User.ConversionFunction = Conversion;
3567 User.FoundConversionFunction = Best->FoundDecl;
3568 User.EllipsisConversion = false;
3569
3570 // C++ [over.ics.user]p2:
3571 // The second standard conversion sequence converts the
3572 // result of the user-defined conversion to the target type
3573 // for the sequence. Since an implicit conversion sequence
3574 // is an initialization, the special rules for
3575 // initialization by user-defined conversion apply when
3576 // selecting the best user-defined conversion for a
3577 // user-defined conversion sequence (see 13.3.3 and
3578 // 13.3.3.1).
3579 User.After = Best->FinalConversion;
3580 return Result;
3581 }
3582 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3582)
;
3583
3584 case OR_No_Viable_Function:
3585 return OR_No_Viable_Function;
3586
3587 case OR_Ambiguous:
3588 return OR_Ambiguous;
3589 }
3590
3591 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 3591)
;
3592}
3593
3594bool
3595Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3596 ImplicitConversionSequence ICS;
3597 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3598 OverloadCandidateSet::CSK_Normal);
3599 OverloadingResult OvResult =
3600 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3601 CandidateSet, false, false);
3602
3603 if (!(OvResult == OR_Ambiguous ||
3604 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3605 return false;
3606
3607 auto Cands = CandidateSet.CompleteCandidates(
3608 *this,
3609 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3610 From);
3611 if (OvResult == OR_Ambiguous)
3612 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3613 << From->getType() << ToType << From->getSourceRange();
3614 else { // OR_No_Viable_Function && !CandidateSet.empty()
3615 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3616 diag::err_typecheck_nonviable_condition_incomplete,
3617 From->getType(), From->getSourceRange()))
3618 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3619 << false << From->getType() << From->getSourceRange() << ToType;
3620 }
3621
3622 CandidateSet.NoteCandidates(
3623 *this, From, Cands);
3624 return true;
3625}
3626
3627/// Compare the user-defined conversion functions or constructors
3628/// of two user-defined conversion sequences to determine whether any ordering
3629/// is possible.
3630static ImplicitConversionSequence::CompareKind
3631compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3632 FunctionDecl *Function2) {
3633 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3634 return ImplicitConversionSequence::Indistinguishable;
3635
3636 // Objective-C++:
3637 // If both conversion functions are implicitly-declared conversions from
3638 // a lambda closure type to a function pointer and a block pointer,
3639 // respectively, always prefer the conversion to a function pointer,
3640 // because the function pointer is more lightweight and is more likely
3641 // to keep code working.
3642 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3643 if (!Conv1)
3644 return ImplicitConversionSequence::Indistinguishable;
3645
3646 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3647 if (!Conv2)
3648 return ImplicitConversionSequence::Indistinguishable;
3649
3650 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3651 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3652 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3653 if (Block1 != Block2)
3654 return Block1 ? ImplicitConversionSequence::Worse
3655 : ImplicitConversionSequence::Better;
3656 }
3657
3658 return ImplicitConversionSequence::Indistinguishable;
3659}
3660
3661static bool hasDeprecatedStringLiteralToCharPtrConversion(
3662 const ImplicitConversionSequence &ICS) {
3663 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3664 (ICS.isUserDefined() &&
3665 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3666}
3667
3668/// CompareImplicitConversionSequences - Compare two implicit
3669/// conversion sequences to determine whether one is better than the
3670/// other or if they are indistinguishable (C++ 13.3.3.2).
3671static ImplicitConversionSequence::CompareKind
3672CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3673 const ImplicitConversionSequence& ICS1,
3674 const ImplicitConversionSequence& ICS2)
3675{
3676 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3677 // conversion sequences (as defined in 13.3.3.1)
3678 // -- a standard conversion sequence (13.3.3.1.1) is a better
3679 // conversion sequence than a user-defined conversion sequence or
3680 // an ellipsis conversion sequence, and
3681 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3682 // conversion sequence than an ellipsis conversion sequence
3683 // (13.3.3.1.3).
3684 //
3685 // C++0x [over.best.ics]p10:
3686 // For the purpose of ranking implicit conversion sequences as
3687 // described in 13.3.3.2, the ambiguous conversion sequence is
3688 // treated as a user-defined sequence that is indistinguishable
3689 // from any other user-defined conversion sequence.
3690
3691 // String literal to 'char *' conversion has been deprecated in C++03. It has
3692 // been removed from C++11. We still accept this conversion, if it happens at
3693 // the best viable function. Otherwise, this conversion is considered worse
3694 // than ellipsis conversion. Consider this as an extension; this is not in the
3695 // standard. For example:
3696 //
3697 // int &f(...); // #1
3698 // void f(char*); // #2
3699 // void g() { int &r = f("foo"); }
3700 //
3701 // In C++03, we pick #2 as the best viable function.
3702 // In C++11, we pick #1 as the best viable function, because ellipsis
3703 // conversion is better than string-literal to char* conversion (since there
3704 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3705 // convert arguments, #2 would be the best viable function in C++11.
3706 // If the best viable function has this conversion, a warning will be issued
3707 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3708
3709 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3710 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3711 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3712 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3713 ? ImplicitConversionSequence::Worse
3714 : ImplicitConversionSequence::Better;
3715
3716 if (ICS1.getKindRank() < ICS2.getKindRank())
3717 return ImplicitConversionSequence::Better;
3718 if (ICS2.getKindRank() < ICS1.getKindRank())
3719 return ImplicitConversionSequence::Worse;
3720
3721 // The following checks require both conversion sequences to be of
3722 // the same kind.
3723 if (ICS1.getKind() != ICS2.getKind())
3724 return ImplicitConversionSequence::Indistinguishable;
3725
3726 ImplicitConversionSequence::CompareKind Result =
3727 ImplicitConversionSequence::Indistinguishable;
3728
3729 // Two implicit conversion sequences of the same form are
3730 // indistinguishable conversion sequences unless one of the
3731 // following rules apply: (C++ 13.3.3.2p3):
3732
3733 // List-initialization sequence L1 is a better conversion sequence than
3734 // list-initialization sequence L2 if:
3735 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3736 // if not that,
3737 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3738 // and N1 is smaller than N2.,
3739 // even if one of the other rules in this paragraph would otherwise apply.
3740 if (!ICS1.isBad()) {
3741 if (ICS1.isStdInitializerListElement() &&
3742 !ICS2.isStdInitializerListElement())
3743 return ImplicitConversionSequence::Better;
3744 if (!ICS1.isStdInitializerListElement() &&
3745 ICS2.isStdInitializerListElement())
3746 return ImplicitConversionSequence::Worse;
3747 }
3748
3749 if (ICS1.isStandard())
3750 // Standard conversion sequence S1 is a better conversion sequence than
3751 // standard conversion sequence S2 if [...]
3752 Result = CompareStandardConversionSequences(S, Loc,
3753 ICS1.Standard, ICS2.Standard);
3754 else if (ICS1.isUserDefined()) {
3755 // User-defined conversion sequence U1 is a better conversion
3756 // sequence than another user-defined conversion sequence U2 if
3757 // they contain the same user-defined conversion function or
3758 // constructor and if the second standard conversion sequence of
3759 // U1 is better than the second standard conversion sequence of
3760 // U2 (C++ 13.3.3.2p3).
3761 if (ICS1.UserDefined.ConversionFunction ==
3762 ICS2.UserDefined.ConversionFunction)
3763 Result = CompareStandardConversionSequences(S, Loc,
3764 ICS1.UserDefined.After,
3765 ICS2.UserDefined.After);
3766 else
3767 Result = compareConversionFunctions(S,
3768 ICS1.UserDefined.ConversionFunction,
3769 ICS2.UserDefined.ConversionFunction);
3770 }
3771
3772 return Result;
3773}
3774
3775// Per 13.3.3.2p3, compare the given standard conversion sequences to
3776// determine if one is a proper subset of the other.
3777static ImplicitConversionSequence::CompareKind
3778compareStandardConversionSubsets(ASTContext &Context,
3779 const StandardConversionSequence& SCS1,
3780 const StandardConversionSequence& SCS2) {
3781 ImplicitConversionSequence::CompareKind Result
3782 = ImplicitConversionSequence::Indistinguishable;
3783
3784 // the identity conversion sequence is considered to be a subsequence of
3785 // any non-identity conversion sequence
3786 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3787 return ImplicitConversionSequence::Better;
3788 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3789 return ImplicitConversionSequence::Worse;
3790
3791 if (SCS1.Second != SCS2.Second) {
3792 if (SCS1.Second == ICK_Identity)
3793 Result = ImplicitConversionSequence::Better;
3794 else if (SCS2.Second == ICK_Identity)
3795 Result = ImplicitConversionSequence::Worse;
3796 else
3797 return ImplicitConversionSequence::Indistinguishable;
3798 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3799 return ImplicitConversionSequence::Indistinguishable;
3800
3801 if (SCS1.Third == SCS2.Third) {
3802 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3803 : ImplicitConversionSequence::Indistinguishable;
3804 }
3805
3806 if (SCS1.Third == ICK_Identity)
3807 return Result == ImplicitConversionSequence::Worse
3808 ? ImplicitConversionSequence::Indistinguishable
3809 : ImplicitConversionSequence::Better;
3810
3811 if (SCS2.Third == ICK_Identity)
3812 return Result == ImplicitConversionSequence::Better
3813 ? ImplicitConversionSequence::Indistinguishable
3814 : ImplicitConversionSequence::Worse;
3815
3816 return ImplicitConversionSequence::Indistinguishable;
3817}
3818
3819/// Determine whether one of the given reference bindings is better
3820/// than the other based on what kind of bindings they are.
3821static bool
3822isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3823 const StandardConversionSequence &SCS2) {
3824 // C++0x [over.ics.rank]p3b4:
3825 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3826 // implicit object parameter of a non-static member function declared
3827 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3828 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3829 // lvalue reference to a function lvalue and S2 binds an rvalue
3830 // reference*.
3831 //
3832 // FIXME: Rvalue references. We're going rogue with the above edits,
3833 // because the semantics in the current C++0x working paper (N3225 at the
3834 // time of this writing) break the standard definition of std::forward
3835 // and std::reference_wrapper when dealing with references to functions.
3836 // Proposed wording changes submitted to CWG for consideration.
3837 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3838 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3839 return false;
3840
3841 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3842 SCS2.IsLvalueReference) ||
3843 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3844 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3845}
3846
3847enum class FixedEnumPromotion {
3848 None,
3849 ToUnderlyingType,
3850 ToPromotedUnderlyingType
3851};
3852
3853/// Returns kind of fixed enum promotion the \a SCS uses.
3854static FixedEnumPromotion
3855getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3856
3857 if (SCS.Second != ICK_Integral_Promotion)
3858 return FixedEnumPromotion::None;
3859
3860 QualType FromType = SCS.getFromType();
3861 if (!FromType->isEnumeralType())
3862 return FixedEnumPromotion::None;
3863
3864 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3865 if (!Enum->isFixed())
3866 return FixedEnumPromotion::None;
3867
3868 QualType UnderlyingType = Enum->getIntegerType();
3869 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3870 return FixedEnumPromotion::ToUnderlyingType;
3871
3872 return FixedEnumPromotion::ToPromotedUnderlyingType;
3873}
3874
3875/// CompareStandardConversionSequences - Compare two standard
3876/// conversion sequences to determine whether one is better than the
3877/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3878static ImplicitConversionSequence::CompareKind
3879CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3880 const StandardConversionSequence& SCS1,
3881 const StandardConversionSequence& SCS2)
3882{
3883 // Standard conversion sequence S1 is a better conversion sequence
3884 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3885
3886 // -- S1 is a proper subsequence of S2 (comparing the conversion
3887 // sequences in the canonical form defined by 13.3.3.1.1,
3888 // excluding any Lvalue Transformation; the identity conversion
3889 // sequence is considered to be a subsequence of any
3890 // non-identity conversion sequence) or, if not that,
3891 if (ImplicitConversionSequence::CompareKind CK
3892 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3893 return CK;
3894
3895 // -- the rank of S1 is better than the rank of S2 (by the rules
3896 // defined below), or, if not that,
3897 ImplicitConversionRank Rank1 = SCS1.getRank();
3898 ImplicitConversionRank Rank2 = SCS2.getRank();
3899 if (Rank1 < Rank2)
3900 return ImplicitConversionSequence::Better;
3901 else if (Rank2 < Rank1)
3902 return ImplicitConversionSequence::Worse;
3903
3904 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3905 // are indistinguishable unless one of the following rules
3906 // applies:
3907
3908 // A conversion that is not a conversion of a pointer, or
3909 // pointer to member, to bool is better than another conversion
3910 // that is such a conversion.
3911 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3912 return SCS2.isPointerConversionToBool()
3913 ? ImplicitConversionSequence::Better
3914 : ImplicitConversionSequence::Worse;
3915
3916 // C++14 [over.ics.rank]p4b2:
3917 // This is retroactively applied to C++11 by CWG 1601.
3918 //
3919 // A conversion that promotes an enumeration whose underlying type is fixed
3920 // to its underlying type is better than one that promotes to the promoted
3921 // underlying type, if the two are different.
3922 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3923 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3924 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3925 FEP1 != FEP2)
3926 return FEP1 == FixedEnumPromotion::ToUnderlyingType
3927 ? ImplicitConversionSequence::Better
3928 : ImplicitConversionSequence::Worse;
3929
3930 // C++ [over.ics.rank]p4b2:
3931 //
3932 // If class B is derived directly or indirectly from class A,
3933 // conversion of B* to A* is better than conversion of B* to
3934 // void*, and conversion of A* to void* is better than conversion
3935 // of B* to void*.
3936 bool SCS1ConvertsToVoid
3937 = SCS1.isPointerConversionToVoidPointer(S.Context);
3938 bool SCS2ConvertsToVoid
3939 = SCS2.isPointerConversionToVoidPointer(S.Context);
3940 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3941 // Exactly one of the conversion sequences is a conversion to
3942 // a void pointer; it's the worse conversion.
3943 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3944 : ImplicitConversionSequence::Worse;
3945 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3946 // Neither conversion sequence converts to a void pointer; compare
3947 // their derived-to-base conversions.
3948 if (ImplicitConversionSequence::CompareKind DerivedCK
3949 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3950 return DerivedCK;
3951 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3952 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3953 // Both conversion sequences are conversions to void
3954 // pointers. Compare the source types to determine if there's an
3955 // inheritance relationship in their sources.
3956 QualType FromType1 = SCS1.getFromType();
3957 QualType FromType2 = SCS2.getFromType();
3958
3959 // Adjust the types we're converting from via the array-to-pointer
3960 // conversion, if we need to.
3961 if (SCS1.First == ICK_Array_To_Pointer)
3962 FromType1 = S.Context.getArrayDecayedType(FromType1);
3963 if (SCS2.First == ICK_Array_To_Pointer)
3964 FromType2 = S.Context.getArrayDecayedType(FromType2);
3965
3966 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3967 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3968
3969 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3970 return ImplicitConversionSequence::Better;
3971 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3972 return ImplicitConversionSequence::Worse;
3973
3974 // Objective-C++: If one interface is more specific than the
3975 // other, it is the better one.
3976 const ObjCObjectPointerType* FromObjCPtr1
3977 = FromType1->getAs<ObjCObjectPointerType>();
3978 const ObjCObjectPointerType* FromObjCPtr2
3979 = FromType2->getAs<ObjCObjectPointerType>();
3980 if (FromObjCPtr1 && FromObjCPtr2) {
3981 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3982 FromObjCPtr2);
3983 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3984 FromObjCPtr1);
3985 if (AssignLeft != AssignRight) {
3986 return AssignLeft? ImplicitConversionSequence::Better
3987 : ImplicitConversionSequence::Worse;
3988 }
3989 }
3990 }
3991
3992 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3993 // Check for a better reference binding based on the kind of bindings.
3994 if (isBetterReferenceBindingKind(SCS1, SCS2))
3995 return ImplicitConversionSequence::Better;
3996 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3997 return ImplicitConversionSequence::Worse;
3998 }
3999
4000 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4001 // bullet 3).
4002 if (ImplicitConversionSequence::CompareKind QualCK
4003 = CompareQualificationConversions(S, SCS1, SCS2))
4004 return QualCK;
4005
4006 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4007 // C++ [over.ics.rank]p3b4:
4008 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4009 // which the references refer are the same type except for
4010 // top-level cv-qualifiers, and the type to which the reference
4011 // initialized by S2 refers is more cv-qualified than the type
4012 // to which the reference initialized by S1 refers.
4013 QualType T1 = SCS1.getToType(2);
4014 QualType T2 = SCS2.getToType(2);
4015 T1 = S.Context.getCanonicalType(T1);
4016 T2 = S.Context.getCanonicalType(T2);
4017 Qualifiers T1Quals, T2Quals;
4018 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4019 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4020 if (UnqualT1 == UnqualT2) {
4021 // Objective-C++ ARC: If the references refer to objects with different
4022 // lifetimes, prefer bindings that don't change lifetime.
4023 if (SCS1.ObjCLifetimeConversionBinding !=
4024 SCS2.ObjCLifetimeConversionBinding) {
4025 return SCS1.ObjCLifetimeConversionBinding
4026 ? ImplicitConversionSequence::Worse
4027 : ImplicitConversionSequence::Better;
4028 }
4029
4030 // If the type is an array type, promote the element qualifiers to the
4031 // type for comparison.
4032 if (isa<ArrayType>(T1) && T1Quals)
4033 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4034 if (isa<ArrayType>(T2) && T2Quals)
4035 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4036 if (T2.isMoreQualifiedThan(T1))
4037 return ImplicitConversionSequence::Better;
4038 if (T1.isMoreQualifiedThan(T2))
4039 return ImplicitConversionSequence::Worse;
4040 }
4041 }
4042
4043 // In Microsoft mode, prefer an integral conversion to a
4044 // floating-to-integral conversion if the integral conversion
4045 // is between types of the same size.
4046 // For example:
4047 // void f(float);
4048 // void f(int);
4049 // int main {
4050 // long a;
4051 // f(a);
4052 // }
4053 // Here, MSVC will call f(int) instead of generating a compile error
4054 // as clang will do in standard mode.
4055 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4056 SCS2.Second == ICK_Floating_Integral &&
4057 S.Context.getTypeSize(SCS1.getFromType()) ==
4058 S.Context.getTypeSize(SCS1.getToType(2)))
4059 return ImplicitConversionSequence::Better;
4060
4061 // Prefer a compatible vector conversion over a lax vector conversion
4062 // For example:
4063 //
4064 // typedef float __v4sf __attribute__((__vector_size__(16)));
4065 // void f(vector float);
4066 // void f(vector signed int);
4067 // int main() {
4068 // __v4sf a;
4069 // f(a);
4070 // }
4071 // Here, we'd like to choose f(vector float) and not
4072 // report an ambiguous call error
4073 if (SCS1.Second == ICK_Vector_Conversion &&
4074 SCS2.Second == ICK_Vector_Conversion) {
4075 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4076 SCS1.getFromType(), SCS1.getToType(2));
4077 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4078 SCS2.getFromType(), SCS2.getToType(2));
4079
4080 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4081 return SCS1IsCompatibleVectorConversion
4082 ? ImplicitConversionSequence::Better
4083 : ImplicitConversionSequence::Worse;
4084 }
4085
4086 return ImplicitConversionSequence::Indistinguishable;
4087}
4088
4089/// CompareQualificationConversions - Compares two standard conversion
4090/// sequences to determine whether they can be ranked based on their
4091/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4092static ImplicitConversionSequence::CompareKind
4093CompareQualificationConversions(Sema &S,
4094 const StandardConversionSequence& SCS1,
4095 const StandardConversionSequence& SCS2) {
4096 // C++ 13.3.3.2p3:
4097 // -- S1 and S2 differ only in their qualification conversion and
4098 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
4099 // cv-qualification signature of type T1 is a proper subset of
4100 // the cv-qualification signature of type T2, and S1 is not the
4101 // deprecated string literal array-to-pointer conversion (4.2).
4102 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4103 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4104 return ImplicitConversionSequence::Indistinguishable;
4105
4106 // FIXME: the example in the standard doesn't use a qualification
4107 // conversion (!)
4108 QualType T1 = SCS1.getToType(2);
4109 QualType T2 = SCS2.getToType(2);
4110 T1 = S.Context.getCanonicalType(T1);
4111 T2 = S.Context.getCanonicalType(T2);
4112 assert(!T1->isReferenceType() && !T2->isReferenceType())((!T1->isReferenceType() && !T2->isReferenceType
()) ? static_cast<void> (0) : __assert_fail ("!T1->isReferenceType() && !T2->isReferenceType()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4112, __PRETTY_FUNCTION__))
;
4113 Qualifiers T1Quals, T2Quals;
4114 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4115 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4116
4117 // If the types are the same, we won't learn anything by unwrapping
4118 // them.
4119 if (UnqualT1 == UnqualT2)
4120 return ImplicitConversionSequence::Indistinguishable;
4121
4122 ImplicitConversionSequence::CompareKind Result
4123 = ImplicitConversionSequence::Indistinguishable;
4124
4125 // Objective-C++ ARC:
4126 // Prefer qualification conversions not involving a change in lifetime
4127 // to qualification conversions that do not change lifetime.
4128 if (SCS1.QualificationIncludesObjCLifetime !=
4129 SCS2.QualificationIncludesObjCLifetime) {
4130 Result = SCS1.QualificationIncludesObjCLifetime
4131 ? ImplicitConversionSequence::Worse
4132 : ImplicitConversionSequence::Better;
4133 }
4134
4135 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4136 // Within each iteration of the loop, we check the qualifiers to
4137 // determine if this still looks like a qualification
4138 // conversion. Then, if all is well, we unwrap one more level of
4139 // pointers or pointers-to-members and do it all again
4140 // until there are no more pointers or pointers-to-members left
4141 // to unwrap. This essentially mimics what
4142 // IsQualificationConversion does, but here we're checking for a
4143 // strict subset of qualifiers.
4144 if (T1.getQualifiers().withoutObjCLifetime() ==
4145 T2.getQualifiers().withoutObjCLifetime())
4146 // The qualifiers are the same, so this doesn't tell us anything
4147 // about how the sequences rank.
4148 // ObjC ownership quals are omitted above as they interfere with
4149 // the ARC overload rule.
4150 ;
4151 else if (T2.isMoreQualifiedThan(T1)) {
4152 // T1 has fewer qualifiers, so it could be the better sequence.
4153 if (Result == ImplicitConversionSequence::Worse)
4154 // Neither has qualifiers that are a subset of the other's
4155 // qualifiers.
4156 return ImplicitConversionSequence::Indistinguishable;
4157
4158 Result = ImplicitConversionSequence::Better;
4159 } else if (T1.isMoreQualifiedThan(T2)) {
4160 // T2 has fewer qualifiers, so it could be the better sequence.
4161 if (Result == ImplicitConversionSequence::Better)
4162 // Neither has qualifiers that are a subset of the other's
4163 // qualifiers.
4164 return ImplicitConversionSequence::Indistinguishable;
4165
4166 Result = ImplicitConversionSequence::Worse;
4167 } else {
4168 // Qualifiers are disjoint.
4169 return ImplicitConversionSequence::Indistinguishable;
4170 }
4171
4172 // If the types after this point are equivalent, we're done.
4173 if (S.Context.hasSameUnqualifiedType(T1, T2))
4174 break;
4175 }
4176
4177 // Check that the winning standard conversion sequence isn't using
4178 // the deprecated string literal array to pointer conversion.
4179 switch (Result) {
4180 case ImplicitConversionSequence::Better:
4181 if (SCS1.DeprecatedStringLiteralToCharPtr)
4182 Result = ImplicitConversionSequence::Indistinguishable;
4183 break;
4184
4185 case ImplicitConversionSequence::Indistinguishable:
4186 break;
4187
4188 case ImplicitConversionSequence::Worse:
4189 if (SCS2.DeprecatedStringLiteralToCharPtr)
4190 Result = ImplicitConversionSequence::Indistinguishable;
4191 break;
4192 }
4193
4194 return Result;
4195}
4196
4197/// CompareDerivedToBaseConversions - Compares two standard conversion
4198/// sequences to determine whether they can be ranked based on their
4199/// various kinds of derived-to-base conversions (C++
4200/// [over.ics.rank]p4b3). As part of these checks, we also look at
4201/// conversions between Objective-C interface types.
4202static ImplicitConversionSequence::CompareKind
4203CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4204 const StandardConversionSequence& SCS1,
4205 const StandardConversionSequence& SCS2) {
4206 QualType FromType1 = SCS1.getFromType();
4207 QualType ToType1 = SCS1.getToType(1);
4208 QualType FromType2 = SCS2.getFromType();
4209 QualType ToType2 = SCS2.getToType(1);
4210
4211 // Adjust the types we're converting from via the array-to-pointer
4212 // conversion, if we need to.
4213 if (SCS1.First == ICK_Array_To_Pointer)
4214 FromType1 = S.Context.getArrayDecayedType(FromType1);
4215 if (SCS2.First == ICK_Array_To_Pointer)
4216 FromType2 = S.Context.getArrayDecayedType(FromType2);
4217
4218 // Canonicalize all of the types.
4219 FromType1 = S.Context.getCanonicalType(FromType1);
4220 ToType1 = S.Context.getCanonicalType(ToType1);
4221 FromType2 = S.Context.getCanonicalType(FromType2);
4222 ToType2 = S.Context.getCanonicalType(ToType2);
4223
4224 // C++ [over.ics.rank]p4b3:
4225 //
4226 // If class B is derived directly or indirectly from class A and
4227 // class C is derived directly or indirectly from B,
4228 //
4229 // Compare based on pointer conversions.
4230 if (SCS1.Second == ICK_Pointer_Conversion &&
4231 SCS2.Second == ICK_Pointer_Conversion &&
4232 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4233 FromType1->isPointerType() && FromType2->isPointerType() &&
4234 ToType1->isPointerType() && ToType2->isPointerType()) {
4235 QualType FromPointee1 =
4236 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4237 QualType ToPointee1 =
4238 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4239 QualType FromPointee2 =
4240 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4241 QualType ToPointee2 =
4242 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4243
4244 // -- conversion of C* to B* is better than conversion of C* to A*,
4245 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4246 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4247 return ImplicitConversionSequence::Better;
4248 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4249 return ImplicitConversionSequence::Worse;
4250 }
4251
4252 // -- conversion of B* to A* is better than conversion of C* to A*,
4253 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4254 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4255 return ImplicitConversionSequence::Better;
4256 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4257 return ImplicitConversionSequence::Worse;
4258 }
4259 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4260 SCS2.Second == ICK_Pointer_Conversion) {
4261 const ObjCObjectPointerType *FromPtr1
4262 = FromType1->getAs<ObjCObjectPointerType>();
4263 const ObjCObjectPointerType *FromPtr2
4264 = FromType2->getAs<ObjCObjectPointerType>();
4265 const ObjCObjectPointerType *ToPtr1
4266 = ToType1->getAs<ObjCObjectPointerType>();
4267 const ObjCObjectPointerType *ToPtr2
4268 = ToType2->getAs<ObjCObjectPointerType>();
4269
4270 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4271 // Apply the same conversion ranking rules for Objective-C pointer types
4272 // that we do for C++ pointers to class types. However, we employ the
4273 // Objective-C pseudo-subtyping relationship used for assignment of
4274 // Objective-C pointer types.
4275 bool FromAssignLeft
4276 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4277 bool FromAssignRight
4278 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4279 bool ToAssignLeft
4280 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4281 bool ToAssignRight
4282 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4283
4284 // A conversion to an a non-id object pointer type or qualified 'id'
4285 // type is better than a conversion to 'id'.
4286 if (ToPtr1->isObjCIdType() &&
4287 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4288 return ImplicitConversionSequence::Worse;
4289 if (ToPtr2->isObjCIdType() &&
4290 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4291 return ImplicitConversionSequence::Better;
4292
4293 // A conversion to a non-id object pointer type is better than a
4294 // conversion to a qualified 'id' type
4295 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4296 return ImplicitConversionSequence::Worse;
4297 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4298 return ImplicitConversionSequence::Better;
4299
4300 // A conversion to an a non-Class object pointer type or qualified 'Class'
4301 // type is better than a conversion to 'Class'.
4302 if (ToPtr1->isObjCClassType() &&
4303 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4304 return ImplicitConversionSequence::Worse;
4305 if (ToPtr2->isObjCClassType() &&
4306 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4307 return ImplicitConversionSequence::Better;
4308
4309 // A conversion to a non-Class object pointer type is better than a
4310 // conversion to a qualified 'Class' type.
4311 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4312 return ImplicitConversionSequence::Worse;
4313 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4314 return ImplicitConversionSequence::Better;
4315
4316 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4317 if (S.Context.hasSameType(FromType1, FromType2) &&
4318 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4319 (ToAssignLeft != ToAssignRight)) {
4320 if (FromPtr1->isSpecialized()) {
4321 // "conversion of B<A> * to B * is better than conversion of B * to
4322 // C *.
4323 bool IsFirstSame =
4324 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4325 bool IsSecondSame =
4326 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4327 if (IsFirstSame) {
4328 if (!IsSecondSame)
4329 return ImplicitConversionSequence::Better;
4330 } else if (IsSecondSame)
4331 return ImplicitConversionSequence::Worse;
4332 }
4333 return ToAssignLeft? ImplicitConversionSequence::Worse
4334 : ImplicitConversionSequence::Better;
4335 }
4336
4337 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4338 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4339 (FromAssignLeft != FromAssignRight))
4340 return FromAssignLeft? ImplicitConversionSequence::Better
4341 : ImplicitConversionSequence::Worse;
4342 }
4343 }
4344
4345 // Ranking of member-pointer types.
4346 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4347 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4348 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4349 const MemberPointerType * FromMemPointer1 =
4350 FromType1->getAs<MemberPointerType>();
4351 const MemberPointerType * ToMemPointer1 =
4352 ToType1->getAs<MemberPointerType>();
4353 const MemberPointerType * FromMemPointer2 =
4354 FromType2->getAs<MemberPointerType>();
4355 const MemberPointerType * ToMemPointer2 =
4356 ToType2->getAs<MemberPointerType>();
4357 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4358 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4359 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4360 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4361 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4362 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4363 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4364 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4365 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4366 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4367 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4368 return ImplicitConversionSequence::Worse;
4369 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4370 return ImplicitConversionSequence::Better;
4371 }
4372 // conversion of B::* to C::* is better than conversion of A::* to C::*
4373 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4374 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4375 return ImplicitConversionSequence::Better;
4376 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4377 return ImplicitConversionSequence::Worse;
4378 }
4379 }
4380
4381 if (SCS1.Second == ICK_Derived_To_Base) {
4382 // -- conversion of C to B is better than conversion of C to A,
4383 // -- binding of an expression of type C to a reference of type
4384 // B& is better than binding an expression of type C to a
4385 // reference of type A&,
4386 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4387 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4388 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4389 return ImplicitConversionSequence::Better;
4390 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4391 return ImplicitConversionSequence::Worse;
4392 }
4393
4394 // -- conversion of B to A is better than conversion of C to A.
4395 // -- binding of an expression of type B to a reference of type
4396 // A& is better than binding an expression of type C to a
4397 // reference of type A&,
4398 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4399 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4400 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4401 return ImplicitConversionSequence::Better;
4402 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4403 return ImplicitConversionSequence::Worse;
4404 }
4405 }
4406
4407 return ImplicitConversionSequence::Indistinguishable;
4408}
4409
4410/// Determine whether the given type is valid, e.g., it is not an invalid
4411/// C++ class.
4412static bool isTypeValid(QualType T) {
4413 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4414 return !Record->isInvalidDecl();
4415
4416 return true;
4417}
4418
4419static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4420 if (!T.getQualifiers().hasUnaligned())
4421 return T;
4422
4423 Qualifiers Q;
4424 T = Ctx.getUnqualifiedArrayType(T, Q);
4425 Q.removeUnaligned();
4426 return Ctx.getQualifiedType(T, Q);
4427}
4428
4429/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4430/// determine whether they are reference-compatible,
4431/// reference-related, or incompatible, for use in C++ initialization by
4432/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4433/// type, and the first type (T1) is the pointee type of the reference
4434/// type being initialized.
4435Sema::ReferenceCompareResult
4436Sema::CompareReferenceRelationship(SourceLocation Loc,
4437 QualType OrigT1, QualType OrigT2,
4438 ReferenceConversions *ConvOut) {
4439 assert(!OrigT1->isReferenceType() &&((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4440, __PRETTY_FUNCTION__))
4440 "T1 must be the pointee type of the reference type")((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4440, __PRETTY_FUNCTION__))
;
4441 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")((!OrigT2->isReferenceType() && "T2 cannot be a reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4441, __PRETTY_FUNCTION__))
;
4442
4443 QualType T1 = Context.getCanonicalType(OrigT1);
4444 QualType T2 = Context.getCanonicalType(OrigT2);
4445 Qualifiers T1Quals, T2Quals;
4446 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4447 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4448
4449 ReferenceConversions ConvTmp;
4450 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4451 Conv = ReferenceConversions();
4452
4453 // C++2a [dcl.init.ref]p4:
4454 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4455 // reference-related to "cv2 T2" if T1 is similar to T2, or
4456 // T1 is a base class of T2.
4457 // "cv1 T1" is reference-compatible with "cv2 T2" if
4458 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4459 // "pointer to cv1 T1" via a standard conversion sequence.
4460
4461 // Check for standard conversions we can apply to pointers: derived-to-base
4462 // conversions, ObjC pointer conversions, and function pointer conversions.
4463 // (Qualification conversions are checked last.)
4464 QualType ConvertedT2;
4465 if (UnqualT1 == UnqualT2) {
4466 // Nothing to do.
4467 } else if (isCompleteType(Loc, OrigT2) &&
4468 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4469 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4470 Conv |= ReferenceConversions::DerivedToBase;
4471 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4472 UnqualT2->isObjCObjectOrInterfaceType() &&
4473 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4474 Conv |= ReferenceConversions::ObjC;
4475 else if (UnqualT2->isFunctionType() &&
4476 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4477 Conv |= ReferenceConversions::Function;
4478 // No need to check qualifiers; function types don't have them.
4479 return Ref_Compatible;
4480 }
4481 bool ConvertedReferent = Conv != 0;
4482
4483 // We can have a qualification conversion. Compute whether the types are
4484 // similar at the same time.
4485 bool PreviousToQualsIncludeConst = true;
4486 bool TopLevel = true;
4487 do {
4488 if (T1 == T2)
4489 break;
4490
4491 // We will need a qualification conversion.
4492 Conv |= ReferenceConversions::Qualification;
4493
4494 // Track whether we performed a qualification conversion anywhere other
4495 // than the top level. This matters for ranking reference bindings in
4496 // overload resolution.
4497 if (!TopLevel)
4498 Conv |= ReferenceConversions::NestedQualification;
4499
4500 // MS compiler ignores __unaligned qualifier for references; do the same.
4501 T1 = withoutUnaligned(Context, T1);
4502 T2 = withoutUnaligned(Context, T2);
4503
4504 // If we find a qualifier mismatch, the types are not reference-compatible,
4505 // but are still be reference-related if they're similar.
4506 bool ObjCLifetimeConversion = false;
4507 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false,
4508 PreviousToQualsIncludeConst,
4509 ObjCLifetimeConversion))
4510 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4511 ? Ref_Related
4512 : Ref_Incompatible;
4513
4514 // FIXME: Should we track this for any level other than the first?
4515 if (ObjCLifetimeConversion)
4516 Conv |= ReferenceConversions::ObjCLifetime;
4517
4518 TopLevel = false;
4519 } while (Context.UnwrapSimilarTypes(T1, T2));
4520
4521 // At this point, if the types are reference-related, we must either have the
4522 // same inner type (ignoring qualifiers), or must have already worked out how
4523 // to convert the referent.
4524 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4525 ? Ref_Compatible
4526 : Ref_Incompatible;
4527}
4528
4529/// Look for a user-defined conversion to a value reference-compatible
4530/// with DeclType. Return true if something definite is found.
4531static bool
4532FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4533 QualType DeclType, SourceLocation DeclLoc,
4534 Expr *Init, QualType T2, bool AllowRvalues,
4535 bool AllowExplicit) {
4536 assert(T2->isRecordType() && "Can only find conversions of record types.")((T2->isRecordType() && "Can only find conversions of record types."
) ? static_cast<void> (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4536, __PRETTY_FUNCTION__))
;
4537 CXXRecordDecl *T2RecordDecl
4538 = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4539
4540 OverloadCandidateSet CandidateSet(
4541 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4542 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4543 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4544 NamedDecl *D = *I;
4545 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4546 if (isa<UsingShadowDecl>(D))
4547 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4548
4549 FunctionTemplateDecl *ConvTemplate
4550 = dyn_cast<FunctionTemplateDecl>(D);
4551 CXXConversionDecl *Conv;
4552 if (ConvTemplate)
4553 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4554 else
4555 Conv = cast<CXXConversionDecl>(D);
4556
4557 if (AllowRvalues) {
4558 // If we are initializing an rvalue reference, don't permit conversion
4559 // functions that return lvalues.
4560 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4561 const ReferenceType *RefType
4562 = Conv->getConversionType()->getAs<LValueReferenceType>();
4563 if (RefType && !RefType->getPointeeType()->isFunctionType())
4564 continue;
4565 }
4566
4567 if (!ConvTemplate &&
4568 S.CompareReferenceRelationship(
4569 DeclLoc,
4570 Conv->getConversionType()
4571 .getNonReferenceType()
4572 .getUnqualifiedType(),
4573 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4574 Sema::Ref_Incompatible)
4575 continue;
4576 } else {
4577 // If the conversion function doesn't return a reference type,
4578 // it can't be considered for this conversion. An rvalue reference
4579 // is only acceptable if its referencee is a function type.
4580
4581 const ReferenceType *RefType =
4582 Conv->getConversionType()->getAs<ReferenceType>();
4583 if (!RefType ||
4584 (!RefType->isLValueReferenceType() &&
4585 !RefType->getPointeeType()->isFunctionType()))
4586 continue;
4587 }
4588
4589 if (ConvTemplate)
4590 S.AddTemplateConversionCandidate(
4591 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4592 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4593 else
4594 S.AddConversionCandidate(
4595 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4596 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4597 }
4598
4599 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4600
4601 OverloadCandidateSet::iterator Best;
4602 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4603 case OR_Success:
4604 // C++ [over.ics.ref]p1:
4605 //
4606 // [...] If the parameter binds directly to the result of
4607 // applying a conversion function to the argument
4608 // expression, the implicit conversion sequence is a
4609 // user-defined conversion sequence (13.3.3.1.2), with the
4610 // second standard conversion sequence either an identity
4611 // conversion or, if the conversion function returns an
4612 // entity of a type that is a derived class of the parameter
4613 // type, a derived-to-base Conversion.
4614 if (!Best->FinalConversion.DirectBinding)
4615 return false;
4616
4617 ICS.setUserDefined();
4618 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4619 ICS.UserDefined.After = Best->FinalConversion;
4620 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4621 ICS.UserDefined.ConversionFunction = Best->Function;
4622 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4623 ICS.UserDefined.EllipsisConversion = false;
4624 assert(ICS.UserDefined.After.ReferenceBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4626, __PRETTY_FUNCTION__))
4625 ICS.UserDefined.After.DirectBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4626, __PRETTY_FUNCTION__))
4626 "Expected a direct reference binding!")((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4626, __PRETTY_FUNCTION__))
;
4627 return true;
4628
4629 case OR_Ambiguous:
4630 ICS.setAmbiguous();
4631 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4632 Cand != CandidateSet.end(); ++Cand)
4633 if (Cand->Best)
4634 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4635 return true;
4636
4637 case OR_No_Viable_Function:
4638 case OR_Deleted:
4639 // There was no suitable conversion, or we found a deleted
4640 // conversion; continue with other checks.
4641 return false;
4642 }
4643
4644 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4644)
;
4645}
4646
4647/// Compute an implicit conversion sequence for reference
4648/// initialization.
4649static ImplicitConversionSequence
4650TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4651 SourceLocation DeclLoc,
4652 bool SuppressUserConversions,
4653 bool AllowExplicit) {
4654 assert(DeclType->isReferenceType() && "Reference init needs a reference")((DeclType->isReferenceType() && "Reference init needs a reference"
) ? static_cast<void> (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 4654, __PRETTY_FUNCTION__))
;
4655
4656 // Most paths end in a failed conversion.
4657 ImplicitConversionSequence ICS;
4658 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4659
4660 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4661 QualType T2 = Init->getType();
4662
4663 // If the initializer is the address of an overloaded function, try
4664 // to resolve the overloaded function. If all goes well, T2 is the
4665 // type of the resulting function.
4666 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4667 DeclAccessPair Found;
4668 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4669 false, Found))
4670 T2 = Fn->getType();
4671 }
4672
4673 // Compute some basic properties of the types and the initializer.
4674 bool isRValRef = DeclType->isRValueReferenceType();
4675 Expr::Classification InitCategory = Init->Classify(S.Context);
4676
4677 Sema::ReferenceConversions RefConv;
4678 Sema::ReferenceCompareResult RefRelationship =
4679 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4680
4681 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4682 ICS.setStandard();
4683 ICS.Standard.First = ICK_Identity;
4684 // FIXME: A reference binding can be a function conversion too. We should
4685 // consider that when ordering reference-to-function bindings.
4686 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4687 ? ICK_Derived_To_Base
4688 : (RefConv & Sema::ReferenceConversions::ObjC)
4689 ? ICK_Compatible_Conversion
4690 : ICK_Identity;
4691 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4692 // a reference binding that performs a non-top-level qualification
4693 // conversion as a qualification conversion, not as an identity conversion.
4694 ICS.Standard.Third = (RefConv &
4695 Sema::ReferenceConversions::NestedQualification)
4696 ? ICK_Qualification
4697 : ICK_Identity;
4698 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4699 ICS.Standard.setToType(0, T2);
4700 ICS.Standard.setToType(1, T1);
4701 ICS.Standard.setToType(2, T1);
4702 ICS.Standard.ReferenceBinding = true;
4703 ICS.Standard.DirectBinding = BindsDirectly;
4704 ICS.Standard.IsLvalueReference = !isRValRef;
4705 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4706 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4707 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4708 ICS.Standard.ObjCLifetimeConversionBinding =
4709 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4710 ICS.Standard.CopyConstructor = nullptr;
4711 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4712 };
4713
4714 // C++0x [dcl.init.ref]p5:
4715 // A reference to type "cv1 T1" is initialized by an expression
4716 // of type "cv2 T2" as follows:
4717
4718 // -- If reference is an lvalue reference and the initializer expression
4719 if (!isRValRef) {
4720 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4721 // reference-compatible with "cv2 T2," or
4722 //
4723 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4724 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4725 // C++ [over.ics.ref]p1:
4726 // When a parameter of reference type binds directly (8.5.3)
4727 // to an argument expression, the implicit conversion sequence
4728 // is the identity conversion, unless the argument expression
4729 // has a type that is a derived class of the parameter type,
4730 // in which case the implicit conversion sequence is a
4731 // derived-to-base Conversion (13.3.3.1).
4732 SetAsReferenceBinding(/*BindsDirectly=*/true);
4733
4734 // Nothing more to do: the inaccessibility/ambiguity check for
4735 // derived-to-base conversions is suppressed when we're
4736 // computing the implicit conversion sequence (C++
4737 // [over.best.ics]p2).
4738 return ICS;
4739 }
4740
4741 // -- has a class type (i.e., T2 is a class type), where T1 is
4742 // not reference-related to T2, and can be implicitly
4743 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4744 // is reference-compatible with "cv3 T3" 92) (this
4745 // conversion is selected by enumerating the applicable
4746 // conversion functions (13.3.1.6) and choosing the best
4747 // one through overload resolution (13.3)),
4748 if (!SuppressUserConversions && T2->isRecordType() &&
4749 S.isCompleteType(DeclLoc, T2) &&
4750 RefRelationship == Sema::Ref_Incompatible) {
4751 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4752 Init, T2, /*AllowRvalues=*/false,
4753 AllowExplicit))
4754 return ICS;
4755 }
4756 }
4757
4758 // -- Otherwise, the reference shall be an lvalue reference to a
4759 // non-volatile const type (i.e., cv1 shall be const), or the reference
4760 // shall be an rvalue reference.
4761 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4762 return ICS;
4763
4764 // -- If the initializer expression
4765 //
4766 // -- is an xvalue, class prvalue, array prvalue or function
4767 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4768 if (RefRelationship == Sema::Ref_Compatible &&
4769 (InitCategory.isXValue() ||
4770 (InitCategory.isPRValue() &&
4771 (T2->isRecordType() || T2->isArrayType())) ||
4772 (InitCategory.isLValue() && T2->isFunctionType()))) {
4773 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4774 // binding unless we're binding to a class prvalue.
4775 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4776 // allow the use of rvalue references in C++98/03 for the benefit of
4777 // standard library implementors; therefore, we need the xvalue check here.
4778 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4779 !(InitCategory.isPRValue() || T2->isRecordType()));
4780 return ICS;
4781 }
4782
4783 // -- has a class type (i.e., T2 is a class type), where T1 is not
4784 // reference-related to T2, and can be implicitly converted to
4785 // an xvalue, class prvalue, or function lvalue of type
4786 // "cv3 T3", where "cv1 T1" is reference-compatible with
4787 // "cv3 T3",
4788 //
4789 // then the reference is bound to the value of the initializer
4790 // expression in the first case and to the result of the conversion
4791 // in the second case (or, in either case, to an appropriate base
4792 // class subobject).
4793 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4794 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4795 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4796 Init, T2, /*AllowRvalues=*/true,
4797 AllowExplicit)) {
4798 // In the second case, if the reference is an rvalue reference
4799 // and the second standard conversion sequence of the
4800 // user-defined conversion sequence includes an lvalue-to-rvalue
4801 // conversion, the program is ill-formed.
4802 if (ICS.isUserDefined() && isRValRef &&
4803 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4804 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4805
4806 return ICS;
4807 }
4808
4809 // A temporary of function type cannot be created; don't even try.
4810 if (T1->isFunctionType())
4811 return ICS;
4812
4813 // -- Otherwise, a temporary of type "cv1 T1" is created and
4814 // initialized from the initializer expression using the
4815 // rules for a non-reference copy initialization (8.5). The
4816 // reference is then bound to the temporary. If T1 is
4817 // reference-related to T2, cv1 must be the same
4818 // cv-qualification as, or greater cv-qualification than,
4819 // cv2; otherwise, the program is ill-formed.
4820 if (RefRelationship == Sema::Ref_Related) {
4821 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4822 // we would be reference-compatible or reference-compatible with
4823 // added qualification. But that wasn't the case, so the reference
4824 // initialization fails.
4825 //
4826 // Note that we only want to check address spaces and cvr-qualifiers here.
4827 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4828 Qualifiers T1Quals = T1.getQualifiers();
4829 Qualifiers T2Quals = T2.getQualifiers();
4830 T1Quals.removeObjCGCAttr();
4831 T1Quals.removeObjCLifetime();
4832 T2Quals.removeObjCGCAttr();
4833 T2Quals.removeObjCLifetime();
4834 // MS compiler ignores __unaligned qualifier for references; do the same.
4835 T1Quals.removeUnaligned();
4836 T2Quals.removeUnaligned();
4837 if (!T1Quals.compatiblyIncludes(T2Quals))
4838 return ICS;
4839 }
4840
4841 // If at least one of the types is a class type, the types are not
4842 // related, and we aren't allowed any user conversions, the
4843 // reference binding fails. This case is important for breaking
4844 // recursion, since TryImplicitConversion below will attempt to
4845 // create a temporary through the use of a copy constructor.
4846 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4847 (T1->isRecordType() || T2->isRecordType()))
4848 return ICS;
4849
4850 // If T1 is reference-related to T2 and the reference is an rvalue
4851 // reference, the initializer expression shall not be an lvalue.
4852 if (RefRelationship >= Sema::Ref_Related &&
4853 isRValRef && Init->Classify(S.Context).isLValue())
4854 return ICS;
4855
4856 // C++ [over.ics.ref]p2:
4857 // When a parameter of reference type is not bound directly to
4858 // an argument expression, the conversion sequence is the one
4859 // required to convert the argument expression to the
4860 // underlying type of the reference according to
4861 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4862 // to copy-initializing a temporary of the underlying type with
4863 // the argument expression. Any difference in top-level
4864 // cv-qualification is subsumed by the initialization itself
4865 // and does not constitute a conversion.
4866 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4867 /*AllowExplicit=*/false,
4868 /*InOverloadResolution=*/false,
4869 /*CStyle=*/false,
4870 /*AllowObjCWritebackConversion=*/false,
4871 /*AllowObjCConversionOnExplicit=*/false);
4872
4873 // Of course, that's still a reference binding.
4874 if (ICS.isStandard()) {
4875 ICS.Standard.ReferenceBinding = true;
4876 ICS.Standard.IsLvalueReference = !isRValRef;
4877 ICS.Standard.BindsToFunctionLvalue = false;
4878 ICS.Standard.BindsToRvalue = true;
4879 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4880 ICS.Standard.ObjCLifetimeConversionBinding = false;
4881 } else if (ICS.isUserDefined()) {
4882 const ReferenceType *LValRefType =
4883 ICS.UserDefined.ConversionFunction->getReturnType()
4884 ->getAs<LValueReferenceType>();
4885
4886 // C++ [over.ics.ref]p3:
4887 // Except for an implicit object parameter, for which see 13.3.1, a
4888 // standard conversion sequence cannot be formed if it requires [...]
4889 // binding an rvalue reference to an lvalue other than a function
4890 // lvalue.
4891 // Note that the function case is not possible here.
4892 if (DeclType->isRValueReferenceType() && LValRefType) {
4893 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4894 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4895 // reference to an rvalue!
4896 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4897 return ICS;
4898 }
4899
4900 ICS.UserDefined.After.ReferenceBinding = true;
4901 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4902 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4903 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4904 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4905 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4906 }
4907
4908 return ICS;
4909}
4910
4911static ImplicitConversionSequence
4912TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4913 bool SuppressUserConversions,
4914 bool InOverloadResolution,
4915 bool AllowObjCWritebackConversion,
4916 bool AllowExplicit = false);
4917
4918/// TryListConversion - Try to copy-initialize a value of type ToType from the
4919/// initializer list From.
4920static ImplicitConversionSequence
4921TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4922 bool SuppressUserConversions,
4923 bool InOverloadResolution,
4924 bool AllowObjCWritebackConversion) {
4925 // C++11 [over.ics.list]p1:
4926 // When an argument is an initializer list, it is not an expression and
4927 // special rules apply for converting it to a parameter type.
4928
4929 ImplicitConversionSequence Result;
4930 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4931
4932 // We need a complete type for what follows. Incomplete types can never be
4933 // initialized from init lists.
4934 if (!S.isCompleteType(From->getBeginLoc(), ToType))
4935 return Result;
4936
4937 // Per DR1467:
4938 // If the parameter type is a class X and the initializer list has a single
4939 // element of type cv U, where U is X or a class derived from X, the
4940 // implicit conversion sequence is the one required to convert the element
4941 // to the parameter type.
4942 //
4943 // Otherwise, if the parameter type is a character array [... ]
4944 // and the initializer list has a single element that is an
4945 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4946 // implicit conversion sequence is the identity conversion.
4947 if (From->getNumInits() == 1) {
4948 if (ToType->isRecordType()) {
4949 QualType InitType = From->getInit(0)->getType();
4950 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4951 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4952 return TryCopyInitialization(S, From->getInit(0), ToType,
4953 SuppressUserConversions,
4954 InOverloadResolution,
4955 AllowObjCWritebackConversion);
4956 }
4957 // FIXME: Check the other conditions here: array of character type,
4958 // initializer is a string literal.
4959 if (ToType->isArrayType()) {
4960 InitializedEntity Entity =
4961 InitializedEntity::InitializeParameter(S.Context, ToType,
4962 /*Consumed=*/false);
4963 if (S.CanPerformCopyInitialization(Entity, From)) {
4964 Result.setStandard();
4965 Result.Standard.setAsIdentityConversion();
4966 Result.Standard.setFromType(ToType);
4967 Result.Standard.setAllToTypes(ToType);
4968 return Result;
4969 }
4970 }
4971 }
4972
4973 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4974 // C++11 [over.ics.list]p2:
4975 // If the parameter type is std::initializer_list<X> or "array of X" and
4976 // all the elements can be implicitly converted to X, the implicit
4977 // conversion sequence is the worst conversion necessary to convert an
4978 // element of the list to X.
4979 //
4980 // C++14 [over.ics.list]p3:
4981 // Otherwise, if the parameter type is "array of N X", if the initializer
4982 // list has exactly N elements or if it has fewer than N elements and X is
4983 // default-constructible, and if all the elements of the initializer list
4984 // can be implicitly converted to X, the implicit conversion sequence is
4985 // the worst conversion necessary to convert an element of the list to X.
4986 //
4987 // FIXME: We're missing a lot of these checks.
4988 bool toStdInitializerList = false;
4989 QualType X;
4990 if (ToType->isArrayType())
4991 X = S.Context.getAsArrayType(ToType)->getElementType();
4992 else
4993 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4994 if (!X.isNull()) {
4995 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4996 Expr *Init = From->getInit(i);
4997 ImplicitConversionSequence ICS =
4998 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4999 InOverloadResolution,
5000 AllowObjCWritebackConversion);
5001 // If a single element isn't convertible, fail.
5002 if (ICS.isBad()) {
5003 Result = ICS;
5004 break;
5005 }
5006 // Otherwise, look for the worst conversion.
5007 if (Result.isBad() || CompareImplicitConversionSequences(
5008 S, From->getBeginLoc(), ICS, Result) ==
5009 ImplicitConversionSequence::Worse)
5010 Result = ICS;
5011 }
5012
5013 // For an empty list, we won't have computed any conversion sequence.
5014 // Introduce the identity conversion sequence.
5015 if (From->getNumInits() == 0) {
5016 Result.setStandard();
5017 Result.Standard.setAsIdentityConversion();
5018 Result.Standard.setFromType(ToType);
5019 Result.Standard.setAllToTypes(ToType);
5020 }
5021
5022 Result.setStdInitializerListElement(toStdInitializerList);
5023 return Result;
5024 }
5025
5026 // C++14 [over.ics.list]p4:
5027 // C++11 [over.ics.list]p3:
5028 // Otherwise, if the parameter is a non-aggregate class X and overload
5029 // resolution chooses a single best constructor [...] the implicit
5030 // conversion sequence is a user-defined conversion sequence. If multiple
5031 // constructors are viable but none is better than the others, the
5032 // implicit conversion sequence is a user-defined conversion sequence.
5033 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5034 // This function can deal with initializer lists.
5035 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5036 /*AllowExplicit=*/false,
5037 InOverloadResolution, /*CStyle=*/false,
5038 AllowObjCWritebackConversion,
5039 /*AllowObjCConversionOnExplicit=*/false);
5040 }
5041
5042 // C++14 [over.ics.list]p5:
5043 // C++11 [over.ics.list]p4:
5044 // Otherwise, if the parameter has an aggregate type which can be
5045 // initialized from the initializer list [...] the implicit conversion
5046 // sequence is a user-defined conversion sequence.
5047 if (ToType->isAggregateType()) {
5048 // Type is an aggregate, argument is an init list. At this point it comes
5049 // down to checking whether the initialization works.
5050 // FIXME: Find out whether this parameter is consumed or not.
5051 InitializedEntity Entity =
5052 InitializedEntity::InitializeParameter(S.Context, ToType,
5053 /*Consumed=*/false);
5054 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5055 From)) {
5056 Result.setUserDefined();
5057 Result.UserDefined.Before.setAsIdentityConversion();
5058 // Initializer lists don't have a type.
5059 Result.UserDefined.Before.setFromType(QualType());
5060 Result.UserDefined.Before.setAllToTypes(QualType());
5061
5062 Result.UserDefined.After.setAsIdentityConversion();
5063 Result.UserDefined.After.setFromType(ToType);
5064 Result.UserDefined.After.setAllToTypes(ToType);
5065 Result.UserDefined.ConversionFunction = nullptr;
5066 }
5067 return Result;
5068 }
5069
5070 // C++14 [over.ics.list]p6:
5071 // C++11 [over.ics.list]p5:
5072 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5073 if (ToType->isReferenceType()) {
5074 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5075 // mention initializer lists in any way. So we go by what list-
5076 // initialization would do and try to extrapolate from that.
5077
5078 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5079
5080 // If the initializer list has a single element that is reference-related
5081 // to the parameter type, we initialize the reference from that.
5082 if (From->getNumInits() == 1) {
5083 Expr *Init = From->getInit(0);
5084
5085 QualType T2 = Init->getType();
5086
5087 // If the initializer is the address of an overloaded function, try
5088 // to resolve the overloaded function. If all goes well, T2 is the
5089 // type of the resulting function.
5090 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5091 DeclAccessPair Found;
5092 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5093 Init, ToType, false, Found))
5094 T2 = Fn->getType();
5095 }
5096
5097 // Compute some basic properties of the types and the initializer.
5098 Sema::ReferenceCompareResult RefRelationship =
5099 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5100
5101 if (RefRelationship >= Sema::Ref_Related) {
5102 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5103 SuppressUserConversions,
5104 /*AllowExplicit=*/false);
5105 }
5106 }
5107
5108 // Otherwise, we bind the reference to a temporary created from the
5109 // initializer list.
5110 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5111 InOverloadResolution,
5112 AllowObjCWritebackConversion);
5113 if (Result.isFailure())
5114 return Result;
5115 assert(!Result.isEllipsis() &&((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5116, __PRETTY_FUNCTION__))
5116 "Sub-initialization cannot result in ellipsis conversion.")((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5116, __PRETTY_FUNCTION__))
;
5117
5118 // Can we even bind to a temporary?
5119 if (ToType->isRValueReferenceType() ||
5120 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5121 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5122 Result.UserDefined.After;
5123 SCS.ReferenceBinding = true;
5124 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5125 SCS.BindsToRvalue = true;
5126 SCS.BindsToFunctionLvalue = false;
5127 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5128 SCS.ObjCLifetimeConversionBinding = false;
5129 } else
5130 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5131 From, ToType);
5132 return Result;
5133 }
5134
5135 // C++14 [over.ics.list]p7:
5136 // C++11 [over.ics.list]p6:
5137 // Otherwise, if the parameter type is not a class:
5138 if (!ToType->isRecordType()) {
5139 // - if the initializer list has one element that is not itself an
5140 // initializer list, the implicit conversion sequence is the one
5141 // required to convert the element to the parameter type.
5142 unsigned NumInits = From->getNumInits();
5143 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5144 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5145 SuppressUserConversions,
5146 InOverloadResolution,
5147 AllowObjCWritebackConversion);
5148 // - if the initializer list has no elements, the implicit conversion
5149 // sequence is the identity conversion.
5150 else if (NumInits == 0) {
5151 Result.setStandard();
5152 Result.Standard.setAsIdentityConversion();
5153 Result.Standard.setFromType(ToType);
5154 Result.Standard.setAllToTypes(ToType);
5155 }
5156 return Result;
5157 }
5158
5159 // C++14 [over.ics.list]p8:
5160 // C++11 [over.ics.list]p7:
5161 // In all cases other than those enumerated above, no conversion is possible
5162 return Result;
5163}
5164
5165/// TryCopyInitialization - Try to copy-initialize a value of type
5166/// ToType from the expression From. Return the implicit conversion
5167/// sequence required to pass this argument, which may be a bad
5168/// conversion sequence (meaning that the argument cannot be passed to
5169/// a parameter of this type). If @p SuppressUserConversions, then we
5170/// do not permit any user-defined conversion sequences.
5171static ImplicitConversionSequence
5172TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5173 bool SuppressUserConversions,
5174 bool InOverloadResolution,
5175 bool AllowObjCWritebackConversion,
5176 bool AllowExplicit) {
5177 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5178 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5179 InOverloadResolution,AllowObjCWritebackConversion);
5180
5181 if (ToType->isReferenceType())
5182 return TryReferenceInit(S, From, ToType,
5183 /*FIXME:*/ From->getBeginLoc(),
5184 SuppressUserConversions, AllowExplicit);
5185
5186 return TryImplicitConversion(S, From, ToType,
5187 SuppressUserConversions,
5188 /*AllowExplicit=*/false,
5189 InOverloadResolution,
5190 /*CStyle=*/false,
5191 AllowObjCWritebackConversion,
5192 /*AllowObjCConversionOnExplicit=*/false);
5193}
5194
5195static bool TryCopyInitialization(const CanQualType FromQTy,
5196 const CanQualType ToQTy,
5197 Sema &S,
5198 SourceLocation Loc,
5199 ExprValueKind FromVK) {
5200 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5201 ImplicitConversionSequence ICS =
5202 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5203
5204 return !ICS.isBad();
5205}
5206
5207/// TryObjectArgumentInitialization - Try to initialize the object
5208/// parameter of the given member function (@c Method) from the
5209/// expression @p From.
5210static ImplicitConversionSequence
5211TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5212 Expr::Classification FromClassification,
5213 CXXMethodDecl *Method,
5214 CXXRecordDecl *ActingContext) {
5215 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5216 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5217 // const volatile object.
5218 Qualifiers Quals = Method->getMethodQualifiers();
5219 if (isa<CXXDestructorDecl>(Method)) {
5220 Quals.addConst();
5221 Quals.addVolatile();
5222 }
5223
5224 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5225
5226 // Set up the conversion sequence as a "bad" conversion, to allow us
5227 // to exit early.
5228 ImplicitConversionSequence ICS;
5229
5230 // We need to have an object of class type.
5231 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5232 FromType = PT->getPointeeType();
5233
5234 // When we had a pointer, it's implicitly dereferenced, so we
5235 // better have an lvalue.
5236 assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0
) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5236, __PRETTY_FUNCTION__))
;
5237 }
5238
5239 assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) :
__assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5239, __PRETTY_FUNCTION__))
;
5240
5241 // C++0x [over.match.funcs]p4:
5242 // For non-static member functions, the type of the implicit object
5243 // parameter is
5244 //
5245 // - "lvalue reference to cv X" for functions declared without a
5246 // ref-qualifier or with the & ref-qualifier
5247 // - "rvalue reference to cv X" for functions declared with the &&
5248 // ref-qualifier
5249 //
5250 // where X is the class of which the function is a member and cv is the
5251 // cv-qualification on the member function declaration.
5252 //
5253 // However, when finding an implicit conversion sequence for the argument, we
5254 // are not allowed to perform user-defined conversions
5255 // (C++ [over.match.funcs]p5). We perform a simplified version of
5256 // reference binding here, that allows class rvalues to bind to
5257 // non-constant references.
5258
5259 // First check the qualifiers.
5260 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5261 if (ImplicitParamType.getCVRQualifiers()
5262 != FromTypeCanon.getLocalCVRQualifiers() &&
5263 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5264 ICS.setBad(BadConversionSequence::bad_qualifiers,
5265 FromType, ImplicitParamType);
5266 return ICS;
5267 }
5268
5269 if (FromTypeCanon.hasAddressSpace()) {
5270 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5271 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5272 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5273 ICS.setBad(BadConversionSequence::bad_qualifiers,
5274 FromType, ImplicitParamType);
5275 return ICS;
5276 }
5277 }
5278
5279 // Check that we have either the same type or a derived type. It
5280 // affects the conversion rank.
5281 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5282 ImplicitConversionKind SecondKind;
5283 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5284 SecondKind = ICK_Identity;
5285 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5286 SecondKind = ICK_Derived_To_Base;
5287 else {
5288 ICS.setBad(BadConversionSequence::unrelated_class,
5289 FromType, ImplicitParamType);
5290 return ICS;
5291 }
5292
5293 // Check the ref-qualifier.
5294 switch (Method->getRefQualifier()) {
5295 case RQ_None:
5296 // Do nothing; we don't care about lvalueness or rvalueness.
5297 break;
5298
5299 case RQ_LValue:
5300 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5301 // non-const lvalue reference cannot bind to an rvalue
5302 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5303 ImplicitParamType);
5304 return ICS;
5305 }
5306 break;
5307
5308 case RQ_RValue:
5309 if (!FromClassification.isRValue()) {
5310 // rvalue reference cannot bind to an lvalue
5311 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5312 ImplicitParamType);
5313 return ICS;
5314 }
5315 break;
5316 }
5317
5318 // Success. Mark this as a reference binding.
5319 ICS.setStandard();
5320 ICS.Standard.setAsIdentityConversion();
5321 ICS.Standard.Second = SecondKind;
5322 ICS.Standard.setFromType(FromType);
5323 ICS.Standard.setAllToTypes(ImplicitParamType);
5324 ICS.Standard.ReferenceBinding = true;
5325 ICS.Standard.DirectBinding = true;
5326 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5327 ICS.Standard.BindsToFunctionLvalue = false;
5328 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5329 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5330 = (Method->getRefQualifier() == RQ_None);
5331 return ICS;
5332}
5333
5334/// PerformObjectArgumentInitialization - Perform initialization of
5335/// the implicit object parameter for the given Method with the given
5336/// expression.
5337ExprResult
5338Sema::PerformObjectArgumentInitialization(Expr *From,
5339 NestedNameSpecifier *Qualifier,
5340 NamedDecl *FoundDecl,
5341 CXXMethodDecl *Method) {
5342 QualType FromRecordType, DestType;
5343 QualType ImplicitParamRecordType =
5344 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5345
5346 Expr::Classification FromClassification;
5347 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5348 FromRecordType = PT->getPointeeType();
5349 DestType = Method->getThisType();
5350 FromClassification = Expr::Classification::makeSimpleLValue();
5351 } else {
5352 FromRecordType = From->getType();
5353 DestType = ImplicitParamRecordType;
5354 FromClassification = From->Classify(Context);
5355
5356 // When performing member access on an rvalue, materialize a temporary.
5357 if (From->isRValue()) {
5358 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5359 Method->getRefQualifier() !=
5360 RefQualifierKind::RQ_RValue);
5361 }
5362 }
5363
5364 // Note that we always use the true parent context when performing
5365 // the actual argument initialization.
5366 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5367 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5368 Method->getParent());
5369 if (ICS.isBad()) {
5370 switch (ICS.Bad.Kind) {
5371 case BadConversionSequence::bad_qualifiers: {
5372 Qualifiers FromQs = FromRecordType.getQualifiers();
5373 Qualifiers ToQs = DestType.getQualifiers();
5374 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5375 if (CVR) {
5376 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5377 << Method->getDeclName() << FromRecordType << (CVR - 1)
5378 << From->getSourceRange();
5379 Diag(Method->getLocation(), diag::note_previous_decl)
5380 << Method->getDeclName();
5381 return ExprError();
5382 }
5383 break;
5384 }
5385
5386 case BadConversionSequence::lvalue_ref_to_rvalue:
5387 case BadConversionSequence::rvalue_ref_to_lvalue: {
5388 bool IsRValueQualified =
5389 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5390 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5391 << Method->getDeclName() << FromClassification.isRValue()
5392 << IsRValueQualified;
5393 Diag(Method->getLocation(), diag::note_previous_decl)
5394 << Method->getDeclName();
5395 return ExprError();
5396 }
5397
5398 case BadConversionSequence::no_conversion:
5399 case BadConversionSequence::unrelated_class:
5400 break;
5401 }
5402
5403 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5404 << ImplicitParamRecordType << FromRecordType
5405 << From->getSourceRange();
5406 }
5407
5408 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5409 ExprResult FromRes =
5410 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5411 if (FromRes.isInvalid())
5412 return ExprError();
5413 From = FromRes.get();
5414 }
5415
5416 if (!Context.hasSameType(From->getType(), DestType)) {
5417 CastKind CK;
5418 QualType PteeTy = DestType->getPointeeType();
5419 LangAS DestAS =
5420 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5421 if (FromRecordType.getAddressSpace() != DestAS)
5422 CK = CK_AddressSpaceConversion;
5423 else
5424 CK = CK_NoOp;
5425 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5426 }
5427 return From;
5428}
5429
5430/// TryContextuallyConvertToBool - Attempt to contextually convert the
5431/// expression From to bool (C++0x [conv]p3).
5432static ImplicitConversionSequence
5433TryContextuallyConvertToBool(Sema &S, Expr *From) {
5434 return TryImplicitConversion(S, From, S.Context.BoolTy,
5435 /*SuppressUserConversions=*/false,
5436 /*AllowExplicit=*/true,
5437 /*InOverloadResolution=*/false,
5438 /*CStyle=*/false,
5439 /*AllowObjCWritebackConversion=*/false,
5440 /*AllowObjCConversionOnExplicit=*/false);
5441}
5442
5443/// PerformContextuallyConvertToBool - Perform a contextual conversion
5444/// of the expression From to bool (C++0x [conv]p3).
5445ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5446 if (checkPlaceholderForOverload(*this, From))
5447 return ExprError();
5448
5449 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5450 if (!ICS.isBad())
5451 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5452
5453 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5454 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5455 << From->getType() << From->getSourceRange();
5456 return ExprError();
5457}
5458
5459/// Check that the specified conversion is permitted in a converted constant
5460/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5461/// is acceptable.
5462static bool CheckConvertedConstantConversions(Sema &S,
5463 StandardConversionSequence &SCS) {
5464 // Since we know that the target type is an integral or unscoped enumeration
5465 // type, most conversion kinds are impossible. All possible First and Third
5466 // conversions are fine.
5467 switch (SCS.Second) {
5468 case ICK_Identity:
5469 case ICK_Function_Conversion:
5470 case ICK_Integral_Promotion:
5471 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5472 case ICK_Zero_Queue_Conversion:
5473 return true;
5474
5475 case ICK_Boolean_Conversion:
5476 // Conversion from an integral or unscoped enumeration type to bool is
5477 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5478 // conversion, so we allow it in a converted constant expression.
5479 //
5480 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5481 // a lot of popular code. We should at least add a warning for this
5482 // (non-conforming) extension.
5483 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5484 SCS.getToType(2)->isBooleanType();
5485
5486 case ICK_Pointer_Conversion:
5487 case ICK_Pointer_Member:
5488 // C++1z: null pointer conversions and null member pointer conversions are
5489 // only permitted if the source type is std::nullptr_t.
5490 return SCS.getFromType()->isNullPtrType();
5491
5492 case ICK_Floating_Promotion:
5493 case ICK_Complex_Promotion:
5494 case ICK_Floating_Conversion:
5495 case ICK_Complex_Conversion:
5496 case ICK_Floating_Integral:
5497 case ICK_Compatible_Conversion:
5498 case ICK_Derived_To_Base:
5499 case ICK_Vector_Conversion:
5500 case ICK_Vector_Splat:
5501 case ICK_Complex_Real:
5502 case ICK_Block_Pointer_Conversion:
5503 case ICK_TransparentUnionConversion:
5504 case ICK_Writeback_Conversion:
5505 case ICK_Zero_Event_Conversion:
5506 case ICK_C_Only_Conversion:
5507 case ICK_Incompatible_Pointer_Conversion:
5508 return false;
5509
5510 case ICK_Lvalue_To_Rvalue:
5511 case ICK_Array_To_Pointer:
5512 case ICK_Function_To_Pointer:
5513 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5513)
;
5514
5515 case ICK_Qualification:
5516 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5516)
;
5517
5518 case ICK_Num_Conversion_Kinds:
5519 break;
5520 }
5521
5522 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5522)
;
5523}
5524
5525/// CheckConvertedConstantExpression - Check that the expression From is a
5526/// converted constant expression of type T, perform the conversion and produce
5527/// the converted expression, per C++11 [expr.const]p3.
5528static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5529 QualType T, APValue &Value,
5530 Sema::CCEKind CCE,
5531 bool RequireInt) {
5532 assert(S.getLangOpts().CPlusPlus11 &&((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5533, __PRETTY_FUNCTION__))
5533 "converted constant expression outside C++11")((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5533, __PRETTY_FUNCTION__))
;
5534
5535 if (checkPlaceholderForOverload(S, From))
5536 return ExprError();
5537
5538 // C++1z [expr.const]p3:
5539 // A converted constant expression of type T is an expression,
5540 // implicitly converted to type T, where the converted
5541 // expression is a constant expression and the implicit conversion
5542 // sequence contains only [... list of conversions ...].
5543 // C++1z [stmt.if]p2:
5544 // If the if statement is of the form if constexpr, the value of the
5545 // condition shall be a contextually converted constant expression of type
5546 // bool.
5547 ImplicitConversionSequence ICS =
5548 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5549 ? TryContextuallyConvertToBool(S, From)
5550 : TryCopyInitialization(S, From, T,
5551 /*SuppressUserConversions=*/false,
5552 /*InOverloadResolution=*/false,
5553 /*AllowObjCWritebackConversion=*/false,
5554 /*AllowExplicit=*/false);
5555 StandardConversionSequence *SCS = nullptr;
5556 switch (ICS.getKind()) {
5557 case ImplicitConversionSequence::StandardConversion:
5558 SCS = &ICS.Standard;
5559 break;
5560 case ImplicitConversionSequence::UserDefinedConversion:
5561 // We are converting to a non-class type, so the Before sequence
5562 // must be trivial.
5563 SCS = &ICS.UserDefined.After;
5564 break;
5565 case ImplicitConversionSequence::AmbiguousConversion:
5566 case ImplicitConversionSequence::BadConversion:
5567 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5568 return S.Diag(From->getBeginLoc(),
5569 diag::err_typecheck_converted_constant_expression)
5570 << From->getType() << From->getSourceRange() << T;
5571 return ExprError();
5572
5573 case ImplicitConversionSequence::EllipsisConversion:
5574 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5574)
;
5575 }
5576
5577 // Check that we would only use permitted conversions.
5578 if (!CheckConvertedConstantConversions(S, *SCS)) {
5579 return S.Diag(From->getBeginLoc(),
5580 diag::err_typecheck_converted_constant_expression_disallowed)
5581 << From->getType() << From->getSourceRange() << T;
5582 }
5583 // [...] and where the reference binding (if any) binds directly.
5584 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5585 return S.Diag(From->getBeginLoc(),
5586 diag::err_typecheck_converted_constant_expression_indirect)
5587 << From->getType() << From->getSourceRange() << T;
5588 }
5589
5590 ExprResult Result =
5591 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5592 if (Result.isInvalid())
5593 return Result;
5594
5595 // C++2a [intro.execution]p5:
5596 // A full-expression is [...] a constant-expression [...]
5597 Result =
5598 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5599 /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5600 if (Result.isInvalid())
5601 return Result;
5602
5603 // Check for a narrowing implicit conversion.
5604 APValue PreNarrowingValue;
5605 QualType PreNarrowingType;
5606 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5607 PreNarrowingType)) {
5608 case NK_Dependent_Narrowing:
5609 // Implicit conversion to a narrower type, but the expression is
5610 // value-dependent so we can't tell whether it's actually narrowing.
5611 case NK_Variable_Narrowing:
5612 // Implicit conversion to a narrower type, and the value is not a constant
5613 // expression. We'll diagnose this in a moment.
5614 case NK_Not_Narrowing:
5615 break;
5616
5617 case NK_Constant_Narrowing:
5618 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5619 << CCE << /*Constant*/ 1
5620 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5621 break;
5622
5623 case NK_Type_Narrowing:
5624 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5625 << CCE << /*Constant*/ 0 << From->getType() << T;
5626 break;
5627 }
5628
5629 if (Result.get()->isValueDependent()) {
5630 Value = APValue();
5631 return Result;
5632 }
5633
5634 // Check the expression is a constant expression.
5635 SmallVector<PartialDiagnosticAt, 8> Notes;
5636 Expr::EvalResult Eval;
5637 Eval.Diag = &Notes;
5638 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5639 ? Expr::EvaluateForMangling
5640 : Expr::EvaluateForCodeGen;
5641
5642 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5643 (RequireInt && !Eval.Val.isInt())) {
5644 // The expression can't be folded, so we can't keep it at this position in
5645 // the AST.
5646 Result = ExprError();
5647 } else {
5648 Value = Eval.Val;
5649
5650 if (Notes.empty()) {
5651 // It's a constant expression.
5652 return ConstantExpr::Create(S.Context, Result.get(), Value);
5653 }
5654 }
5655
5656 // It's not a constant expression. Produce an appropriate diagnostic.
5657 if (Notes.size() == 1 &&
5658 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5659 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5660 else {
5661 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5662 << CCE << From->getSourceRange();
5663 for (unsigned I = 0; I < Notes.size(); ++I)
5664 S.Diag(Notes[I].first, Notes[I].second);
5665 }
5666 return ExprError();
5667}
5668
5669ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5670 APValue &Value, CCEKind CCE) {
5671 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5672}
5673
5674ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5675 llvm::APSInt &Value,
5676 CCEKind CCE) {
5677 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")((T->isIntegralOrEnumerationType() && "unexpected converted const type"
) ? static_cast<void> (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5677, __PRETTY_FUNCTION__))
;
5678
5679 APValue V;
5680 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5681 if (!R.isInvalid() && !R.get()->isValueDependent())
5682 Value = V.getInt();
5683 return R;
5684}
5685
5686
5687/// dropPointerConversions - If the given standard conversion sequence
5688/// involves any pointer conversions, remove them. This may change
5689/// the result type of the conversion sequence.
5690static void dropPointerConversion(StandardConversionSequence &SCS) {
5691 if (SCS.Second == ICK_Pointer_Conversion) {
5692 SCS.Second = ICK_Identity;
5693 SCS.Third = ICK_Identity;
5694 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5695 }
5696}
5697
5698/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5699/// convert the expression From to an Objective-C pointer type.
5700static ImplicitConversionSequence
5701TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5702 // Do an implicit conversion to 'id'.
5703 QualType Ty = S.Context.getObjCIdType();
5704 ImplicitConversionSequence ICS
5705 = TryImplicitConversion(S, From, Ty,
5706 // FIXME: Are these flags correct?
5707 /*SuppressUserConversions=*/false,
5708 /*AllowExplicit=*/true,
5709 /*InOverloadResolution=*/false,
5710 /*CStyle=*/false,
5711 /*AllowObjCWritebackConversion=*/false,
5712 /*AllowObjCConversionOnExplicit=*/true);
5713
5714 // Strip off any final conversions to 'id'.
5715 switch (ICS.getKind()) {
5716 case ImplicitConversionSequence::BadConversion:
5717 case ImplicitConversionSequence::AmbiguousConversion:
5718 case ImplicitConversionSequence::EllipsisConversion:
5719 break;
5720
5721 case ImplicitConversionSequence::UserDefinedConversion:
5722 dropPointerConversion(ICS.UserDefined.After);
5723 break;
5724
5725 case ImplicitConversionSequence::StandardConversion:
5726 dropPointerConversion(ICS.Standard);
5727 break;
5728 }
5729
5730 return ICS;
5731}
5732
5733/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5734/// conversion of the expression From to an Objective-C pointer type.
5735/// Returns a valid but null ExprResult if no conversion sequence exists.
5736ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5737 if (checkPlaceholderForOverload(*this, From))
5738 return ExprError();
5739
5740 QualType Ty = Context.getObjCIdType();
5741 ImplicitConversionSequence ICS =
5742 TryContextuallyConvertToObjCPointer(*this, From);
5743 if (!ICS.isBad())
5744 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5745 return ExprResult();
5746}
5747
5748/// Determine whether the provided type is an integral type, or an enumeration
5749/// type of a permitted flavor.
5750bool Sema::ICEConvertDiagnoser::match(QualType T) {
5751 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5752 : T->isIntegralOrUnscopedEnumerationType();
5753}
5754
5755static ExprResult
5756diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5757 Sema::ContextualImplicitConverter &Converter,
5758 QualType T, UnresolvedSetImpl &ViableConversions) {
5759
5760 if (Converter.Suppress)
5761 return ExprError();
5762
5763 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5764 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5765 CXXConversionDecl *Conv =
5766 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5767 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5768 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5769 }
5770 return From;
5771}
5772
5773static bool
5774diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5775 Sema::ContextualImplicitConverter &Converter,
5776 QualType T, bool HadMultipleCandidates,
5777 UnresolvedSetImpl &ExplicitConversions) {
5778 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5779 DeclAccessPair Found = ExplicitConversions[0];
5780 CXXConversionDecl *Conversion =
5781 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5782
5783 // The user probably meant to invoke the given explicit
5784 // conversion; use it.
5785 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5786 std::string TypeStr;
5787 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5788
5789 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5790 << FixItHint::CreateInsertion(From->getBeginLoc(),
5791 "static_cast<" + TypeStr + ">(")
5792 << FixItHint::CreateInsertion(
5793 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5794 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5795
5796 // If we aren't in a SFINAE context, build a call to the
5797 // explicit conversion function.
5798 if (SemaRef.isSFINAEContext())
5799 return true;
5800
5801 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5802 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5803 HadMultipleCandidates);
5804 if (Result.isInvalid())
5805 return true;
5806 // Record usage of conversion in an implicit cast.
5807 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5808 CK_UserDefinedConversion, Result.get(),
5809 nullptr, Result.get()->getValueKind());
5810 }
5811 return false;
5812}
5813
5814static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5815 Sema::ContextualImplicitConverter &Converter,
5816 QualType T, bool HadMultipleCandidates,
5817 DeclAccessPair &Found) {
5818 CXXConversionDecl *Conversion =
5819 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5820 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5821
5822 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5823 if (!Converter.SuppressConversion) {
5824 if (SemaRef.isSFINAEContext())
5825 return true;
5826
5827 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5828 << From->getSourceRange();
5829 }
5830
5831 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5832 HadMultipleCandidates);
5833 if (Result.isInvalid())
5834 return true;
5835 // Record usage of conversion in an implicit cast.
5836 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5837 CK_UserDefinedConversion, Result.get(),
5838 nullptr, Result.get()->getValueKind());
5839 return false;
5840}
5841
5842static ExprResult finishContextualImplicitConversion(
5843 Sema &SemaRef, SourceLocation Loc, Expr *From,
5844 Sema::ContextualImplicitConverter &Converter) {
5845 if (!Converter.match(From->getType()) && !Converter.Suppress)
5846 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5847 << From->getSourceRange();
5848
5849 return SemaRef.DefaultLvalueConversion(From);
5850}
5851
5852static void
5853collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5854 UnresolvedSetImpl &ViableConversions,
5855 OverloadCandidateSet &CandidateSet) {
5856 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5857 DeclAccessPair FoundDecl = ViableConversions[I];
5858 NamedDecl *D = FoundDecl.getDecl();
5859 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5860 if (isa<UsingShadowDecl>(D))
5861 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5862
5863 CXXConversionDecl *Conv;
5864 FunctionTemplateDecl *ConvTemplate;
5865 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5866 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5867 else
5868 Conv = cast<CXXConversionDecl>(D);
5869
5870 if (ConvTemplate)
5871 SemaRef.AddTemplateConversionCandidate(
5872 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5873 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5874 else
5875 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5876 ToType, CandidateSet,
5877 /*AllowObjCConversionOnExplicit=*/false,
5878 /*AllowExplicit*/ true);
5879 }
5880}
5881
5882/// Attempt to convert the given expression to a type which is accepted
5883/// by the given converter.
5884///
5885/// This routine will attempt to convert an expression of class type to a
5886/// type accepted by the specified converter. In C++11 and before, the class
5887/// must have a single non-explicit conversion function converting to a matching
5888/// type. In C++1y, there can be multiple such conversion functions, but only
5889/// one target type.
5890///
5891/// \param Loc The source location of the construct that requires the
5892/// conversion.
5893///
5894/// \param From The expression we're converting from.
5895///
5896/// \param Converter Used to control and diagnose the conversion process.
5897///
5898/// \returns The expression, converted to an integral or enumeration type if
5899/// successful.
5900ExprResult Sema::PerformContextualImplicitConversion(
5901 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5902 // We can't perform any more checking for type-dependent expressions.
5903 if (From->isTypeDependent())
5904 return From;
5905
5906 // Process placeholders immediately.
5907 if (From->hasPlaceholderType()) {
5908 ExprResult result = CheckPlaceholderExpr(From);
5909 if (result.isInvalid())
5910 return result;
5911 From = result.get();
5912 }
5913
5914 // If the expression already has a matching type, we're golden.
5915 QualType T = From->getType();
5916 if (Converter.match(T))
5917 return DefaultLvalueConversion(From);
5918
5919 // FIXME: Check for missing '()' if T is a function type?
5920
5921 // We can only perform contextual implicit conversions on objects of class
5922 // type.
5923 const RecordType *RecordTy = T->getAs<RecordType>();
5924 if (!RecordTy || !getLangOpts().CPlusPlus) {
5925 if (!Converter.Suppress)
5926 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5927 return From;
5928 }
5929
5930 // We must have a complete class type.
5931 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5932 ContextualImplicitConverter &Converter;
5933 Expr *From;
5934
5935 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5936 : Converter(Converter), From(From) {}
5937
5938 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5939 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5940 }
5941 } IncompleteDiagnoser(Converter, From);
5942
5943 if (Converter.Suppress ? !isCompleteType(Loc, T)
5944 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5945 return From;
5946
5947 // Look for a conversion to an integral or enumeration type.
5948 UnresolvedSet<4>
5949 ViableConversions; // These are *potentially* viable in C++1y.
5950 UnresolvedSet<4> ExplicitConversions;
5951 const auto &Conversions =
5952 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5953
5954 bool HadMultipleCandidates =
5955 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5956
5957 // To check that there is only one target type, in C++1y:
5958 QualType ToType;
5959 bool HasUniqueTargetType = true;
5960
5961 // Collect explicit or viable (potentially in C++1y) conversions.
5962 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5963 NamedDecl *D = (*I)->getUnderlyingDecl();
5964 CXXConversionDecl *Conversion;
5965 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5966 if (ConvTemplate) {
5967 if (getLangOpts().CPlusPlus14)
5968 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5969 else
5970 continue; // C++11 does not consider conversion operator templates(?).
5971 } else
5972 Conversion = cast<CXXConversionDecl>(D);
5973
5974 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5976, __PRETTY_FUNCTION__))
5975 "Conversion operator templates are considered potentially "(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5976, __PRETTY_FUNCTION__))
5976 "viable in C++1y")(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 5976, __PRETTY_FUNCTION__))
;
5977
5978 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5979 if (Converter.match(CurToType) || ConvTemplate) {
5980
5981 if (Conversion->isExplicit()) {
5982 // FIXME: For C++1y, do we need this restriction?
5983 // cf. diagnoseNoViableConversion()
5984 if (!ConvTemplate)
5985 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5986 } else {
5987 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5988 if (ToType.isNull())
5989 ToType = CurToType.getUnqualifiedType();
5990 else if (HasUniqueTargetType &&
5991 (CurToType.getUnqualifiedType() != ToType))
5992 HasUniqueTargetType = false;
5993 }
5994 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5995 }
5996 }
5997 }
5998
5999 if (getLangOpts().CPlusPlus14) {
6000 // C++1y [conv]p6:
6001 // ... An expression e of class type E appearing in such a context
6002 // is said to be contextually implicitly converted to a specified
6003 // type T and is well-formed if and only if e can be implicitly
6004 // converted to a type T that is determined as follows: E is searched
6005 // for conversion functions whose return type is cv T or reference to
6006 // cv T such that T is allowed by the context. There shall be
6007 // exactly one such T.
6008
6009 // If no unique T is found:
6010 if (ToType.isNull()) {
6011 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6012 HadMultipleCandidates,
6013 ExplicitConversions))
6014 return ExprError();
6015 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6016 }
6017
6018 // If more than one unique Ts are found:
6019 if (!HasUniqueTargetType)
6020 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6021 ViableConversions);
6022
6023 // If one unique T is found:
6024 // First, build a candidate set from the previously recorded
6025 // potentially viable conversions.
6026 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6027 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6028 CandidateSet);
6029
6030 // Then, perform overload resolution over the candidate set.
6031 OverloadCandidateSet::iterator Best;
6032 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6033 case OR_Success: {
6034 // Apply this conversion.
6035 DeclAccessPair Found =
6036 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6037 if (recordConversion(*this, Loc, From, Converter, T,
6038 HadMultipleCandidates, Found))
6039 return ExprError();
6040 break;
6041 }
6042 case OR_Ambiguous:
6043 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6044 ViableConversions);
6045 case OR_No_Viable_Function:
6046 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6047 HadMultipleCandidates,
6048 ExplicitConversions))
6049 return ExprError();
6050 LLVM_FALLTHROUGH[[gnu::fallthrough]];
6051 case OR_Deleted:
6052 // We'll complain below about a non-integral condition type.
6053 break;
6054 }
6055 } else {
6056 switch (ViableConversions.size()) {
6057 case 0: {
6058 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6059 HadMultipleCandidates,
6060 ExplicitConversions))
6061 return ExprError();
6062
6063 // We'll complain below about a non-integral condition type.
6064 break;
6065 }
6066 case 1: {
6067 // Apply this conversion.
6068 DeclAccessPair Found = ViableConversions[0];
6069 if (recordConversion(*this, Loc, From, Converter, T,
6070 HadMultipleCandidates, Found))
6071 return ExprError();
6072 break;
6073 }
6074 default:
6075 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6076 ViableConversions);
6077 }
6078 }
6079
6080 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6081}
6082
6083/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6084/// an acceptable non-member overloaded operator for a call whose
6085/// arguments have types T1 (and, if non-empty, T2). This routine
6086/// implements the check in C++ [over.match.oper]p3b2 concerning
6087/// enumeration types.
6088static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6089 FunctionDecl *Fn,
6090 ArrayRef<Expr *> Args) {
6091 QualType T1 = Args[0]->getType();
6092 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6093
6094 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6095 return true;
6096
6097 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6098 return true;
6099
6100 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
6101 if (Proto->getNumParams() < 1)
6102 return false;
6103
6104 if (T1->isEnumeralType()) {
6105 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6106 if (Context.hasSameUnqualifiedType(T1, ArgType))
6107 return true;
6108 }
6109
6110 if (Proto->getNumParams() < 2)
6111 return false;
6112
6113 if (!T2.isNull() && T2->isEnumeralType()) {
6114 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6115 if (Context.hasSameUnqualifiedType(T2, ArgType))
6116 return true;
6117 }
6118
6119 return false;
6120}
6121
6122/// AddOverloadCandidate - Adds the given function to the set of
6123/// candidate functions, using the given function call arguments. If
6124/// @p SuppressUserConversions, then don't allow user-defined
6125/// conversions via constructors or conversion operators.
6126///
6127/// \param PartialOverloading true if we are performing "partial" overloading
6128/// based on an incomplete set of function arguments. This feature is used by
6129/// code completion.
6130void Sema::AddOverloadCandidate(
6131 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6132 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6133 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6134 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6135 OverloadCandidateParamOrder PO) {
6136 const FunctionProtoType *Proto
6137 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6138 assert(Proto && "Functions without a prototype cannot be overloaded")((Proto && "Functions without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6138, __PRETTY_FUNCTION__))
;
6139 assert(!Function->getDescribedFunctionTemplate() &&((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6140, __PRETTY_FUNCTION__))
6140 "Use AddTemplateOverloadCandidate for function templates")((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6140, __PRETTY_FUNCTION__))
;
6141
6142 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6143 if (!isa<CXXConstructorDecl>(Method)) {
6144 // If we get here, it's because we're calling a member function
6145 // that is named without a member access expression (e.g.,
6146 // "this->f") that was either written explicitly or created
6147 // implicitly. This can happen with a qualified call to a member
6148 // function, e.g., X::f(). We use an empty type for the implied
6149 // object argument (C++ [over.call.func]p3), and the acting context
6150 // is irrelevant.
6151 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6152 Expr::Classification::makeSimpleLValue(), Args,
6153 CandidateSet, SuppressUserConversions,
6154 PartialOverloading, EarlyConversions, PO);
6155 return;
6156 }
6157 // We treat a constructor like a non-member function, since its object
6158 // argument doesn't participate in overload resolution.
6159 }
6160
6161 if (!CandidateSet.isNewCandidate(Function, PO))
6162 return;
6163
6164 // C++11 [class.copy]p11: [DR1402]
6165 // A defaulted move constructor that is defined as deleted is ignored by
6166 // overload resolution.
6167 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6168 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6169 Constructor->isMoveConstructor())
6170 return;
6171
6172 // Overload resolution is always an unevaluated context.
6173 EnterExpressionEvaluationContext Unevaluated(
6174 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6175
6176 // C++ [over.match.oper]p3:
6177 // if no operand has a class type, only those non-member functions in the
6178 // lookup set that have a first parameter of type T1 or "reference to
6179 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6180 // is a right operand) a second parameter of type T2 or "reference to
6181 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6182 // candidate functions.
6183 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6184 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6185 return;
6186
6187 // Add this candidate
6188 OverloadCandidate &Candidate =
6189 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6190 Candidate.FoundDecl = FoundDecl;
6191 Candidate.Function = Function;
6192 Candidate.Viable = true;
6193 Candidate.RewriteKind =
6194 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6195 Candidate.IsSurrogate = false;
6196 Candidate.IsADLCandidate = IsADLCandidate;
6197 Candidate.IgnoreObjectArgument = false;
6198 Candidate.ExplicitCallArguments = Args.size();
6199
6200 // Explicit functions are not actually candidates at all if we're not
6201 // allowing them in this context, but keep them around so we can point
6202 // to them in diagnostics.
6203 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6204 Candidate.Viable = false;
6205 Candidate.FailureKind = ovl_fail_explicit;
6206 return;
6207 }
6208
6209 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6210 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6211 Candidate.Viable = false;
6212 Candidate.FailureKind = ovl_non_default_multiversion_function;
6213 return;
6214 }
6215
6216 if (Constructor) {
6217 // C++ [class.copy]p3:
6218 // A member function template is never instantiated to perform the copy
6219 // of a class object to an object of its class type.
6220 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6221 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6222 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6223 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6224 ClassType))) {
6225 Candidate.Viable = false;
6226 Candidate.FailureKind = ovl_fail_illegal_constructor;
6227 return;
6228 }
6229
6230 // C++ [over.match.funcs]p8: (proposed DR resolution)
6231 // A constructor inherited from class type C that has a first parameter
6232 // of type "reference to P" (including such a constructor instantiated
6233 // from a template) is excluded from the set of candidate functions when
6234 // constructing an object of type cv D if the argument list has exactly
6235 // one argument and D is reference-related to P and P is reference-related
6236 // to C.
6237 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6238 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6239 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6240 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6241 QualType C = Context.getRecordType(Constructor->getParent());
6242 QualType D = Context.getRecordType(Shadow->getParent());
6243 SourceLocation Loc = Args.front()->getExprLoc();
6244 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6245 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6246 Candidate.Viable = false;
6247 Candidate.FailureKind = ovl_fail_inhctor_slice;
6248 return;
6249 }
6250 }
6251
6252 // Check that the constructor is capable of constructing an object in the
6253 // destination address space.
6254 if (!Qualifiers::isAddressSpaceSupersetOf(
6255 Constructor->getMethodQualifiers().getAddressSpace(),
6256 CandidateSet.getDestAS())) {
6257 Candidate.Viable = false;
6258 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6259 }
6260 }
6261
6262 unsigned NumParams = Proto->getNumParams();
6263
6264 // (C++ 13.3.2p2): A candidate function having fewer than m
6265 // parameters is viable only if it has an ellipsis in its parameter
6266 // list (8.3.5).
6267 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6268 !Proto->isVariadic()) {
6269 Candidate.Viable = false;
6270 Candidate.FailureKind = ovl_fail_too_many_arguments;
6271 return;
6272 }
6273
6274 // (C++ 13.3.2p2): A candidate function having more than m parameters
6275 // is viable only if the (m+1)st parameter has a default argument
6276 // (8.3.6). For the purposes of overload resolution, the
6277 // parameter list is truncated on the right, so that there are
6278 // exactly m parameters.
6279 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6280 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6281 // Not enough arguments.
6282 Candidate.Viable = false;
6283 Candidate.FailureKind = ovl_fail_too_few_arguments;
6284 return;
6285 }
6286
6287 // (CUDA B.1): Check for invalid calls between targets.
6288 if (getLangOpts().CUDA)
6289 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6290 // Skip the check for callers that are implicit members, because in this
6291 // case we may not yet know what the member's target is; the target is
6292 // inferred for the member automatically, based on the bases and fields of
6293 // the class.
6294 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6295 Candidate.Viable = false;
6296 Candidate.FailureKind = ovl_fail_bad_target;
6297 return;
6298 }
6299
6300 if (Expr *RequiresClause = Function->getTrailingRequiresClause()) {
6301 ConstraintSatisfaction Satisfaction;
6302 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) ||
6303 !Satisfaction.IsSatisfied) {
6304 Candidate.Viable = false;
6305 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6306 return;
6307 }
6308 }
6309
6310 // Determine the implicit conversion sequences for each of the
6311 // arguments.
6312 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6313 unsigned ConvIdx =
6314 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6315 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6316 // We already formed a conversion sequence for this parameter during
6317 // template argument deduction.
6318 } else if (ArgIdx < NumParams) {
6319 // (C++ 13.3.2p3): for F to be a viable function, there shall
6320 // exist for each argument an implicit conversion sequence
6321 // (13.3.3.1) that converts that argument to the corresponding
6322 // parameter of F.
6323 QualType ParamType = Proto->getParamType(ArgIdx);
6324 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6325 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6326 /*InOverloadResolution=*/true,
6327 /*AllowObjCWritebackConversion=*/
6328 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6329 if (Candidate.Conversions[ConvIdx].isBad()) {
6330 Candidate.Viable = false;
6331 Candidate.FailureKind = ovl_fail_bad_conversion;
6332 return;
6333 }
6334 } else {
6335 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6336 // argument for which there is no corresponding parameter is
6337 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6338 Candidate.Conversions[ConvIdx].setEllipsis();
6339 }
6340 }
6341
6342 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6343 Candidate.Viable = false;
6344 Candidate.FailureKind = ovl_fail_enable_if;
6345 Candidate.DeductionFailure.Data = FailedAttr;
6346 return;
6347 }
6348
6349 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6350 Candidate.Viable = false;
6351 Candidate.FailureKind = ovl_fail_ext_disabled;
6352 return;
6353 }
6354}
6355
6356ObjCMethodDecl *
6357Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6358 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6359 if (Methods.size() <= 1)
6360 return nullptr;
6361
6362 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6363 bool Match = true;
6364 ObjCMethodDecl *Method = Methods[b];
6365 unsigned NumNamedArgs = Sel.getNumArgs();
6366 // Method might have more arguments than selector indicates. This is due
6367 // to addition of c-style arguments in method.
6368 if (Method->param_size() > NumNamedArgs)
6369 NumNamedArgs = Method->param_size();
6370 if (Args.size() < NumNamedArgs)
6371 continue;
6372
6373 for (unsigned i = 0; i < NumNamedArgs; i++) {
6374 // We can't do any type-checking on a type-dependent argument.
6375 if (Args[i]->isTypeDependent()) {
6376 Match = false;
6377 break;
6378 }
6379
6380 ParmVarDecl *param = Method->parameters()[i];
6381 Expr *argExpr = Args[i];
6382 assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6382, __PRETTY_FUNCTION__))
;
6383
6384 // Strip the unbridged-cast placeholder expression off unless it's
6385 // a consumed argument.
6386 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6387 !param->hasAttr<CFConsumedAttr>())
6388 argExpr = stripARCUnbridgedCast(argExpr);
6389
6390 // If the parameter is __unknown_anytype, move on to the next method.
6391 if (param->getType() == Context.UnknownAnyTy) {
6392 Match = false;
6393 break;
6394 }
6395
6396 ImplicitConversionSequence ConversionState
6397 = TryCopyInitialization(*this, argExpr, param->getType(),
6398 /*SuppressUserConversions*/false,
6399 /*InOverloadResolution=*/true,
6400 /*AllowObjCWritebackConversion=*/
6401 getLangOpts().ObjCAutoRefCount,
6402 /*AllowExplicit*/false);
6403 // This function looks for a reasonably-exact match, so we consider
6404 // incompatible pointer conversions to be a failure here.
6405 if (ConversionState.isBad() ||
6406 (ConversionState.isStandard() &&
6407 ConversionState.Standard.Second ==
6408 ICK_Incompatible_Pointer_Conversion)) {
6409 Match = false;
6410 break;
6411 }
6412 }
6413 // Promote additional arguments to variadic methods.
6414 if (Match && Method->isVariadic()) {
6415 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6416 if (Args[i]->isTypeDependent()) {
6417 Match = false;
6418 break;
6419 }
6420 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6421 nullptr);
6422 if (Arg.isInvalid()) {
6423 Match = false;
6424 break;
6425 }
6426 }
6427 } else {
6428 // Check for extra arguments to non-variadic methods.
6429 if (Args.size() != NumNamedArgs)
6430 Match = false;
6431 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6432 // Special case when selectors have no argument. In this case, select
6433 // one with the most general result type of 'id'.
6434 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6435 QualType ReturnT = Methods[b]->getReturnType();
6436 if (ReturnT->isObjCIdType())
6437 return Methods[b];
6438 }
6439 }
6440 }
6441
6442 if (Match)
6443 return Method;
6444 }
6445 return nullptr;
6446}
6447
6448static bool
6449convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6450 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6451 bool MissingImplicitThis, Expr *&ConvertedThis,
6452 SmallVectorImpl<Expr *> &ConvertedArgs) {
6453 if (ThisArg) {
6454 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6455 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6456, __PRETTY_FUNCTION__))
6456 "Shouldn't have `this` for ctors!")((!isa<CXXConstructorDecl>(Method) && "Shouldn't have `this` for ctors!"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6456, __PRETTY_FUNCTION__))
;
6457 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")((!Method->isStatic() && "Shouldn't have `this` for static methods!"
) ? static_cast<void> (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6457, __PRETTY_FUNCTION__))
;
6458 ExprResult R = S.PerformObjectArgumentInitialization(
6459 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6460 if (R.isInvalid())
6461 return false;
6462 ConvertedThis = R.get();
6463 } else {
6464 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6465 (void)MD;
6466 assert((MissingImplicitThis || MD->isStatic() ||(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6468, __PRETTY_FUNCTION__))
6467 isa<CXXConstructorDecl>(MD)) &&(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6468, __PRETTY_FUNCTION__))
6468 "Expected `this` for non-ctor instance methods")(((MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl
>(MD)) && "Expected `this` for non-ctor instance methods"
) ? static_cast<void> (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6468, __PRETTY_FUNCTION__))
;
6469 }
6470 ConvertedThis = nullptr;
6471 }
6472
6473 // Ignore any variadic arguments. Converting them is pointless, since the
6474 // user can't refer to them in the function condition.
6475 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6476
6477 // Convert the arguments.
6478 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6479 ExprResult R;
6480 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6481 S.Context, Function->getParamDecl(I)),
6482 SourceLocation(), Args[I]);
6483
6484 if (R.isInvalid())
6485 return false;
6486
6487 ConvertedArgs.push_back(R.get());
6488 }
6489
6490 if (Trap.hasErrorOccurred())
6491 return false;
6492
6493 // Push default arguments if needed.
6494 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6495 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6496 ParmVarDecl *P = Function->getParamDecl(i);
6497 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6498 ? P->getUninstantiatedDefaultArg()
6499 : P->getDefaultArg();
6500 // This can only happen in code completion, i.e. when PartialOverloading
6501 // is true.
6502 if (!DefArg)
6503 return false;
6504 ExprResult R =
6505 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6506 S.Context, Function->getParamDecl(i)),
6507 SourceLocation(), DefArg);
6508 if (R.isInvalid())
6509 return false;
6510 ConvertedArgs.push_back(R.get());
6511 }
6512
6513 if (Trap.hasErrorOccurred())
6514 return false;
6515 }
6516 return true;
6517}
6518
6519EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6520 bool MissingImplicitThis) {
6521 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6522 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6523 return nullptr;
6524
6525 SFINAETrap Trap(*this);
6526 SmallVector<Expr *, 16> ConvertedArgs;
6527 // FIXME: We should look into making enable_if late-parsed.
6528 Expr *DiscardedThis;
6529 if (!convertArgsForAvailabilityChecks(
6530 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6531 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6532 return *EnableIfAttrs.begin();
6533
6534 for (auto *EIA : EnableIfAttrs) {
6535 APValue Result;
6536 // FIXME: This doesn't consider value-dependent cases, because doing so is
6537 // very difficult. Ideally, we should handle them more gracefully.
6538 if (EIA->getCond()->isValueDependent() ||
6539 !EIA->getCond()->EvaluateWithSubstitution(
6540 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6541 return EIA;
6542
6543 if (!Result.isInt() || !Result.getInt().getBoolValue())
6544 return EIA;
6545 }
6546 return nullptr;
6547}
6548
6549template <typename CheckFn>
6550static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6551 bool ArgDependent, SourceLocation Loc,
6552 CheckFn &&IsSuccessful) {
6553 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6554 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6555 if (ArgDependent == DIA->getArgDependent())
6556 Attrs.push_back(DIA);
6557 }
6558
6559 // Common case: No diagnose_if attributes, so we can quit early.
6560 if (Attrs.empty())
6561 return false;
6562
6563 auto WarningBegin = std::stable_partition(
6564 Attrs.begin(), Attrs.end(),
6565 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6566
6567 // Note that diagnose_if attributes are late-parsed, so they appear in the
6568 // correct order (unlike enable_if attributes).
6569 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6570 IsSuccessful);
6571 if (ErrAttr != WarningBegin) {
6572 const DiagnoseIfAttr *DIA = *ErrAttr;
6573 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6574 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6575 << DIA->getParent() << DIA->getCond()->getSourceRange();
6576 return true;
6577 }
6578
6579 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6580 if (IsSuccessful(DIA)) {
6581 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6582 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6583 << DIA->getParent() << DIA->getCond()->getSourceRange();
6584 }
6585
6586 return false;
6587}
6588
6589bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6590 const Expr *ThisArg,
6591 ArrayRef<const Expr *> Args,
6592 SourceLocation Loc) {
6593 return diagnoseDiagnoseIfAttrsWith(
6594 *this, Function, /*ArgDependent=*/true, Loc,
6595 [&](const DiagnoseIfAttr *DIA) {
6596 APValue Result;
6597 // It's sane to use the same Args for any redecl of this function, since
6598 // EvaluateWithSubstitution only cares about the position of each
6599 // argument in the arg list, not the ParmVarDecl* it maps to.
6600 if (!DIA->getCond()->EvaluateWithSubstitution(
6601 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6602 return false;
6603 return Result.isInt() && Result.getInt().getBoolValue();
6604 });
6605}
6606
6607bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6608 SourceLocation Loc) {
6609 return diagnoseDiagnoseIfAttrsWith(
6610 *this, ND, /*ArgDependent=*/false, Loc,
6611 [&](const DiagnoseIfAttr *DIA) {
6612 bool Result;
6613 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6614 Result;
6615 });
6616}
6617
6618/// Add all of the function declarations in the given function set to
6619/// the overload candidate set.
6620void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6621 ArrayRef<Expr *> Args,
6622 OverloadCandidateSet &CandidateSet,
6623 TemplateArgumentListInfo *ExplicitTemplateArgs,
6624 bool SuppressUserConversions,
6625 bool PartialOverloading,
6626 bool FirstArgumentIsBase) {
6627 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6628 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6629 ArrayRef<Expr *> FunctionArgs = Args;
6630
6631 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6632 FunctionDecl *FD =
6633 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6634
6635 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6636 QualType ObjectType;
6637 Expr::Classification ObjectClassification;
6638 if (Args.size() > 0) {
6639 if (Expr *E = Args[0]) {
6640 // Use the explicit base to restrict the lookup:
6641 ObjectType = E->getType();
6642 // Pointers in the object arguments are implicitly dereferenced, so we
6643 // always classify them as l-values.
6644 if (!ObjectType.isNull() && ObjectType->isPointerType())
6645 ObjectClassification = Expr::Classification::makeSimpleLValue();
6646 else
6647 ObjectClassification = E->Classify(Context);
6648 } // .. else there is an implicit base.
6649 FunctionArgs = Args.slice(1);
6650 }
6651 if (FunTmpl) {
6652 AddMethodTemplateCandidate(
6653 FunTmpl, F.getPair(),
6654 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6655 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6656 FunctionArgs, CandidateSet, SuppressUserConversions,
6657 PartialOverloading);
6658 } else {
6659 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6660 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6661 ObjectClassification, FunctionArgs, CandidateSet,
6662 SuppressUserConversions, PartialOverloading);
6663 }
6664 } else {
6665 // This branch handles both standalone functions and static methods.
6666
6667 // Slice the first argument (which is the base) when we access
6668 // static method as non-static.
6669 if (Args.size() > 0 &&
6670 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6671 !isa<CXXConstructorDecl>(FD)))) {
6672 assert(cast<CXXMethodDecl>(FD)->isStatic())((cast<CXXMethodDecl>(FD)->isStatic()) ? static_cast
<void> (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6672, __PRETTY_FUNCTION__))
;
6673 FunctionArgs = Args.slice(1);
6674 }
6675 if (FunTmpl) {
6676 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6677 ExplicitTemplateArgs, FunctionArgs,
6678 CandidateSet, SuppressUserConversions,
6679 PartialOverloading);
6680 } else {
6681 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6682 SuppressUserConversions, PartialOverloading);
6683 }
6684 }
6685 }
6686}
6687
6688/// AddMethodCandidate - Adds a named decl (which is some kind of
6689/// method) as a method candidate to the given overload set.
6690void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6691 Expr::Classification ObjectClassification,
6692 ArrayRef<Expr *> Args,
6693 OverloadCandidateSet &CandidateSet,
6694 bool SuppressUserConversions,
6695 OverloadCandidateParamOrder PO) {
6696 NamedDecl *Decl = FoundDecl.getDecl();
6697 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6698
6699 if (isa<UsingShadowDecl>(Decl))
6700 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6701
6702 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6703 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6704, __PRETTY_FUNCTION__))
6704 "Expected a member function template")((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6704, __PRETTY_FUNCTION__))
;
6705 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6706 /*ExplicitArgs*/ nullptr, ObjectType,
6707 ObjectClassification, Args, CandidateSet,
6708 SuppressUserConversions, false, PO);
6709 } else {
6710 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6711 ObjectType, ObjectClassification, Args, CandidateSet,
6712 SuppressUserConversions, false, None, PO);
6713 }
6714}
6715
6716/// AddMethodCandidate - Adds the given C++ member function to the set
6717/// of candidate functions, using the given function call arguments
6718/// and the object argument (@c Object). For example, in a call
6719/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6720/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6721/// allow user-defined conversions via constructors or conversion
6722/// operators.
6723void
6724Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6725 CXXRecordDecl *ActingContext, QualType ObjectType,
6726 Expr::Classification ObjectClassification,
6727 ArrayRef<Expr *> Args,
6728 OverloadCandidateSet &CandidateSet,
6729 bool SuppressUserConversions,
6730 bool PartialOverloading,
6731 ConversionSequenceList EarlyConversions,
6732 OverloadCandidateParamOrder PO) {
6733 const FunctionProtoType *Proto
6734 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6735 assert(Proto && "Methods without a prototype cannot be overloaded")((Proto && "Methods without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6735, __PRETTY_FUNCTION__))
;
6736 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6737, __PRETTY_FUNCTION__))
6737 "Use AddOverloadCandidate for constructors")((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6737, __PRETTY_FUNCTION__))
;
6738
6739 if (!CandidateSet.isNewCandidate(Method, PO))
6740 return;
6741
6742 // C++11 [class.copy]p23: [DR1402]
6743 // A defaulted move assignment operator that is defined as deleted is
6744 // ignored by overload resolution.
6745 if (Method->isDefaulted() && Method->isDeleted() &&
6746 Method->isMoveAssignmentOperator())
6747 return;
6748
6749 // Overload resolution is always an unevaluated context.
6750 EnterExpressionEvaluationContext Unevaluated(
6751 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6752
6753 // Add this candidate
6754 OverloadCandidate &Candidate =
6755 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6756 Candidate.FoundDecl = FoundDecl;
6757 Candidate.Function = Method;
6758 Candidate.RewriteKind =
6759 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6760 Candidate.IsSurrogate = false;
6761 Candidate.IgnoreObjectArgument = false;
6762 Candidate.ExplicitCallArguments = Args.size();
6763
6764 unsigned NumParams = Proto->getNumParams();
6765
6766 // (C++ 13.3.2p2): A candidate function having fewer than m
6767 // parameters is viable only if it has an ellipsis in its parameter
6768 // list (8.3.5).
6769 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6770 !Proto->isVariadic()) {
6771 Candidate.Viable = false;
6772 Candidate.FailureKind = ovl_fail_too_many_arguments;
6773 return;
6774 }
6775
6776 // (C++ 13.3.2p2): A candidate function having more than m parameters
6777 // is viable only if the (m+1)st parameter has a default argument
6778 // (8.3.6). For the purposes of overload resolution, the
6779 // parameter list is truncated on the right, so that there are
6780 // exactly m parameters.
6781 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6782 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6783 // Not enough arguments.
6784 Candidate.Viable = false;
6785 Candidate.FailureKind = ovl_fail_too_few_arguments;
6786 return;
6787 }
6788
6789 Candidate.Viable = true;
6790
6791 if (Method->isStatic() || ObjectType.isNull())
6792 // The implicit object argument is ignored.
6793 Candidate.IgnoreObjectArgument = true;
6794 else {
6795 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6796 // Determine the implicit conversion sequence for the object
6797 // parameter.
6798 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6799 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6800 Method, ActingContext);
6801 if (Candidate.Conversions[ConvIdx].isBad()) {
6802 Candidate.Viable = false;
6803 Candidate.FailureKind = ovl_fail_bad_conversion;
6804 return;
6805 }
6806 }
6807
6808 // (CUDA B.1): Check for invalid calls between targets.
6809 if (getLangOpts().CUDA)
6810 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6811 if (!IsAllowedCUDACall(Caller, Method)) {
6812 Candidate.Viable = false;
6813 Candidate.FailureKind = ovl_fail_bad_target;
6814 return;
6815 }
6816
6817 if (Expr *RequiresClause = Method->getTrailingRequiresClause()) {
6818 ConstraintSatisfaction Satisfaction;
6819 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) ||
6820 !Satisfaction.IsSatisfied) {
6821 Candidate.Viable = false;
6822 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6823 return;
6824 }
6825 }
6826
6827 // Determine the implicit conversion sequences for each of the
6828 // arguments.
6829 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6830 unsigned ConvIdx =
6831 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6832 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6833 // We already formed a conversion sequence for this parameter during
6834 // template argument deduction.
6835 } else if (ArgIdx < NumParams) {
6836 // (C++ 13.3.2p3): for F to be a viable function, there shall
6837 // exist for each argument an implicit conversion sequence
6838 // (13.3.3.1) that converts that argument to the corresponding
6839 // parameter of F.
6840 QualType ParamType = Proto->getParamType(ArgIdx);
6841 Candidate.Conversions[ConvIdx]
6842 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6843 SuppressUserConversions,
6844 /*InOverloadResolution=*/true,
6845 /*AllowObjCWritebackConversion=*/
6846 getLangOpts().ObjCAutoRefCount);
6847 if (Candidate.Conversions[ConvIdx].isBad()) {
6848 Candidate.Viable = false;
6849 Candidate.FailureKind = ovl_fail_bad_conversion;
6850 return;
6851 }
6852 } else {
6853 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6854 // argument for which there is no corresponding parameter is
6855 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6856 Candidate.Conversions[ConvIdx].setEllipsis();
6857 }
6858 }
6859
6860 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6861 Candidate.Viable = false;
6862 Candidate.FailureKind = ovl_fail_enable_if;
6863 Candidate.DeductionFailure.Data = FailedAttr;
6864 return;
6865 }
6866
6867 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6868 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6869 Candidate.Viable = false;
6870 Candidate.FailureKind = ovl_non_default_multiversion_function;
6871 }
6872}
6873
6874/// Add a C++ member function template as a candidate to the candidate
6875/// set, using template argument deduction to produce an appropriate member
6876/// function template specialization.
6877void Sema::AddMethodTemplateCandidate(
6878 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6879 CXXRecordDecl *ActingContext,
6880 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6881 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6882 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6883 bool PartialOverloading, OverloadCandidateParamOrder PO) {
6884 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6885 return;
6886
6887 // C++ [over.match.funcs]p7:
6888 // In each case where a candidate is a function template, candidate
6889 // function template specializations are generated using template argument
6890 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6891 // candidate functions in the usual way.113) A given name can refer to one
6892 // or more function templates and also to a set of overloaded non-template
6893 // functions. In such a case, the candidate functions generated from each
6894 // function template are combined with the set of non-template candidate
6895 // functions.
6896 TemplateDeductionInfo Info(CandidateSet.getLocation());
6897 FunctionDecl *Specialization = nullptr;
6898 ConversionSequenceList Conversions;
6899 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6900 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6901 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6902 return CheckNonDependentConversions(
6903 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6904 SuppressUserConversions, ActingContext, ObjectType,
6905 ObjectClassification, PO);
6906 })) {
6907 OverloadCandidate &Candidate =
6908 CandidateSet.addCandidate(Conversions.size(), Conversions);
6909 Candidate.FoundDecl = FoundDecl;
6910 Candidate.Function = MethodTmpl->getTemplatedDecl();
6911 Candidate.Viable = false;
6912 Candidate.RewriteKind =
6913 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6914 Candidate.IsSurrogate = false;
6915 Candidate.IgnoreObjectArgument =
6916 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6917 ObjectType.isNull();
6918 Candidate.ExplicitCallArguments = Args.size();
6919 if (Result == TDK_NonDependentConversionFailure)
6920 Candidate.FailureKind = ovl_fail_bad_conversion;
6921 else {
6922 Candidate.FailureKind = ovl_fail_bad_deduction;
6923 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6924 Info);
6925 }
6926 return;
6927 }
6928
6929 // Add the function template specialization produced by template argument
6930 // deduction as a candidate.
6931 assert(Specialization && "Missing member function template specialization?")((Specialization && "Missing member function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6931, __PRETTY_FUNCTION__))
;
6932 assert(isa<CXXMethodDecl>(Specialization) &&((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6933, __PRETTY_FUNCTION__))
6933 "Specialization is not a member function?")((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 6933, __PRETTY_FUNCTION__))
;
6934 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6935 ActingContext, ObjectType, ObjectClassification, Args,
6936 CandidateSet, SuppressUserConversions, PartialOverloading,
6937 Conversions, PO);
6938}
6939
6940/// Determine whether a given function template has a simple explicit specifier
6941/// or a non-value-dependent explicit-specification that evaluates to true.
6942static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6943 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6944}
6945
6946/// Add a C++ function template specialization as a candidate
6947/// in the candidate set, using template argument deduction to produce
6948/// an appropriate function template specialization.
6949void Sema::AddTemplateOverloadCandidate(
6950 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6951 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6952 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6953 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6954 OverloadCandidateParamOrder PO) {
6955 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6956 return;
6957
6958 // If the function template has a non-dependent explicit specification,
6959 // exclude it now if appropriate; we are not permitted to perform deduction
6960 // and substitution in this case.
6961 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6962 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6963 Candidate.FoundDecl = FoundDecl;
6964 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6965 Candidate.Viable = false;
6966 Candidate.FailureKind = ovl_fail_explicit;
6967 return;
6968 }
6969
6970 // C++ [over.match.funcs]p7:
6971 // In each case where a candidate is a function template, candidate
6972 // function template specializations are generated using template argument
6973 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6974 // candidate functions in the usual way.113) A given name can refer to one
6975 // or more function templates and also to a set of overloaded non-template
6976 // functions. In such a case, the candidate functions generated from each
6977 // function template are combined with the set of non-template candidate
6978 // functions.
6979 TemplateDeductionInfo Info(CandidateSet.getLocation());
6980 FunctionDecl *Specialization = nullptr;
6981 ConversionSequenceList Conversions;
6982 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6983 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6984 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6985 return CheckNonDependentConversions(
6986 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
6987 SuppressUserConversions, nullptr, QualType(), {}, PO);
6988 })) {
6989 OverloadCandidate &Candidate =
6990 CandidateSet.addCandidate(Conversions.size(), Conversions);
6991 Candidate.FoundDecl = FoundDecl;
6992 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6993 Candidate.Viable = false;
6994 Candidate.RewriteKind =
6995 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6996 Candidate.IsSurrogate = false;
6997 Candidate.IsADLCandidate = IsADLCandidate;
6998 // Ignore the object argument if there is one, since we don't have an object
6999 // type.
7000 Candidate.IgnoreObjectArgument =
7001 isa<CXXMethodDecl>(Candidate.Function) &&
7002 !isa<CXXConstructorDecl>(Candidate.Function);
7003 Candidate.ExplicitCallArguments = Args.size();
7004 if (Result == TDK_NonDependentConversionFailure)
7005 Candidate.FailureKind = ovl_fail_bad_conversion;
7006 else {
7007 Candidate.FailureKind = ovl_fail_bad_deduction;
7008 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7009 Info);
7010 }
7011 return;
7012 }
7013
7014 // Add the function template specialization produced by template argument
7015 // deduction as a candidate.
7016 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7016, __PRETTY_FUNCTION__))
;
7017 AddOverloadCandidate(
7018 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7019 PartialOverloading, AllowExplicit,
7020 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7021}
7022
7023/// Check that implicit conversion sequences can be formed for each argument
7024/// whose corresponding parameter has a non-dependent type, per DR1391's
7025/// [temp.deduct.call]p10.
7026bool Sema::CheckNonDependentConversions(
7027 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7028 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7029 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7030 CXXRecordDecl *ActingContext, QualType ObjectType,
7031 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7032 // FIXME: The cases in which we allow explicit conversions for constructor
7033 // arguments never consider calling a constructor template. It's not clear
7034 // that is correct.
7035 const bool AllowExplicit = false;
7036
7037 auto *FD = FunctionTemplate->getTemplatedDecl();
7038 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7039 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7040 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7041
7042 Conversions =
7043 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7044
7045 // Overload resolution is always an unevaluated context.
7046 EnterExpressionEvaluationContext Unevaluated(
7047 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7048
7049 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7050 // require that, but this check should never result in a hard error, and
7051 // overload resolution is permitted to sidestep instantiations.
7052 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7053 !ObjectType.isNull()) {
7054 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7055 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7056 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7057 Method, ActingContext);
7058 if (Conversions[ConvIdx].isBad())
7059 return true;
7060 }
7061
7062 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7063 ++I) {
7064 QualType ParamType = ParamTypes[I];
7065 if (!ParamType->isDependentType()) {
7066 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7067 ? 0
7068 : (ThisConversions + I);
7069 Conversions[ConvIdx]
7070 = TryCopyInitialization(*this, Args[I], ParamType,
7071 SuppressUserConversions,
7072 /*InOverloadResolution=*/true,
7073 /*AllowObjCWritebackConversion=*/
7074 getLangOpts().ObjCAutoRefCount,
7075 AllowExplicit);
7076 if (Conversions[ConvIdx].isBad())
7077 return true;
7078 }
7079 }
7080
7081 return false;
7082}
7083
7084/// Determine whether this is an allowable conversion from the result
7085/// of an explicit conversion operator to the expected type, per C++
7086/// [over.match.conv]p1 and [over.match.ref]p1.
7087///
7088/// \param ConvType The return type of the conversion function.
7089///
7090/// \param ToType The type we are converting to.
7091///
7092/// \param AllowObjCPointerConversion Allow a conversion from one
7093/// Objective-C pointer to another.
7094///
7095/// \returns true if the conversion is allowable, false otherwise.
7096static bool isAllowableExplicitConversion(Sema &S,
7097 QualType ConvType, QualType ToType,
7098 bool AllowObjCPointerConversion) {
7099 QualType ToNonRefType = ToType.getNonReferenceType();
7100
7101 // Easy case: the types are the same.
7102 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7103 return true;
7104
7105 // Allow qualification conversions.
7106 bool ObjCLifetimeConversion;
7107 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7108 ObjCLifetimeConversion))
7109 return true;
7110
7111 // If we're not allowed to consider Objective-C pointer conversions,
7112 // we're done.
7113 if (!AllowObjCPointerConversion)
7114 return false;
7115
7116 // Is this an Objective-C pointer conversion?
7117 bool IncompatibleObjC = false;
7118 QualType ConvertedType;
7119 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7120 IncompatibleObjC);
7121}
7122
7123/// AddConversionCandidate - Add a C++ conversion function as a
7124/// candidate in the candidate set (C++ [over.match.conv],
7125/// C++ [over.match.copy]). From is the expression we're converting from,
7126/// and ToType is the type that we're eventually trying to convert to
7127/// (which may or may not be the same type as the type that the
7128/// conversion function produces).
7129void Sema::AddConversionCandidate(
7130 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7131 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7132 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7133 bool AllowExplicit, bool AllowResultConversion) {
7134 assert(!Conversion->getDescribedFunctionTemplate() &&((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7135, __PRETTY_FUNCTION__))
7135 "Conversion function templates use AddTemplateConversionCandidate")((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7135, __PRETTY_FUNCTION__))
;
7136 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7137 if (!CandidateSet.isNewCandidate(Conversion))
7138 return;
7139
7140 // If the conversion function has an undeduced return type, trigger its
7141 // deduction now.
7142 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7143 if (DeduceReturnType(Conversion, From->getExprLoc()))
7144 return;
7145 ConvType = Conversion->getConversionType().getNonReferenceType();
7146 }
7147
7148 // If we don't allow any conversion of the result type, ignore conversion
7149 // functions that don't convert to exactly (possibly cv-qualified) T.
7150 if (!AllowResultConversion &&
7151 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7152 return;
7153
7154 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7155 // operator is only a candidate if its return type is the target type or
7156 // can be converted to the target type with a qualification conversion.
7157 //
7158 // FIXME: Include such functions in the candidate list and explain why we
7159 // can't select them.
7160 if (Conversion->isExplicit() &&
7161 !isAllowableExplicitConversion(*this, ConvType, ToType,
7162 AllowObjCConversionOnExplicit))
7163 return;
7164
7165 // Overload resolution is always an unevaluated context.
7166 EnterExpressionEvaluationContext Unevaluated(
7167 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7168
7169 // Add this candidate
7170 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7171 Candidate.FoundDecl = FoundDecl;
7172 Candidate.Function = Conversion;
7173 Candidate.IsSurrogate = false;
7174 Candidate.IgnoreObjectArgument = false;
7175 Candidate.FinalConversion.setAsIdentityConversion();
7176 Candidate.FinalConversion.setFromType(ConvType);
7177 Candidate.FinalConversion.setAllToTypes(ToType);
7178 Candidate.Viable = true;
7179 Candidate.ExplicitCallArguments = 1;
7180
7181 // Explicit functions are not actually candidates at all if we're not
7182 // allowing them in this context, but keep them around so we can point
7183 // to them in diagnostics.
7184 if (!AllowExplicit && Conversion->isExplicit()) {
7185 Candidate.Viable = false;
7186 Candidate.FailureKind = ovl_fail_explicit;
7187 return;
7188 }
7189
7190 // C++ [over.match.funcs]p4:
7191 // For conversion functions, the function is considered to be a member of
7192 // the class of the implicit implied object argument for the purpose of
7193 // defining the type of the implicit object parameter.
7194 //
7195 // Determine the implicit conversion sequence for the implicit
7196 // object parameter.
7197 QualType ImplicitParamType = From->getType();
7198 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7199 ImplicitParamType = FromPtrType->getPointeeType();
7200 CXXRecordDecl *ConversionContext
7201 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7202
7203 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7204 *this, CandidateSet.getLocation(), From->getType(),
7205 From->Classify(Context), Conversion, ConversionContext);
7206
7207 if (Candidate.Conversions[0].isBad()) {
7208 Candidate.Viable = false;
7209 Candidate.FailureKind = ovl_fail_bad_conversion;
7210 return;
7211 }
7212
7213 Expr *RequiresClause = Conversion->getTrailingRequiresClause();
7214 if (RequiresClause) {
7215 ConstraintSatisfaction Satisfaction;
7216 if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) ||
7217 !Satisfaction.IsSatisfied) {
7218 Candidate.Viable = false;
7219 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7220 return;
7221 }
7222 }
7223
7224 // We won't go through a user-defined type conversion function to convert a
7225 // derived to base as such conversions are given Conversion Rank. They only
7226 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7227 QualType FromCanon
7228 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7229 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7230 if (FromCanon == ToCanon ||
7231 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7232 Candidate.Viable = false;
7233 Candidate.FailureKind = ovl_fail_trivial_conversion;
7234 return;
7235 }
7236
7237 // To determine what the conversion from the result of calling the
7238 // conversion function to the type we're eventually trying to
7239 // convert to (ToType), we need to synthesize a call to the
7240 // conversion function and attempt copy initialization from it. This
7241 // makes sure that we get the right semantics with respect to
7242 // lvalues/rvalues and the type. Fortunately, we can allocate this
7243 // call on the stack and we don't need its arguments to be
7244 // well-formed.
7245 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7246 VK_LValue, From->getBeginLoc());
7247 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7248 Context.getPointerType(Conversion->getType()),
7249 CK_FunctionToPointerDecay,
7250 &ConversionRef, VK_RValue);
7251
7252 QualType ConversionType = Conversion->getConversionType();
7253 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7254 Candidate.Viable = false;
7255 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7256 return;
7257 }
7258
7259 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7260
7261 // Note that it is safe to allocate CallExpr on the stack here because
7262 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7263 // allocator).
7264 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7265
7266 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7267 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7268 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7269
7270 ImplicitConversionSequence ICS =
7271 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7272 /*SuppressUserConversions=*/true,
7273 /*InOverloadResolution=*/false,
7274 /*AllowObjCWritebackConversion=*/false);
7275
7276 switch (ICS.getKind()) {
7277 case ImplicitConversionSequence::StandardConversion:
7278 Candidate.FinalConversion = ICS.Standard;
7279
7280 // C++ [over.ics.user]p3:
7281 // If the user-defined conversion is specified by a specialization of a
7282 // conversion function template, the second standard conversion sequence
7283 // shall have exact match rank.
7284 if (Conversion->getPrimaryTemplate() &&
7285 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7286 Candidate.Viable = false;
7287 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7288 return;
7289 }
7290
7291 // C++0x [dcl.init.ref]p5:
7292 // In the second case, if the reference is an rvalue reference and
7293 // the second standard conversion sequence of the user-defined
7294 // conversion sequence includes an lvalue-to-rvalue conversion, the
7295 // program is ill-formed.
7296 if (ToType->isRValueReferenceType() &&
7297 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7298 Candidate.Viable = false;
7299 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7300 return;
7301 }
7302 break;
7303
7304 case ImplicitConversionSequence::BadConversion:
7305 Candidate.Viable = false;
7306 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7307 return;
7308
7309 default:
7310 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7311)
7311 "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7311)
;
7312 }
7313
7314 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7315 Candidate.Viable = false;
7316 Candidate.FailureKind = ovl_fail_enable_if;
7317 Candidate.DeductionFailure.Data = FailedAttr;
7318 return;
7319 }
7320
7321 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7322 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7323 Candidate.Viable = false;
7324 Candidate.FailureKind = ovl_non_default_multiversion_function;
7325 }
7326}
7327
7328/// Adds a conversion function template specialization
7329/// candidate to the overload set, using template argument deduction
7330/// to deduce the template arguments of the conversion function
7331/// template from the type that we are converting to (C++
7332/// [temp.deduct.conv]).
7333void Sema::AddTemplateConversionCandidate(
7334 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7335 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7336 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7337 bool AllowExplicit, bool AllowResultConversion) {
7338 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7339, __PRETTY_FUNCTION__))
7339 "Only conversion function templates permitted here")((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7339, __PRETTY_FUNCTION__))
;
7340
7341 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7342 return;
7343
7344 // If the function template has a non-dependent explicit specification,
7345 // exclude it now if appropriate; we are not permitted to perform deduction
7346 // and substitution in this case.
7347 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7348 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7349 Candidate.FoundDecl = FoundDecl;
7350 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7351 Candidate.Viable = false;
7352 Candidate.FailureKind = ovl_fail_explicit;
7353 return;
7354 }
7355
7356 TemplateDeductionInfo Info(CandidateSet.getLocation());
7357 CXXConversionDecl *Specialization = nullptr;
7358 if (TemplateDeductionResult Result
7359 = DeduceTemplateArguments(FunctionTemplate, ToType,
7360 Specialization, Info)) {
7361 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7362 Candidate.FoundDecl = FoundDecl;
7363 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7364 Candidate.Viable = false;
7365 Candidate.FailureKind = ovl_fail_bad_deduction;
7366 Candidate.IsSurrogate = false;
7367 Candidate.IgnoreObjectArgument = false;
7368 Candidate.ExplicitCallArguments = 1;
7369 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7370 Info);
7371 return;
7372 }
7373
7374 // Add the conversion function template specialization produced by
7375 // template argument deduction as a candidate.
7376 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7376, __PRETTY_FUNCTION__))
;
7377 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7378 CandidateSet, AllowObjCConversionOnExplicit,
7379 AllowExplicit, AllowResultConversion);
7380}
7381
7382/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7383/// converts the given @c Object to a function pointer via the
7384/// conversion function @c Conversion, and then attempts to call it
7385/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7386/// the type of function that we'll eventually be calling.
7387void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7388 DeclAccessPair FoundDecl,
7389 CXXRecordDecl *ActingContext,
7390 const FunctionProtoType *Proto,
7391 Expr *Object,
7392 ArrayRef<Expr *> Args,
7393 OverloadCandidateSet& CandidateSet) {
7394 if (!CandidateSet.isNewCandidate(Conversion))
7395 return;
7396
7397 // Overload resolution is always an unevaluated context.
7398 EnterExpressionEvaluationContext Unevaluated(
7399 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7400
7401 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7402 Candidate.FoundDecl = FoundDecl;
7403 Candidate.Function = nullptr;
7404 Candidate.Surrogate = Conversion;
7405 Candidate.Viable = true;
7406 Candidate.IsSurrogate = true;
7407 Candidate.IgnoreObjectArgument = false;
7408 Candidate.ExplicitCallArguments = Args.size();
7409
7410 // Determine the implicit conversion sequence for the implicit
7411 // object parameter.
7412 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7413 *this, CandidateSet.getLocation(), Object->getType(),
7414 Object->Classify(Context), Conversion, ActingContext);
7415 if (ObjectInit.isBad()) {
7416 Candidate.Viable = false;
7417 Candidate.FailureKind = ovl_fail_bad_conversion;
7418 Candidate.Conversions[0] = ObjectInit;
7419 return;
7420 }
7421
7422 // The first conversion is actually a user-defined conversion whose
7423 // first conversion is ObjectInit's standard conversion (which is
7424 // effectively a reference binding). Record it as such.
7425 Candidate.Conversions[0].setUserDefined();
7426 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7427 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7428 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7429 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7430 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7431 Candidate.Conversions[0].UserDefined.After
7432 = Candidate.Conversions[0].UserDefined.Before;
7433 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7434
7435 // Find the
7436 unsigned NumParams = Proto->getNumParams();
7437
7438 // (C++ 13.3.2p2): A candidate function having fewer than m
7439 // parameters is viable only if it has an ellipsis in its parameter
7440 // list (8.3.5).
7441 if (Args.size() > NumParams && !Proto->isVariadic()) {
7442 Candidate.Viable = false;
7443 Candidate.FailureKind = ovl_fail_too_many_arguments;
7444 return;
7445 }
7446
7447 // Function types don't have any default arguments, so just check if
7448 // we have enough arguments.
7449 if (Args.size() < NumParams) {
7450 // Not enough arguments.
7451 Candidate.Viable = false;
7452 Candidate.FailureKind = ovl_fail_too_few_arguments;
7453 return;
7454 }
7455
7456 // Determine the implicit conversion sequences for each of the
7457 // arguments.
7458 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7459 if (ArgIdx < NumParams) {
7460 // (C++ 13.3.2p3): for F to be a viable function, there shall
7461 // exist for each argument an implicit conversion sequence
7462 // (13.3.3.1) that converts that argument to the corresponding
7463 // parameter of F.
7464 QualType ParamType = Proto->getParamType(ArgIdx);
7465 Candidate.Conversions[ArgIdx + 1]
7466 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7467 /*SuppressUserConversions=*/false,
7468 /*InOverloadResolution=*/false,
7469 /*AllowObjCWritebackConversion=*/
7470 getLangOpts().ObjCAutoRefCount);
7471 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7472 Candidate.Viable = false;
7473 Candidate.FailureKind = ovl_fail_bad_conversion;
7474 return;
7475 }
7476 } else {
7477 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7478 // argument for which there is no corresponding parameter is
7479 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7480 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7481 }
7482 }
7483
7484 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7485 Candidate.Viable = false;
7486 Candidate.FailureKind = ovl_fail_enable_if;
7487 Candidate.DeductionFailure.Data = FailedAttr;
7488 return;
7489 }
7490}
7491
7492/// Add all of the non-member operator function declarations in the given
7493/// function set to the overload candidate set.
7494void Sema::AddNonMemberOperatorCandidates(
7495 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7496 OverloadCandidateSet &CandidateSet,
7497 TemplateArgumentListInfo *ExplicitTemplateArgs) {
7498 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7499 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7500 ArrayRef<Expr *> FunctionArgs = Args;
7501
7502 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7503 FunctionDecl *FD =
7504 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7505
7506 // Don't consider rewritten functions if we're not rewriting.
7507 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7508 continue;
7509
7510 assert(!isa<CXXMethodDecl>(FD) &&((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7511, __PRETTY_FUNCTION__))
7511 "unqualified operator lookup found a member function")((!isa<CXXMethodDecl>(FD) && "unqualified operator lookup found a member function"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXMethodDecl>(FD) && \"unqualified operator lookup found a member function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7511, __PRETTY_FUNCTION__))
;
7512
7513 if (FunTmpl) {
7514 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7515 FunctionArgs, CandidateSet);
7516 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7517 AddTemplateOverloadCandidate(
7518 FunTmpl, F.getPair(), ExplicitTemplateArgs,
7519 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7520 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7521 } else {
7522 if (ExplicitTemplateArgs)
7523 continue;
7524 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7525 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7526 AddOverloadCandidate(FD, F.getPair(),
7527 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7528 false, false, true, false, ADLCallKind::NotADL,
7529 None, OverloadCandidateParamOrder::Reversed);
7530 }
7531 }
7532}
7533
7534/// Add overload candidates for overloaded operators that are
7535/// member functions.
7536///
7537/// Add the overloaded operator candidates that are member functions
7538/// for the operator Op that was used in an operator expression such
7539/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7540/// CandidateSet will store the added overload candidates. (C++
7541/// [over.match.oper]).
7542void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7543 SourceLocation OpLoc,
7544 ArrayRef<Expr *> Args,
7545 OverloadCandidateSet &CandidateSet,
7546 OverloadCandidateParamOrder PO) {
7547 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7548
7549 // C++ [over.match.oper]p3:
7550 // For a unary operator @ with an operand of a type whose
7551 // cv-unqualified version is T1, and for a binary operator @ with
7552 // a left operand of a type whose cv-unqualified version is T1 and
7553 // a right operand of a type whose cv-unqualified version is T2,
7554 // three sets of candidate functions, designated member
7555 // candidates, non-member candidates and built-in candidates, are
7556 // constructed as follows:
7557 QualType T1 = Args[0]->getType();
7558
7559 // -- If T1 is a complete class type or a class currently being
7560 // defined, the set of member candidates is the result of the
7561 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7562 // the set of member candidates is empty.
7563 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7564 // Complete the type if it can be completed.
7565 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7566 return;
7567 // If the type is neither complete nor being defined, bail out now.
7568 if (!T1Rec->getDecl()->getDefinition())
7569 return;
7570
7571 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7572 LookupQualifiedName(Operators, T1Rec->getDecl());
7573 Operators.suppressDiagnostics();
7574
7575 for (LookupResult::iterator Oper = Operators.begin(),
7576 OperEnd = Operators.end();
7577 Oper != OperEnd;
7578 ++Oper)
7579 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7580 Args[0]->Classify(Context), Args.slice(1),
7581 CandidateSet, /*SuppressUserConversion=*/false, PO);
7582 }
7583}
7584
7585/// AddBuiltinCandidate - Add a candidate for a built-in
7586/// operator. ResultTy and ParamTys are the result and parameter types
7587/// of the built-in candidate, respectively. Args and NumArgs are the
7588/// arguments being passed to the candidate. IsAssignmentOperator
7589/// should be true when this built-in candidate is an assignment
7590/// operator. NumContextualBoolArguments is the number of arguments
7591/// (at the beginning of the argument list) that will be contextually
7592/// converted to bool.
7593void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7594 OverloadCandidateSet& CandidateSet,
7595 bool IsAssignmentOperator,
7596 unsigned NumContextualBoolArguments) {
7597 // Overload resolution is always an unevaluated context.
7598 EnterExpressionEvaluationContext Unevaluated(
7599 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7600
7601 // Add this candidate
7602 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7603 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7604 Candidate.Function = nullptr;
7605 Candidate.IsSurrogate = false;
7606 Candidate.IgnoreObjectArgument = false;
7607 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7608
7609 // Determine the implicit conversion sequences for each of the
7610 // arguments.
7611 Candidate.Viable = true;
7612 Candidate.ExplicitCallArguments = Args.size();
7613 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7614 // C++ [over.match.oper]p4:
7615 // For the built-in assignment operators, conversions of the
7616 // left operand are restricted as follows:
7617 // -- no temporaries are introduced to hold the left operand, and
7618 // -- no user-defined conversions are applied to the left
7619 // operand to achieve a type match with the left-most
7620 // parameter of a built-in candidate.
7621 //
7622 // We block these conversions by turning off user-defined
7623 // conversions, since that is the only way that initialization of
7624 // a reference to a non-class type can occur from something that
7625 // is not of the same type.
7626 if (ArgIdx < NumContextualBoolArguments) {
7627 assert(ParamTys[ArgIdx] == Context.BoolTy &&((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7628, __PRETTY_FUNCTION__))
7628 "Contextual conversion to bool requires bool type")((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7628, __PRETTY_FUNCTION__))
;
7629 Candidate.Conversions[ArgIdx]
7630 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7631 } else {
7632 Candidate.Conversions[ArgIdx]
7633 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7634 ArgIdx == 0 && IsAssignmentOperator,
7635 /*InOverloadResolution=*/false,
7636 /*AllowObjCWritebackConversion=*/
7637 getLangOpts().ObjCAutoRefCount);
7638 }
7639 if (Candidate.Conversions[ArgIdx].isBad()) {
7640 Candidate.Viable = false;
7641 Candidate.FailureKind = ovl_fail_bad_conversion;
7642 break;
7643 }
7644 }
7645}
7646
7647namespace {
7648
7649/// BuiltinCandidateTypeSet - A set of types that will be used for the
7650/// candidate operator functions for built-in operators (C++
7651/// [over.built]). The types are separated into pointer types and
7652/// enumeration types.
7653class BuiltinCandidateTypeSet {
7654 /// TypeSet - A set of types.
7655 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7656 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7657
7658 /// PointerTypes - The set of pointer types that will be used in the
7659 /// built-in candidates.
7660 TypeSet PointerTypes;
7661
7662 /// MemberPointerTypes - The set of member pointer types that will be
7663 /// used in the built-in candidates.
7664 TypeSet MemberPointerTypes;
7665
7666 /// EnumerationTypes - The set of enumeration types that will be
7667 /// used in the built-in candidates.
7668 TypeSet EnumerationTypes;
7669
7670 /// The set of vector types that will be used in the built-in
7671 /// candidates.
7672 TypeSet VectorTypes;
7673
7674 /// A flag indicating non-record types are viable candidates
7675 bool HasNonRecordTypes;
7676
7677 /// A flag indicating whether either arithmetic or enumeration types
7678 /// were present in the candidate set.
7679 bool HasArithmeticOrEnumeralTypes;
7680
7681 /// A flag indicating whether the nullptr type was present in the
7682 /// candidate set.
7683 bool HasNullPtrType;
7684
7685 /// Sema - The semantic analysis instance where we are building the
7686 /// candidate type set.
7687 Sema &SemaRef;
7688
7689 /// Context - The AST context in which we will build the type sets.
7690 ASTContext &Context;
7691
7692 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7693 const Qualifiers &VisibleQuals);
7694 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7695
7696public:
7697 /// iterator - Iterates through the types that are part of the set.
7698 typedef TypeSet::iterator iterator;
7699
7700 BuiltinCandidateTypeSet(Sema &SemaRef)
7701 : HasNonRecordTypes(false),
7702 HasArithmeticOrEnumeralTypes(false),
7703 HasNullPtrType(false),
7704 SemaRef(SemaRef),
7705 Context(SemaRef.Context) { }
7706
7707 void AddTypesConvertedFrom(QualType Ty,
7708 SourceLocation Loc,
7709 bool AllowUserConversions,
7710 bool AllowExplicitConversions,
7711 const Qualifiers &VisibleTypeConversionsQuals);
7712
7713 /// pointer_begin - First pointer type found;
7714 iterator pointer_begin() { return PointerTypes.begin(); }
7715
7716 /// pointer_end - Past the last pointer type found;
7717 iterator pointer_end() { return PointerTypes.end(); }
7718
7719 /// member_pointer_begin - First member pointer type found;
7720 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7721
7722 /// member_pointer_end - Past the last member pointer type found;
7723 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7724
7725 /// enumeration_begin - First enumeration type found;
7726 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7727
7728 /// enumeration_end - Past the last enumeration type found;
7729 iterator enumeration_end() { return EnumerationTypes.end(); }
7730
7731 iterator vector_begin() { return VectorTypes.begin(); }
7732 iterator vector_end() { return VectorTypes.end(); }
7733
7734 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7735 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7736 bool hasNullPtrType() const { return HasNullPtrType; }
7737};
7738
7739} // end anonymous namespace
7740
7741/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7742/// the set of pointer types along with any more-qualified variants of
7743/// that type. For example, if @p Ty is "int const *", this routine
7744/// will add "int const *", "int const volatile *", "int const
7745/// restrict *", and "int const volatile restrict *" to the set of
7746/// pointer types. Returns true if the add of @p Ty itself succeeded,
7747/// false otherwise.
7748///
7749/// FIXME: what to do about extended qualifiers?
7750bool
7751BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7752 const Qualifiers &VisibleQuals) {
7753
7754 // Insert this type.
7755 if (!PointerTypes.insert(Ty))
7756 return false;
7757
7758 QualType PointeeTy;
7759 const PointerType *PointerTy = Ty->getAs<PointerType>();
7760 bool buildObjCPtr = false;
7761 if (!PointerTy) {
7762 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7763 PointeeTy = PTy->getPointeeType();
7764 buildObjCPtr = true;
7765 } else {
7766 PointeeTy = PointerTy->getPointeeType();
7767 }
7768
7769 // Don't add qualified variants of arrays. For one, they're not allowed
7770 // (the qualifier would sink to the element type), and for another, the
7771 // only overload situation where it matters is subscript or pointer +- int,
7772 // and those shouldn't have qualifier variants anyway.
7773 if (PointeeTy->isArrayType())
7774 return true;
7775
7776 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7777 bool hasVolatile = VisibleQuals.hasVolatile();
7778 bool hasRestrict = VisibleQuals.hasRestrict();
7779
7780 // Iterate through all strict supersets of BaseCVR.
7781 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7782 if ((CVR | BaseCVR) != CVR) continue;
7783 // Skip over volatile if no volatile found anywhere in the types.
7784 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7785
7786 // Skip over restrict if no restrict found anywhere in the types, or if
7787 // the type cannot be restrict-qualified.
7788 if ((CVR & Qualifiers::Restrict) &&
7789 (!hasRestrict ||
7790 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7791 continue;
7792
7793 // Build qualified pointee type.
7794 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7795
7796 // Build qualified pointer type.
7797 QualType QPointerTy;
7798 if (!buildObjCPtr)
7799 QPointerTy = Context.getPointerType(QPointeeTy);
7800 else
7801 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7802
7803 // Insert qualified pointer type.
7804 PointerTypes.insert(QPointerTy);
7805 }
7806
7807 return true;
7808}
7809
7810/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7811/// to the set of pointer types along with any more-qualified variants of
7812/// that type. For example, if @p Ty is "int const *", this routine
7813/// will add "int const *", "int const volatile *", "int const
7814/// restrict *", and "int const volatile restrict *" to the set of
7815/// pointer types. Returns true if the add of @p Ty itself succeeded,
7816/// false otherwise.
7817///
7818/// FIXME: what to do about extended qualifiers?
7819bool
7820BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7821 QualType Ty) {
7822 // Insert this type.
7823 if (!MemberPointerTypes.insert(Ty))
7824 return false;
7825
7826 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7827 assert(PointerTy && "type was not a member pointer type!")((PointerTy && "type was not a member pointer type!")
? static_cast<void> (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 7827, __PRETTY_FUNCTION__))
;
7828
7829 QualType PointeeTy = PointerTy->getPointeeType();
7830 // Don't add qualified variants of arrays. For one, they're not allowed
7831 // (the qualifier would sink to the element type), and for another, the
7832 // only overload situation where it matters is subscript or pointer +- int,
7833 // and those shouldn't have qualifier variants anyway.
7834 if (PointeeTy->isArrayType())
7835 return true;
7836 const Type *ClassTy = PointerTy->getClass();
7837
7838 // Iterate through all strict supersets of the pointee type's CVR
7839 // qualifiers.
7840 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7841 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7842 if ((CVR | BaseCVR) != CVR) continue;
7843
7844 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7845 MemberPointerTypes.insert(
7846 Context.getMemberPointerType(QPointeeTy, ClassTy));
7847 }
7848
7849 return true;
7850}
7851
7852/// AddTypesConvertedFrom - Add each of the types to which the type @p
7853/// Ty can be implicit converted to the given set of @p Types. We're
7854/// primarily interested in pointer types and enumeration types. We also
7855/// take member pointer types, for the conditional operator.
7856/// AllowUserConversions is true if we should look at the conversion
7857/// functions of a class type, and AllowExplicitConversions if we
7858/// should also include the explicit conversion functions of a class
7859/// type.
7860void
7861BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7862 SourceLocation Loc,
7863 bool AllowUserConversions,
7864 bool AllowExplicitConversions,
7865 const Qualifiers &VisibleQuals) {
7866 // Only deal with canonical types.
7867 Ty = Context.getCanonicalType(Ty);
7868
7869 // Look through reference types; they aren't part of the type of an
7870 // expression for the purposes of conversions.
7871 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7872 Ty = RefTy->getPointeeType();
7873
7874 // If we're dealing with an array type, decay to the pointer.
7875 if (Ty->isArrayType())
7876 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7877
7878 // Otherwise, we don't care about qualifiers on the type.
7879 Ty = Ty.getLocalUnqualifiedType();
7880
7881 // Flag if we ever add a non-record type.
7882 const RecordType *TyRec = Ty->getAs<RecordType>();
7883 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7884
7885 // Flag if we encounter an arithmetic type.
7886 HasArithmeticOrEnumeralTypes =
7887 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7888
7889 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7890 PointerTypes.insert(Ty);
7891 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7892 // Insert our type, and its more-qualified variants, into the set
7893 // of types.
7894 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7895 return;
7896 } else if (Ty->isMemberPointerType()) {
7897 // Member pointers are far easier, since the pointee can't be converted.
7898 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7899 return;
7900 } else if (Ty->isEnumeralType()) {
7901 HasArithmeticOrEnumeralTypes = true;
7902 EnumerationTypes.insert(Ty);
7903 } else if (Ty->isVectorType()) {
7904 // We treat vector types as arithmetic types in many contexts as an
7905 // extension.
7906 HasArithmeticOrEnumeralTypes = true;
7907 VectorTypes.insert(Ty);
7908 } else if (Ty->isNullPtrType()) {
7909 HasNullPtrType = true;
7910 } else if (AllowUserConversions && TyRec) {
7911 // No conversion functions in incomplete types.
7912 if (!SemaRef.isCompleteType(Loc, Ty))
7913 return;
7914
7915 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7916 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7917 if (isa<UsingShadowDecl>(D))
7918 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7919
7920 // Skip conversion function templates; they don't tell us anything
7921 // about which builtin types we can convert to.
7922 if (isa<FunctionTemplateDecl>(D))
7923 continue;
7924
7925 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7926 if (AllowExplicitConversions || !Conv->isExplicit()) {
7927 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7928 VisibleQuals);
7929 }
7930 }
7931 }
7932}
7933/// Helper function for adjusting address spaces for the pointer or reference
7934/// operands of builtin operators depending on the argument.
7935static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7936 Expr *Arg) {
7937 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7938}
7939
7940/// Helper function for AddBuiltinOperatorCandidates() that adds
7941/// the volatile- and non-volatile-qualified assignment operators for the
7942/// given type to the candidate set.
7943static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7944 QualType T,
7945 ArrayRef<Expr *> Args,
7946 OverloadCandidateSet &CandidateSet) {
7947 QualType ParamTypes[2];
7948
7949 // T& operator=(T&, T)
7950 ParamTypes[0] = S.Context.getLValueReferenceType(
7951 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7952 ParamTypes[1] = T;
7953 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7954 /*IsAssignmentOperator=*/true);
7955
7956 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7957 // volatile T& operator=(volatile T&, T)
7958 ParamTypes[0] = S.Context.getLValueReferenceType(
7959 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7960 Args[0]));
7961 ParamTypes[1] = T;
7962 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7963 /*IsAssignmentOperator=*/true);
7964 }
7965}
7966
7967/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7968/// if any, found in visible type conversion functions found in ArgExpr's type.
7969static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7970 Qualifiers VRQuals;
7971 const RecordType *TyRec;
7972 if (const MemberPointerType *RHSMPType =
7973 ArgExpr->getType()->getAs<MemberPointerType>())
7974 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7975 else
7976 TyRec = ArgExpr->getType()->getAs<RecordType>();
7977 if (!TyRec) {
7978 // Just to be safe, assume the worst case.
7979 VRQuals.addVolatile();
7980 VRQuals.addRestrict();
7981 return VRQuals;
7982 }
7983
7984 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7985 if (!ClassDecl->hasDefinition())
7986 return VRQuals;
7987
7988 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7989 if (isa<UsingShadowDecl>(D))
7990 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7991 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7992 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7993 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7994 CanTy = ResTypeRef->getPointeeType();
7995 // Need to go down the pointer/mempointer chain and add qualifiers
7996 // as see them.
7997 bool done = false;
7998 while (!done) {
7999 if (CanTy.isRestrictQualified())
8000 VRQuals.addRestrict();
8001 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8002 CanTy = ResTypePtr->getPointeeType();
8003 else if (const MemberPointerType *ResTypeMPtr =
8004 CanTy->getAs<MemberPointerType>())
8005 CanTy = ResTypeMPtr->getPointeeType();
8006 else
8007 done = true;
8008 if (CanTy.isVolatileQualified())
8009 VRQuals.addVolatile();
8010 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8011 return VRQuals;
8012 }
8013 }
8014 }
8015 return VRQuals;
8016}
8017
8018namespace {
8019
8020/// Helper class to manage the addition of builtin operator overload
8021/// candidates. It provides shared state and utility methods used throughout
8022/// the process, as well as a helper method to add each group of builtin
8023/// operator overloads from the standard to a candidate set.
8024class BuiltinOperatorOverloadBuilder {
8025 // Common instance state available to all overload candidate addition methods.
8026 Sema &S;
8027 ArrayRef<Expr *> Args;
8028 Qualifiers VisibleTypeConversionsQuals;
8029 bool HasArithmeticOrEnumeralCandidateType;
8030 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8031 OverloadCandidateSet &CandidateSet;
8032
8033 static constexpr int ArithmeticTypesCap = 24;
8034 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8035
8036 // Define some indices used to iterate over the arithmetic types in
8037 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8038 // types are that preserved by promotion (C++ [over.built]p2).
8039 unsigned FirstIntegralType,
8040 LastIntegralType;
8041 unsigned FirstPromotedIntegralType,
8042 LastPromotedIntegralType;
8043 unsigned FirstPromotedArithmeticType,
8044 LastPromotedArithmeticType;
8045 unsigned NumArithmeticTypes;
8046
8047 void InitArithmeticTypes() {
8048 // Start of promoted types.
8049 FirstPromotedArithmeticType = 0;
8050 ArithmeticTypes.push_back(S.Context.FloatTy);
8051 ArithmeticTypes.push_back(S.Context.DoubleTy);
8052 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8053 if (S.Context.getTargetInfo().hasFloat128Type())
8054 ArithmeticTypes.push_back(S.Context.Float128Ty);
8055
8056 // Start of integral types.
8057 FirstIntegralType = ArithmeticTypes.size();
8058 FirstPromotedIntegralType = ArithmeticTypes.size();
8059 ArithmeticTypes.push_back(S.Context.IntTy);
8060 ArithmeticTypes.push_back(S.Context.LongTy);
8061 ArithmeticTypes.push_back(S.Context.LongLongTy);
8062 if (S.Context.getTargetInfo().hasInt128Type())
8063 ArithmeticTypes.push_back(S.Context.Int128Ty);
8064 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8065 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8066 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8067 if (S.Context.getTargetInfo().hasInt128Type())
8068 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8069 LastPromotedIntegralType = ArithmeticTypes.size();
8070 LastPromotedArithmeticType = ArithmeticTypes.size();
8071 // End of promoted types.
8072
8073 ArithmeticTypes.push_back(S.Context.BoolTy);
8074 ArithmeticTypes.push_back(S.Context.CharTy);
8075 ArithmeticTypes.push_back(S.Context.WCharTy);
8076 if (S.Context.getLangOpts().Char8)
8077 ArithmeticTypes.push_back(S.Context.Char8Ty);
8078 ArithmeticTypes.push_back(S.Context.Char16Ty);
8079 ArithmeticTypes.push_back(S.Context.Char32Ty);
8080 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8081 ArithmeticTypes.push_back(S.Context.ShortTy);
8082 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8083 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8084 LastIntegralType = ArithmeticTypes.size();
8085 NumArithmeticTypes = ArithmeticTypes.size();
8086 // End of integral types.
8087 // FIXME: What about complex? What about half?
8088
8089 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types."
) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 8090, __PRETTY_FUNCTION__))
8090 "Enough inline storage for all arithmetic types.")((ArithmeticTypes.size() <= ArithmeticTypesCap && "Enough inline storage for all arithmetic types."
) ? static_cast<void> (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 8090, __PRETTY_FUNCTION__))
;
8091 }
8092
8093 /// Helper method to factor out the common pattern of adding overloads
8094 /// for '++' and '--' builtin operators.
8095 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8096 bool HasVolatile,
8097 bool HasRestrict) {
8098 QualType ParamTypes[2] = {
8099 S.Context.getLValueReferenceType(CandidateTy),
8100 S.Context.IntTy
8101 };
8102
8103 // Non-volatile version.
8104 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8105
8106 // Use a heuristic to reduce number of builtin candidates in the set:
8107 // add volatile version only if there are conversions to a volatile type.
8108 if (HasVolatile) {
8109 ParamTypes[0] =
8110 S.Context.getLValueReferenceType(
8111 S.Context.getVolatileType(CandidateTy));
8112 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8113 }
8114
8115 // Add restrict version only if there are conversions to a restrict type
8116 // and our candidate type is a non-restrict-qualified pointer.
8117 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8118 !CandidateTy.isRestrictQualified()) {
8119 ParamTypes[0]
8120 = S.Context.getLValueReferenceType(
8121 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8122 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8123
8124 if (HasVolatile) {
8125 ParamTypes[0]
8126 = S.Context.getLValueReferenceType(
8127 S.Context.getCVRQualifiedType(CandidateTy,
8128 (Qualifiers::Volatile |
8129 Qualifiers::Restrict)));
8130 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8131 }
8132 }
8133
8134 }
8135
8136public:
8137 BuiltinOperatorOverloadBuilder(
8138 Sema &S, ArrayRef<Expr *> Args,
8139 Qualifiers VisibleTypeConversionsQuals,
8140 bool HasArithmeticOrEnumeralCandidateType,
8141 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8142 OverloadCandidateSet &CandidateSet)
8143 : S(S), Args(Args),
8144 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8145 HasArithmeticOrEnumeralCandidateType(
8146 HasArithmeticOrEnumeralCandidateType),
8147 CandidateTypes(CandidateTypes),
8148 CandidateSet(CandidateSet) {
8149
8150 InitArithmeticTypes();
8151 }
8152
8153 // Increment is deprecated for bool since C++17.
8154 //
8155 // C++ [over.built]p3:
8156 //
8157 // For every pair (T, VQ), where T is an arithmetic type other
8158 // than bool, and VQ is either volatile or empty, there exist
8159 // candidate operator functions of the form
8160 //
8161 // VQ T& operator++(VQ T&);
8162 // T operator++(VQ T&, int);
8163 //
8164 // C++ [over.built]p4:
8165 //
8166 // For every pair (T, VQ), where T is an arithmetic type other
8167 // than bool, and VQ is either volatile or empty, there exist
8168 // candidate operator functions of the form
8169 //
8170 // VQ T& operator--(VQ T&);
8171 // T operator--(VQ T&, int);
8172 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8173 if (!HasArithmeticOrEnumeralCandidateType)
8174 return;
8175
8176 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8177 const auto TypeOfT = ArithmeticTypes[Arith];
8178 if (TypeOfT == S.Context.BoolTy) {
8179 if (Op == OO_MinusMinus)
8180 continue;
8181 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8182 continue;
8183 }
8184 addPlusPlusMinusMinusStyleOverloads(
8185 TypeOfT,
8186 VisibleTypeConversionsQuals.hasVolatile(),
8187 VisibleTypeConversionsQuals.hasRestrict());
8188 }
8189 }
8190
8191 // C++ [over.built]p5:
8192 //
8193 // For every pair (T, VQ), where T is a cv-qualified or
8194 // cv-unqualified object type, and VQ is either volatile or
8195 // empty, there exist candidate operator functions of the form
8196 //
8197 // T*VQ& operator++(T*VQ&);
8198 // T*VQ& operator--(T*VQ&);
8199 // T* operator++(T*VQ&, int);
8200 // T* operator--(T*VQ&, int);
8201 void addPlusPlusMinusMinusPointerOverloads() {
8202 for (BuiltinCandidateTypeSet::iterator
8203 Ptr = CandidateTypes[0].pointer_begin(),
8204 PtrEnd = CandidateTypes[0].pointer_end();
8205 Ptr != PtrEnd; ++Ptr) {
8206 // Skip pointer types that aren't pointers to object types.
8207 if (!(*Ptr)->getPointeeType()->isObjectType())
8208 continue;
8209
8210 addPlusPlusMinusMinusStyleOverloads(*Ptr,
8211 (!(*Ptr).isVolatileQualified() &&
8212 VisibleTypeConversionsQuals.hasVolatile()),
8213 (!(*Ptr).isRestrictQualified() &&
8214 VisibleTypeConversionsQuals.hasRestrict()));
8215 }
8216 }
8217
8218 // C++ [over.built]p6:
8219 // For every cv-qualified or cv-unqualified object type T, there
8220 // exist candidate operator functions of the form
8221 //
8222 // T& operator*(T*);
8223 //
8224 // C++ [over.built]p7:
8225 // For every function type T that does not have cv-qualifiers or a
8226 // ref-qualifier, there exist candidate operator functions of the form
8227 // T& operator*(T*);
8228 void addUnaryStarPointerOverloads() {
8229 for (BuiltinCandidateTypeSet::iterator
8230 Ptr = CandidateTypes[0].pointer_begin(),
8231 PtrEnd = CandidateTypes[0].pointer_end();
8232 Ptr != PtrEnd; ++Ptr) {
8233 QualType ParamTy = *Ptr;
8234 QualType PointeeTy = ParamTy->getPointeeType();
8235 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8236 continue;
8237
8238 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8239 if (Proto->getMethodQuals() || Proto->getRefQualifier())
8240 continue;
8241
8242 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8243 }
8244 }
8245
8246 // C++ [over.built]p9:
8247 // For every promoted arithmetic type T, there exist candidate
8248 // operator functions of the form
8249 //
8250 // T operator+(T);
8251 // T operator-(T);
8252 void addUnaryPlusOrMinusArithmeticOverloads() {
8253 if (!HasArithmeticOrEnumeralCandidateType)
8254 return;
8255
8256 for (unsigned Arith = FirstPromotedArithmeticType;
8257 Arith < LastPromotedArithmeticType; ++Arith) {
8258 QualType ArithTy = ArithmeticTypes[Arith];
8259 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8260 }
8261
8262 // Extension: We also add these operators for vector types.
8263 for (BuiltinCandidateTypeSet::iterator
8264 Vec = CandidateTypes[0].vector_begin(),
8265 VecEnd = CandidateTypes[0].vector_end();
8266 Vec != VecEnd; ++Vec) {
8267 QualType VecTy = *Vec;
8268 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8269 }
8270 }
8271
8272 // C++ [over.built]p8:
8273 // For every type T, there exist candidate operator functions of
8274 // the form
8275 //
8276 // T* operator+(T*);
8277 void addUnaryPlusPointerOverloads() {
8278 for (BuiltinCandidateTypeSet::iterator
8279 Ptr = CandidateTypes[0].pointer_begin(),
8280 PtrEnd = CandidateTypes[0].pointer_end();
8281 Ptr != PtrEnd; ++Ptr) {
8282 QualType ParamTy = *Ptr;
8283 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8284 }
8285 }
8286
8287 // C++ [over.built]p10:
8288 // For every promoted integral type T, there exist candidate
8289 // operator functions of the form
8290 //
8291 // T operator~(T);
8292 void addUnaryTildePromotedIntegralOverloads() {
8293 if (!HasArithmeticOrEnumeralCandidateType)
8294 return;
8295
8296 for (unsigned Int = FirstPromotedIntegralType;
8297 Int < LastPromotedIntegralType; ++Int) {
8298 QualType IntTy = ArithmeticTypes[Int];
8299 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8300 }
8301
8302 // Extension: We also add this operator for vector types.
8303 for (BuiltinCandidateTypeSet::iterator
8304 Vec = CandidateTypes[0].vector_begin(),
8305 VecEnd = CandidateTypes[0].vector_end();
8306 Vec != VecEnd; ++Vec) {
8307 QualType VecTy = *Vec;
8308 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8309 }
8310 }
8311
8312 // C++ [over.match.oper]p16:
8313 // For every pointer to member type T or type std::nullptr_t, there
8314 // exist candidate operator functions of the form
8315 //
8316 // bool operator==(T,T);
8317 // bool operator!=(T,T);
8318 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8319 /// Set of (canonical) types that we've already handled.
8320 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8321
8322 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8323 for (BuiltinCandidateTypeSet::iterator
8324 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8325 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8326 MemPtr != MemPtrEnd;
8327 ++MemPtr) {
8328 // Don't add the same builtin candidate twice.
8329 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8330 continue;
8331
8332 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8333 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8334 }
8335
8336 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8337 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8338 if (AddedTypes.insert(NullPtrTy).second) {
8339 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8340 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8341 }
8342 }
8343 }
8344 }
8345
8346 // C++ [over.built]p15:
8347 //
8348 // For every T, where T is an enumeration type or a pointer type,
8349 // there exist candidate operator functions of the form
8350 //
8351 // bool operator<(T, T);
8352 // bool operator>(T, T);
8353 // bool operator<=(T, T);
8354 // bool operator>=(T, T);
8355 // bool operator==(T, T);
8356 // bool operator!=(T, T);
8357 // R operator<=>(T, T)
8358 void addGenericBinaryPointerOrEnumeralOverloads() {
8359 // C++ [over.match.oper]p3:
8360 // [...]the built-in candidates include all of the candidate operator
8361 // functions defined in 13.6 that, compared to the given operator, [...]
8362 // do not have the same parameter-type-list as any non-template non-member
8363 // candidate.
8364 //
8365 // Note that in practice, this only affects enumeration types because there
8366 // aren't any built-in candidates of record type, and a user-defined operator
8367 // must have an operand of record or enumeration type. Also, the only other
8368 // overloaded operator with enumeration arguments, operator=,
8369 // cannot be overloaded for enumeration types, so this is the only place
8370 // where we must suppress candidates like this.
8371 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8372 UserDefinedBinaryOperators;
8373
8374 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8375 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8376 CandidateTypes[ArgIdx].enumeration_end()) {
8377 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8378 CEnd = CandidateSet.end();
8379 C != CEnd; ++C) {
8380 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8381 continue;
8382
8383 if (C->Function->isFunctionTemplateSpecialization())
8384 continue;
8385
8386 // We interpret "same parameter-type-list" as applying to the
8387 // "synthesized candidate, with the order of the two parameters
8388 // reversed", not to the original function.
8389 bool Reversed = C->RewriteKind & CRK_Reversed;
8390 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8391 ->getType()
8392 .getUnqualifiedType();
8393 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8394 ->getType()
8395 .getUnqualifiedType();
8396
8397 // Skip if either parameter isn't of enumeral type.
8398 if (!FirstParamType->isEnumeralType() ||
8399 !SecondParamType->isEnumeralType())
8400 continue;
8401
8402 // Add this operator to the set of known user-defined operators.
8403 UserDefinedBinaryOperators.insert(
8404 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8405 S.Context.getCanonicalType(SecondParamType)));
8406 }
8407 }
8408 }
8409
8410 /// Set of (canonical) types that we've already handled.
8411 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8412
8413 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8414 for (BuiltinCandidateTypeSet::iterator
8415 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8416 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8417 Ptr != PtrEnd; ++Ptr) {
8418 // Don't add the same builtin candidate twice.
8419 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8420 continue;
8421
8422 QualType ParamTypes[2] = { *Ptr, *Ptr };
8423 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8424 }
8425 for (BuiltinCandidateTypeSet::iterator
8426 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8427 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8428 Enum != EnumEnd; ++Enum) {
8429 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8430
8431 // Don't add the same builtin candidate twice, or if a user defined
8432 // candidate exists.
8433 if (!AddedTypes.insert(CanonType).second ||
8434 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8435 CanonType)))
8436 continue;
8437 QualType ParamTypes[2] = { *Enum, *Enum };
8438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8439 }
8440 }
8441 }
8442
8443 // C++ [over.built]p13:
8444 //
8445 // For every cv-qualified or cv-unqualified object type T
8446 // there exist candidate operator functions of the form
8447 //
8448 // T* operator+(T*, ptrdiff_t);
8449 // T& operator[](T*, ptrdiff_t); [BELOW]
8450 // T* operator-(T*, ptrdiff_t);
8451 // T* operator+(ptrdiff_t, T*);
8452 // T& operator[](ptrdiff_t, T*); [BELOW]
8453 //
8454 // C++ [over.built]p14:
8455 //
8456 // For every T, where T is a pointer to object type, there
8457 // exist candidate operator functions of the form
8458 //
8459 // ptrdiff_t operator-(T, T);
8460 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8461 /// Set of (canonical) types that we've already handled.
8462 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8463
8464 for (int Arg = 0; Arg < 2; ++Arg) {
8465 QualType AsymmetricParamTypes[2] = {
8466 S.Context.getPointerDiffType(),
8467 S.Context.getPointerDiffType(),
8468 };
8469 for (BuiltinCandidateTypeSet::iterator
8470 Ptr = CandidateTypes[Arg].pointer_begin(),
8471 PtrEnd = CandidateTypes[Arg].pointer_end();
8472 Ptr != PtrEnd; ++Ptr) {
8473 QualType PointeeTy = (*Ptr)->getPointeeType();
8474 if (!PointeeTy->isObjectType())
8475 continue;
8476
8477 AsymmetricParamTypes[Arg] = *Ptr;
8478 if (Arg == 0 || Op == OO_Plus) {
8479 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8480 // T* operator+(ptrdiff_t, T*);
8481 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8482 }
8483 if (Op == OO_Minus) {
8484 // ptrdiff_t operator-(T, T);
8485 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8486 continue;
8487
8488 QualType ParamTypes[2] = { *Ptr, *Ptr };
8489 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8490 }
8491 }
8492 }
8493 }
8494
8495 // C++ [over.built]p12:
8496 //
8497 // For every pair of promoted arithmetic types L and R, there
8498 // exist candidate operator functions of the form
8499 //
8500 // LR operator*(L, R);
8501 // LR operator/(L, R);
8502 // LR operator+(L, R);
8503 // LR operator-(L, R);
8504 // bool operator<(L, R);
8505 // bool operator>(L, R);
8506 // bool operator<=(L, R);
8507 // bool operator>=(L, R);
8508 // bool operator==(L, R);
8509 // bool operator!=(L, R);
8510 //
8511 // where LR is the result of the usual arithmetic conversions
8512 // between types L and R.
8513 //
8514 // C++ [over.built]p24:
8515 //
8516 // For every pair of promoted arithmetic types L and R, there exist
8517 // candidate operator functions of the form
8518 //
8519 // LR operator?(bool, L, R);
8520 //
8521 // where LR is the result of the usual arithmetic conversions
8522 // between types L and R.
8523 // Our candidates ignore the first parameter.
8524 void addGenericBinaryArithmeticOverloads() {
8525 if (!HasArithmeticOrEnumeralCandidateType)
8526 return;
8527
8528 for (unsigned Left = FirstPromotedArithmeticType;
8529 Left < LastPromotedArithmeticType; ++Left) {
8530 for (unsigned Right = FirstPromotedArithmeticType;
8531 Right < LastPromotedArithmeticType; ++Right) {
8532 QualType LandR[2] = { ArithmeticTypes[Left],
8533 ArithmeticTypes[Right] };
8534 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8535 }
8536 }
8537
8538 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8539 // conditional operator for vector types.
8540 for (BuiltinCandidateTypeSet::iterator
8541 Vec1 = CandidateTypes[0].vector_begin(),
8542 Vec1End = CandidateTypes[0].vector_end();
8543 Vec1 != Vec1End; ++Vec1) {
8544 for (BuiltinCandidateTypeSet::iterator
8545 Vec2 = CandidateTypes[1].vector_begin(),
8546 Vec2End = CandidateTypes[1].vector_end();
8547 Vec2 != Vec2End; ++Vec2) {
8548 QualType LandR[2] = { *Vec1, *Vec2 };
8549 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8550 }
8551 }
8552 }
8553
8554 // C++2a [over.built]p14:
8555 //
8556 // For every integral type T there exists a candidate operator function
8557 // of the form
8558 //
8559 // std::strong_ordering operator<=>(T, T)
8560 //
8561 // C++2a [over.built]p15:
8562 //
8563 // For every pair of floating-point types L and R, there exists a candidate
8564 // operator function of the form
8565 //
8566 // std::partial_ordering operator<=>(L, R);
8567 //
8568 // FIXME: The current specification for integral types doesn't play nice with
8569 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8570 // comparisons. Under the current spec this can lead to ambiguity during
8571 // overload resolution. For example:
8572 //
8573 // enum A : int {a};
8574 // auto x = (a <=> (long)42);
8575 //
8576 // error: call is ambiguous for arguments 'A' and 'long'.
8577 // note: candidate operator<=>(int, int)
8578 // note: candidate operator<=>(long, long)
8579 //
8580 // To avoid this error, this function deviates from the specification and adds
8581 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8582 // arithmetic types (the same as the generic relational overloads).
8583 //
8584 // For now this function acts as a placeholder.
8585 void addThreeWayArithmeticOverloads() {
8586 addGenericBinaryArithmeticOverloads();
8587 }
8588
8589 // C++ [over.built]p17:
8590 //
8591 // For every pair of promoted integral types L and R, there
8592 // exist candidate operator functions of the form
8593 //
8594 // LR operator%(L, R);
8595 // LR operator&(L, R);
8596 // LR operator^(L, R);
8597 // LR operator|(L, R);
8598 // L operator<<(L, R);
8599 // L operator>>(L, R);
8600 //
8601 // where LR is the result of the usual arithmetic conversions
8602 // between types L and R.
8603 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8604 if (!HasArithmeticOrEnumeralCandidateType)
8605 return;
8606
8607 for (unsigned Left = FirstPromotedIntegralType;
8608 Left < LastPromotedIntegralType; ++Left) {
8609 for (unsigned Right = FirstPromotedIntegralType;
8610 Right < LastPromotedIntegralType; ++Right) {
8611 QualType LandR[2] = { ArithmeticTypes[Left],
8612 ArithmeticTypes[Right] };
8613 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8614 }
8615 }
8616 }
8617
8618 // C++ [over.built]p20:
8619 //
8620 // For every pair (T, VQ), where T is an enumeration or
8621 // pointer to member type and VQ is either volatile or
8622 // empty, there exist candidate operator functions of the form
8623 //
8624 // VQ T& operator=(VQ T&, T);
8625 void addAssignmentMemberPointerOrEnumeralOverloads() {
8626 /// Set of (canonical) types that we've already handled.
8627 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8628
8629 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8630 for (BuiltinCandidateTypeSet::iterator
8631 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8632 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8633 Enum != EnumEnd; ++Enum) {
8634 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8635 continue;
8636
8637 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8638 }
8639
8640 for (BuiltinCandidateTypeSet::iterator
8641 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8642 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8643 MemPtr != MemPtrEnd; ++MemPtr) {
8644 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8645 continue;
8646
8647 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8648 }
8649 }
8650 }
8651
8652 // C++ [over.built]p19:
8653 //
8654 // For every pair (T, VQ), where T is any type and VQ is either
8655 // volatile or empty, there exist candidate operator functions
8656 // of the form
8657 //
8658 // T*VQ& operator=(T*VQ&, T*);
8659 //
8660 // C++ [over.built]p21:
8661 //
8662 // For every pair (T, VQ), where T is a cv-qualified or
8663 // cv-unqualified object type and VQ is either volatile or
8664 // empty, there exist candidate operator functions of the form
8665 //
8666 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8667 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8668 void addAssignmentPointerOverloads(bool isEqualOp) {
8669 /// Set of (canonical) types that we've already handled.
8670 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8671
8672 for (BuiltinCandidateTypeSet::iterator
8673 Ptr = CandidateTypes[0].pointer_begin(),
8674 PtrEnd = CandidateTypes[0].pointer_end();
8675 Ptr != PtrEnd; ++Ptr) {
8676 // If this is operator=, keep track of the builtin candidates we added.
8677 if (isEqualOp)
8678 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8679 else if (!(*Ptr)->getPointeeType()->isObjectType())
8680 continue;
8681
8682 // non-volatile version
8683 QualType ParamTypes[2] = {
8684 S.Context.getLValueReferenceType(*Ptr),
8685 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8686 };
8687 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8688 /*IsAssignmentOperator=*/ isEqualOp);
8689
8690 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8691 VisibleTypeConversionsQuals.hasVolatile();
8692 if (NeedVolatile) {
8693 // volatile version
8694 ParamTypes[0] =
8695 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8696 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8697 /*IsAssignmentOperator=*/isEqualOp);
8698 }
8699
8700 if (!(*Ptr).isRestrictQualified() &&
8701 VisibleTypeConversionsQuals.hasRestrict()) {
8702 // restrict version
8703 ParamTypes[0]
8704 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8705 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8706 /*IsAssignmentOperator=*/isEqualOp);
8707
8708 if (NeedVolatile) {
8709 // volatile restrict version
8710 ParamTypes[0]
8711 = S.Context.getLValueReferenceType(
8712 S.Context.getCVRQualifiedType(*Ptr,
8713 (Qualifiers::Volatile |
8714 Qualifiers::Restrict)));
8715 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8716 /*IsAssignmentOperator=*/isEqualOp);
8717 }
8718 }
8719 }
8720
8721 if (isEqualOp) {
8722 for (BuiltinCandidateTypeSet::iterator
8723 Ptr = CandidateTypes[1].pointer_begin(),
8724 PtrEnd = CandidateTypes[1].pointer_end();
8725 Ptr != PtrEnd; ++Ptr) {
8726 // Make sure we don't add the same candidate twice.
8727 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8728 continue;
8729
8730 QualType ParamTypes[2] = {
8731 S.Context.getLValueReferenceType(*Ptr),
8732 *Ptr,
8733 };
8734
8735 // non-volatile version
8736 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8737 /*IsAssignmentOperator=*/true);
8738
8739 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8740 VisibleTypeConversionsQuals.hasVolatile();
8741 if (NeedVolatile) {
8742 // volatile version
8743 ParamTypes[0] =
8744 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8745 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8746 /*IsAssignmentOperator=*/true);
8747 }
8748
8749 if (!(*Ptr).isRestrictQualified() &&
8750 VisibleTypeConversionsQuals.hasRestrict()) {
8751 // restrict version
8752 ParamTypes[0]
8753 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8754 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8755 /*IsAssignmentOperator=*/true);
8756
8757 if (NeedVolatile) {
8758 // volatile restrict version
8759 ParamTypes[0]
8760 = S.Context.getLValueReferenceType(
8761 S.Context.getCVRQualifiedType(*Ptr,
8762 (Qualifiers::Volatile |
8763 Qualifiers::Restrict)));
8764 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8765 /*IsAssignmentOperator=*/true);
8766 }
8767 }
8768 }
8769 }
8770 }
8771
8772 // C++ [over.built]p18:
8773 //
8774 // For every triple (L, VQ, R), where L is an arithmetic type,
8775 // VQ is either volatile or empty, and R is a promoted
8776 // arithmetic type, there exist candidate operator functions of
8777 // the form
8778 //
8779 // VQ L& operator=(VQ L&, R);
8780 // VQ L& operator*=(VQ L&, R);
8781 // VQ L& operator/=(VQ L&, R);
8782 // VQ L& operator+=(VQ L&, R);
8783 // VQ L& operator-=(VQ L&, R);
8784 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8785 if (!HasArithmeticOrEnumeralCandidateType)
8786 return;
8787
8788 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8789 for (unsigned Right = FirstPromotedArithmeticType;
8790 Right < LastPromotedArithmeticType; ++Right) {
8791 QualType ParamTypes[2];
8792 ParamTypes[1] = ArithmeticTypes[Right];
8793 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8794 S, ArithmeticTypes[Left], Args[0]);
8795 // Add this built-in operator as a candidate (VQ is empty).
8796 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8797 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8798 /*IsAssignmentOperator=*/isEqualOp);
8799
8800 // Add this built-in operator as a candidate (VQ is 'volatile').
8801 if (VisibleTypeConversionsQuals.hasVolatile()) {
8802 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8803 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8804 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8805 /*IsAssignmentOperator=*/isEqualOp);
8806 }
8807 }
8808 }
8809
8810 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8811 for (BuiltinCandidateTypeSet::iterator
8812 Vec1 = CandidateTypes[0].vector_begin(),
8813 Vec1End = CandidateTypes[0].vector_end();
8814 Vec1 != Vec1End; ++Vec1) {
8815 for (BuiltinCandidateTypeSet::iterator
8816 Vec2 = CandidateTypes[1].vector_begin(),
8817 Vec2End = CandidateTypes[1].vector_end();
8818 Vec2 != Vec2End; ++Vec2) {
8819 QualType ParamTypes[2];
8820 ParamTypes[1] = *Vec2;
8821 // Add this built-in operator as a candidate (VQ is empty).
8822 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8823 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8824 /*IsAssignmentOperator=*/isEqualOp);
8825
8826 // Add this built-in operator as a candidate (VQ is 'volatile').
8827 if (VisibleTypeConversionsQuals.hasVolatile()) {
8828 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8829 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8830 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8831 /*IsAssignmentOperator=*/isEqualOp);
8832 }
8833 }
8834 }
8835 }
8836
8837 // C++ [over.built]p22:
8838 //
8839 // For every triple (L, VQ, R), where L is an integral type, VQ
8840 // is either volatile or empty, and R is a promoted integral
8841 // type, there exist candidate operator functions of the form
8842 //
8843 // VQ L& operator%=(VQ L&, R);
8844 // VQ L& operator<<=(VQ L&, R);
8845 // VQ L& operator>>=(VQ L&, R);
8846 // VQ L& operator&=(VQ L&, R);
8847 // VQ L& operator^=(VQ L&, R);
8848 // VQ L& operator|=(VQ L&, R);
8849 void addAssignmentIntegralOverloads() {
8850 if (!HasArithmeticOrEnumeralCandidateType)
8851 return;
8852
8853 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8854 for (unsigned Right = FirstPromotedIntegralType;
8855 Right < LastPromotedIntegralType; ++Right) {
8856 QualType ParamTypes[2];
8857 ParamTypes[1] = ArithmeticTypes[Right];
8858 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8859 S, ArithmeticTypes[Left], Args[0]);
8860 // Add this built-in operator as a candidate (VQ is empty).
8861 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8862 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8863 if (VisibleTypeConversionsQuals.hasVolatile()) {
8864 // Add this built-in operator as a candidate (VQ is 'volatile').
8865 ParamTypes[0] = LeftBaseTy;
8866 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8867 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8868 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8869 }
8870 }
8871 }
8872 }
8873
8874 // C++ [over.operator]p23:
8875 //
8876 // There also exist candidate operator functions of the form
8877 //
8878 // bool operator!(bool);
8879 // bool operator&&(bool, bool);
8880 // bool operator||(bool, bool);
8881 void addExclaimOverload() {
8882 QualType ParamTy = S.Context.BoolTy;
8883 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8884 /*IsAssignmentOperator=*/false,
8885 /*NumContextualBoolArguments=*/1);
8886 }
8887 void addAmpAmpOrPipePipeOverload() {
8888 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8889 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8890 /*IsAssignmentOperator=*/false,
8891 /*NumContextualBoolArguments=*/2);
8892 }
8893
8894 // C++ [over.built]p13:
8895 //
8896 // For every cv-qualified or cv-unqualified object type T there
8897 // exist candidate operator functions of the form
8898 //
8899 // T* operator+(T*, ptrdiff_t); [ABOVE]
8900 // T& operator[](T*, ptrdiff_t);
8901 // T* operator-(T*, ptrdiff_t); [ABOVE]
8902 // T* operator+(ptrdiff_t, T*); [ABOVE]
8903 // T& operator[](ptrdiff_t, T*);
8904 void addSubscriptOverloads() {
8905 for (BuiltinCandidateTypeSet::iterator
8906 Ptr = CandidateTypes[0].pointer_begin(),
8907 PtrEnd = CandidateTypes[0].pointer_end();
8908 Ptr != PtrEnd; ++Ptr) {
8909 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8910 QualType PointeeType = (*Ptr)->getPointeeType();
8911 if (!PointeeType->isObjectType())
8912 continue;
8913
8914 // T& operator[](T*, ptrdiff_t)
8915 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8916 }
8917
8918 for (BuiltinCandidateTypeSet::iterator
8919 Ptr = CandidateTypes[1].pointer_begin(),
8920 PtrEnd = CandidateTypes[1].pointer_end();
8921 Ptr != PtrEnd; ++Ptr) {
8922 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8923 QualType PointeeType = (*Ptr)->getPointeeType();
8924 if (!PointeeType->isObjectType())
8925 continue;
8926
8927 // T& operator[](ptrdiff_t, T*)
8928 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8929 }
8930 }
8931
8932 // C++ [over.built]p11:
8933 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8934 // C1 is the same type as C2 or is a derived class of C2, T is an object
8935 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8936 // there exist candidate operator functions of the form
8937 //
8938 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8939 //
8940 // where CV12 is the union of CV1 and CV2.
8941 void addArrowStarOverloads() {
8942 for (BuiltinCandidateTypeSet::iterator
8943 Ptr = CandidateTypes[0].pointer_begin(),
8944 PtrEnd = CandidateTypes[0].pointer_end();
8945 Ptr != PtrEnd; ++Ptr) {
8946 QualType C1Ty = (*Ptr);
8947 QualType C1;
8948 QualifierCollector Q1;
8949 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8950 if (!isa<RecordType>(C1))
8951 continue;
8952 // heuristic to reduce number of builtin candidates in the set.
8953 // Add volatile/restrict version only if there are conversions to a
8954 // volatile/restrict type.
8955 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8956 continue;
8957 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8958 continue;
8959 for (BuiltinCandidateTypeSet::iterator
8960 MemPtr = CandidateTypes[1].member_pointer_begin(),
8961 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8962 MemPtr != MemPtrEnd; ++MemPtr) {
8963 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8964 QualType C2 = QualType(mptr->getClass(), 0);
8965 C2 = C2.getUnqualifiedType();
8966 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8967 break;
8968 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8969 // build CV12 T&
8970 QualType T = mptr->getPointeeType();
8971 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8972 T.isVolatileQualified())
8973 continue;
8974 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8975 T.isRestrictQualified())
8976 continue;
8977 T = Q1.apply(S.Context, T);
8978 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8979 }
8980 }
8981 }
8982
8983 // Note that we don't consider the first argument, since it has been
8984 // contextually converted to bool long ago. The candidates below are
8985 // therefore added as binary.
8986 //
8987 // C++ [over.built]p25:
8988 // For every type T, where T is a pointer, pointer-to-member, or scoped
8989 // enumeration type, there exist candidate operator functions of the form
8990 //
8991 // T operator?(bool, T, T);
8992 //
8993 void addConditionalOperatorOverloads() {
8994 /// Set of (canonical) types that we've already handled.
8995 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8996
8997 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8998 for (BuiltinCandidateTypeSet::iterator
8999 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9000 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9001 Ptr != PtrEnd; ++Ptr) {
9002 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9003 continue;
9004
9005 QualType ParamTypes[2] = { *Ptr, *Ptr };
9006 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9007 }
9008
9009 for (BuiltinCandidateTypeSet::iterator
9010 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9011 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9012 MemPtr != MemPtrEnd; ++MemPtr) {
9013 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9014 continue;
9015
9016 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9017 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9018 }
9019
9020 if (S.getLangOpts().CPlusPlus11) {
9021 for (BuiltinCandidateTypeSet::iterator
9022 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9023 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9024 Enum != EnumEnd; ++Enum) {
9025 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9026 continue;
9027
9028 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9029 continue;
9030
9031 QualType ParamTypes[2] = { *Enum, *Enum };
9032 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9033 }
9034 }
9035 }
9036 }
9037};
9038
9039} // end anonymous namespace
9040
9041/// AddBuiltinOperatorCandidates - Add the appropriate built-in
9042/// operator overloads to the candidate set (C++ [over.built]), based
9043/// on the operator @p Op and the arguments given. For example, if the
9044/// operator is a binary '+', this routine might add "int
9045/// operator+(int, int)" to cover integer addition.
9046void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9047 SourceLocation OpLoc,
9048 ArrayRef<Expr *> Args,
9049 OverloadCandidateSet &CandidateSet) {
9050 // Find all of the types that the arguments can convert to, but only
9051 // if the operator we're looking at has built-in operator candidates
9052 // that make use of these types. Also record whether we encounter non-record
9053 // candidate types or either arithmetic or enumeral candidate types.
9054 Qualifiers VisibleTypeConversionsQuals;
9055 VisibleTypeConversionsQuals.addConst();
9056 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9057 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9058
9059 bool HasNonRecordCandidateType = false;
9060 bool HasArithmeticOrEnumeralCandidateType = false;
9061 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9062 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9063 CandidateTypes.emplace_back(*this);
9064 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9065 OpLoc,
9066 true,
9067 (Op == OO_Exclaim ||
9068 Op == OO_AmpAmp ||
9069 Op == OO_PipePipe),
9070 VisibleTypeConversionsQuals);
9071 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9072 CandidateTypes[ArgIdx].hasNonRecordTypes();
9073 HasArithmeticOrEnumeralCandidateType =
9074 HasArithmeticOrEnumeralCandidateType ||
9075 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9076 }
9077
9078 // Exit early when no non-record types have been added to the candidate set
9079 // for any of the arguments to the operator.
9080 //
9081 // We can't exit early for !, ||, or &&, since there we have always have
9082 // 'bool' overloads.
9083 if (!HasNonRecordCandidateType &&
9084 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9085 return;
9086
9087 // Setup an object to manage the common state for building overloads.
9088 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9089 VisibleTypeConversionsQuals,
9090 HasArithmeticOrEnumeralCandidateType,
9091 CandidateTypes, CandidateSet);
9092
9093 // Dispatch over the operation to add in only those overloads which apply.
9094 switch (Op) {
9095 case OO_None:
9096 case NUM_OVERLOADED_OPERATORS:
9097 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9097)
;
9098
9099 case OO_New:
9100 case OO_Delete:
9101 case OO_Array_New:
9102 case OO_Array_Delete:
9103 case OO_Call:
9104 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9105)
9105 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9105)
;
9106
9107 case OO_Comma:
9108 case OO_Arrow:
9109 case OO_Coawait:
9110 // C++ [over.match.oper]p3:
9111 // -- For the operator ',', the unary operator '&', the
9112 // operator '->', or the operator 'co_await', the
9113 // built-in candidates set is empty.
9114 break;
9115
9116 case OO_Plus: // '+' is either unary or binary
9117 if (Args.size() == 1)
9118 OpBuilder.addUnaryPlusPointerOverloads();
9119 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9120
9121 case OO_Minus: // '-' is either unary or binary
9122 if (Args.size() == 1) {
9123 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9124 } else {
9125 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9126 OpBuilder.addGenericBinaryArithmeticOverloads();
9127 }
9128 break;
9129
9130 case OO_Star: // '*' is either unary or binary
9131 if (Args.size() == 1)
9132 OpBuilder.addUnaryStarPointerOverloads();
9133 else
9134 OpBuilder.addGenericBinaryArithmeticOverloads();
9135 break;
9136
9137 case OO_Slash:
9138 OpBuilder.addGenericBinaryArithmeticOverloads();
9139 break;
9140
9141 case OO_PlusPlus:
9142 case OO_MinusMinus:
9143 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9144 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9145 break;
9146
9147 case OO_EqualEqual:
9148 case OO_ExclaimEqual:
9149 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9150 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9151
9152 case OO_Less:
9153 case OO_Greater:
9154 case OO_LessEqual:
9155 case OO_GreaterEqual:
9156 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9157 OpBuilder.addGenericBinaryArithmeticOverloads();
9158 break;
9159
9160 case OO_Spaceship:
9161 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9162 OpBuilder.addThreeWayArithmeticOverloads();
9163 break;
9164
9165 case OO_Percent:
9166 case OO_Caret:
9167 case OO_Pipe:
9168 case OO_LessLess:
9169 case OO_GreaterGreater:
9170 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9171 break;
9172
9173 case OO_Amp: // '&' is either unary or binary
9174 if (Args.size() == 1)
9175 // C++ [over.match.oper]p3:
9176 // -- For the operator ',', the unary operator '&', or the
9177 // operator '->', the built-in candidates set is empty.
9178 break;
9179
9180 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9181 break;
9182
9183 case OO_Tilde:
9184 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9185 break;
9186
9187 case OO_Equal:
9188 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9189 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9190
9191 case OO_PlusEqual:
9192 case OO_MinusEqual:
9193 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9194 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9195
9196 case OO_StarEqual:
9197 case OO_SlashEqual:
9198 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9199 break;
9200
9201 case OO_PercentEqual:
9202 case OO_LessLessEqual:
9203 case OO_GreaterGreaterEqual:
9204 case OO_AmpEqual:
9205 case OO_CaretEqual:
9206 case OO_PipeEqual:
9207 OpBuilder.addAssignmentIntegralOverloads();
9208 break;
9209
9210 case OO_Exclaim:
9211 OpBuilder.addExclaimOverload();
9212 break;
9213
9214 case OO_AmpAmp:
9215 case OO_PipePipe:
9216 OpBuilder.addAmpAmpOrPipePipeOverload();
9217 break;
9218
9219 case OO_Subscript:
9220 OpBuilder.addSubscriptOverloads();
9221 break;
9222
9223 case OO_ArrowStar:
9224 OpBuilder.addArrowStarOverloads();
9225 break;
9226
9227 case OO_Conditional:
9228 OpBuilder.addConditionalOperatorOverloads();
9229 OpBuilder.addGenericBinaryArithmeticOverloads();
9230 break;
9231 }
9232}
9233
9234/// Add function candidates found via argument-dependent lookup
9235/// to the set of overloading candidates.
9236///
9237/// This routine performs argument-dependent name lookup based on the
9238/// given function name (which may also be an operator name) and adds
9239/// all of the overload candidates found by ADL to the overload
9240/// candidate set (C++ [basic.lookup.argdep]).
9241void
9242Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9243 SourceLocation Loc,
9244 ArrayRef<Expr *> Args,
9245 TemplateArgumentListInfo *ExplicitTemplateArgs,
9246 OverloadCandidateSet& CandidateSet,
9247 bool PartialOverloading) {
9248 ADLResult Fns;
9249
9250 // FIXME: This approach for uniquing ADL results (and removing
9251 // redundant candidates from the set) relies on pointer-equality,
9252 // which means we need to key off the canonical decl. However,
9253 // always going back to the canonical decl might not get us the
9254 // right set of default arguments. What default arguments are
9255 // we supposed to consider on ADL candidates, anyway?
9256
9257 // FIXME: Pass in the explicit template arguments?
9258 ArgumentDependentLookup(Name, Loc, Args, Fns);
9259
9260 // Erase all of the candidates we already knew about.
9261 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9262 CandEnd = CandidateSet.end();
9263 Cand != CandEnd; ++Cand)
9264 if (Cand->Function) {
9265 Fns.erase(Cand->Function);
9266 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9267 Fns.erase(FunTmpl);
9268 }
9269
9270 // For each of the ADL candidates we found, add it to the overload
9271 // set.
9272 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9273 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9274
9275 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9276 if (ExplicitTemplateArgs)
9277 continue;
9278
9279 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
9280 /*SuppressUserConversions=*/false, PartialOverloading,
9281 /*AllowExplicit*/ true,
9282 /*AllowExplicitConversions*/ false,
9283 ADLCallKind::UsesADL);
9284 } else {
9285 AddTemplateOverloadCandidate(
9286 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
9287 CandidateSet,
9288 /*SuppressUserConversions=*/false, PartialOverloading,
9289 /*AllowExplicit*/true, ADLCallKind::UsesADL);
9290 }
9291 }
9292}
9293
9294namespace {
9295enum class Comparison { Equal, Better, Worse };
9296}
9297
9298/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9299/// overload resolution.
9300///
9301/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9302/// Cand1's first N enable_if attributes have precisely the same conditions as
9303/// Cand2's first N enable_if attributes (where N = the number of enable_if
9304/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9305///
9306/// Note that you can have a pair of candidates such that Cand1's enable_if
9307/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9308/// worse than Cand1's.
9309static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9310 const FunctionDecl *Cand2) {
9311 // Common case: One (or both) decls don't have enable_if attrs.
9312 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9313 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9314 if (!Cand1Attr || !Cand2Attr) {
9315 if (Cand1Attr == Cand2Attr)
9316 return Comparison::Equal;
9317 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9318 }
9319
9320 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9321 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9322
9323 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9324 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9325 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9326 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9327
9328 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9329 // has fewer enable_if attributes than Cand2, and vice versa.
9330 if (!Cand1A)
9331 return Comparison::Worse;
9332 if (!Cand2A)
9333 return Comparison::Better;
9334
9335 Cand1ID.clear();
9336 Cand2ID.clear();
9337
9338 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9339 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9340 if (Cand1ID != Cand2ID)
9341 return Comparison::Worse;
9342 }
9343
9344 return Comparison::Equal;
9345}
9346
9347static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9348 const OverloadCandidate &Cand2) {
9349 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9350 !Cand2.Function->isMultiVersion())
9351 return false;
9352
9353 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9354 // is obviously better.
9355 if (Cand1.Function->isInvalidDecl()) return false;
9356 if (Cand2.Function->isInvalidDecl()) return true;
9357
9358 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9359 // cpu_dispatch, else arbitrarily based on the identifiers.
9360 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9361 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9362 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9363 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9364
9365 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9366 return false;
9367
9368 if (Cand1CPUDisp && !Cand2CPUDisp)
9369 return true;
9370 if (Cand2CPUDisp && !Cand1CPUDisp)
9371 return false;
9372
9373 if (Cand1CPUSpec && Cand2CPUSpec) {
9374 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9375 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9376
9377 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9378 FirstDiff = std::mismatch(
9379 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9380 Cand2CPUSpec->cpus_begin(),
9381 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9382 return LHS->getName() == RHS->getName();
9383 });
9384
9385 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9387, __PRETTY_FUNCTION__))
9386 "Two different cpu-specific versions should not have the same "((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9387, __PRETTY_FUNCTION__))
9387 "identifier list, otherwise they'd be the same decl!")((FirstDiff.first != Cand1CPUSpec->cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? static_cast
<void> (0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9387, __PRETTY_FUNCTION__))
;
9388 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9389 }
9390 llvm_unreachable("No way to get here unless both had cpu_dispatch")::llvm::llvm_unreachable_internal("No way to get here unless both had cpu_dispatch"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9390)
;
9391}
9392
9393/// isBetterOverloadCandidate - Determines whether the first overload
9394/// candidate is a better candidate than the second (C++ 13.3.3p1).
9395bool clang::isBetterOverloadCandidate(
9396 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9397 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9398 // Define viable functions to be better candidates than non-viable
9399 // functions.
9400 if (!Cand2.Viable)
9401 return Cand1.Viable;
9402 else if (!Cand1.Viable)
9403 return false;
9404
9405 // C++ [over.match.best]p1:
9406 //
9407 // -- if F is a static member function, ICS1(F) is defined such
9408 // that ICS1(F) is neither better nor worse than ICS1(G) for
9409 // any function G, and, symmetrically, ICS1(G) is neither
9410 // better nor worse than ICS1(F).
9411 unsigned StartArg = 0;
9412 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9413 StartArg = 1;
9414
9415 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9416 // We don't allow incompatible pointer conversions in C++.
9417 if (!S.getLangOpts().CPlusPlus)
9418 return ICS.isStandard() &&
9419 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9420
9421 // The only ill-formed conversion we allow in C++ is the string literal to
9422 // char* conversion, which is only considered ill-formed after C++11.
9423 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9424 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9425 };
9426
9427 // Define functions that don't require ill-formed conversions for a given
9428 // argument to be better candidates than functions that do.
9429 unsigned NumArgs = Cand1.Conversions.size();
9430 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")((Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"
) ? static_cast<void> (0) : __assert_fail ("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9430, __PRETTY_FUNCTION__))
;
9431 bool HasBetterConversion = false;
9432 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9433 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9434 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9435 if (Cand1Bad != Cand2Bad) {
9436 if (Cand1Bad)
9437 return false;
9438 HasBetterConversion = true;
9439 }
9440 }
9441
9442 if (HasBetterConversion)
9443 return true;
9444
9445 // C++ [over.match.best]p1:
9446 // A viable function F1 is defined to be a better function than another
9447 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9448 // conversion sequence than ICSi(F2), and then...
9449 bool HasWorseConversion = false;
9450 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9451 switch (CompareImplicitConversionSequences(S, Loc,
9452 Cand1.Conversions[ArgIdx],
9453 Cand2.Conversions[ArgIdx])) {
9454 case ImplicitConversionSequence::Better:
9455 // Cand1 has a better conversion sequence.
9456 HasBetterConversion = true;
9457 break;
9458
9459 case ImplicitConversionSequence::Worse:
9460 if (Cand1.Function && Cand1.Function == Cand2.Function &&
9461 (Cand2.RewriteKind & CRK_Reversed) != 0) {
9462 // Work around large-scale breakage caused by considering reversed
9463 // forms of operator== in C++20:
9464 //
9465 // When comparing a function against its reversed form, if we have a
9466 // better conversion for one argument and a worse conversion for the
9467 // other, we prefer the non-reversed form.
9468 //
9469 // This prevents a conversion function from being considered ambiguous
9470 // with its own reversed form in various where it's only incidentally
9471 // heterogeneous.
9472 //
9473 // We diagnose this as an extension from CreateOverloadedBinOp.
9474 HasWorseConversion = true;
9475 break;
9476 }
9477
9478 // Cand1 can't be better than Cand2.
9479 return false;
9480
9481 case ImplicitConversionSequence::Indistinguishable:
9482 // Do nothing.
9483 break;
9484 }
9485 }
9486
9487 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9488 // ICSj(F2), or, if not that,
9489 if (HasBetterConversion)
9490 return true;
9491 if (HasWorseConversion)
9492 return false;
9493
9494 // -- the context is an initialization by user-defined conversion
9495 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9496 // from the return type of F1 to the destination type (i.e.,
9497 // the type of the entity being initialized) is a better
9498 // conversion sequence than the standard conversion sequence
9499 // from the return type of F2 to the destination type.
9500 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9501 Cand1.Function && Cand2.Function &&
9502 isa<CXXConversionDecl>(Cand1.Function) &&
9503 isa<CXXConversionDecl>(Cand2.Function)) {
9504 // First check whether we prefer one of the conversion functions over the
9505 // other. This only distinguishes the results in non-standard, extension
9506 // cases such as the conversion from a lambda closure type to a function
9507 // pointer or block.
9508 ImplicitConversionSequence::CompareKind Result =
9509 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9510 if (Result == ImplicitConversionSequence::Indistinguishable)
9511 Result = CompareStandardConversionSequences(S, Loc,
9512 Cand1.FinalConversion,
9513 Cand2.FinalConversion);
9514
9515 if (Result != ImplicitConversionSequence::Indistinguishable)
9516 return Result == ImplicitConversionSequence::Better;
9517
9518 // FIXME: Compare kind of reference binding if conversion functions
9519 // convert to a reference type used in direct reference binding, per
9520 // C++14 [over.match.best]p1 section 2 bullet 3.
9521 }
9522
9523 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9524 // as combined with the resolution to CWG issue 243.
9525 //
9526 // When the context is initialization by constructor ([over.match.ctor] or
9527 // either phase of [over.match.list]), a constructor is preferred over
9528 // a conversion function.
9529 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9530 Cand1.Function && Cand2.Function &&
9531 isa<CXXConstructorDecl>(Cand1.Function) !=
9532 isa<CXXConstructorDecl>(Cand2.Function))
9533 return isa<CXXConstructorDecl>(Cand1.Function);
9534
9535 // -- F1 is a non-template function and F2 is a function template
9536 // specialization, or, if not that,
9537 bool Cand1IsSpecialization = Cand1.Function &&
9538 Cand1.Function->getPrimaryTemplate();
9539 bool Cand2IsSpecialization = Cand2.Function &&
9540 Cand2.Function->getPrimaryTemplate();
9541 if (Cand1IsSpecialization != Cand2IsSpecialization)
9542 return Cand2IsSpecialization;
9543
9544 // -- F1 and F2 are function template specializations, and the function
9545 // template for F1 is more specialized than the template for F2
9546 // according to the partial ordering rules described in 14.5.5.2, or,
9547 // if not that,
9548 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9549 if (FunctionTemplateDecl *BetterTemplate
9550 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9551 Cand2.Function->getPrimaryTemplate(),
9552 Loc,
9553 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9554 : TPOC_Call,
9555 Cand1.ExplicitCallArguments,
9556 Cand2.ExplicitCallArguments))
9557 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9558 }
9559
9560 // -— F1 and F2 are non-template functions with the same
9561 // parameter-type-lists, and F1 is more constrained than F2 [...],
9562 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9563 !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9564 Cand2.Function->hasPrototype()) {
9565 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9566 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9567 if (PT1->getNumParams() == PT2->getNumParams() &&
9568 PT1->isVariadic() == PT2->isVariadic() &&
9569 S.FunctionParamTypesAreEqual(PT1, PT2)) {
9570 Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9571 Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9572 if (RC1 && RC2) {
9573 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9574 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9575 {RC2}, AtLeastAsConstrained1))
9576 return false;
9577 if (!AtLeastAsConstrained1)
9578 return false;
9579 if (S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9580 {RC1}, AtLeastAsConstrained2))
9581 return false;
9582 if (!AtLeastAsConstrained2)
9583 return true;
9584 } else if (RC1 || RC2)
9585 return RC1 != nullptr;
9586 }
9587 }
9588
9589 // -- F1 is a constructor for a class D, F2 is a constructor for a base
9590 // class B of D, and for all arguments the corresponding parameters of
9591 // F1 and F2 have the same type.
9592 // FIXME: Implement the "all parameters have the same type" check.
9593 bool Cand1IsInherited =
9594 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9595 bool Cand2IsInherited =
9596 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9597 if (Cand1IsInherited != Cand2IsInherited)
9598 return Cand2IsInherited;
9599 else if (Cand1IsInherited) {
9600 assert(Cand2IsInherited)((Cand2IsInherited) ? static_cast<void> (0) : __assert_fail
("Cand2IsInherited", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9600, __PRETTY_FUNCTION__))
;
9601 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9602 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9603 if (Cand1Class->isDerivedFrom(Cand2Class))
9604 return true;
9605 if (Cand2Class->isDerivedFrom(Cand1Class))
9606 return false;
9607 // Inherited from sibling base classes: still ambiguous.
9608 }
9609
9610 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9611 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9612 // with reversed order of parameters and F1 is not
9613 //
9614 // We rank reversed + different operator as worse than just reversed, but
9615 // that comparison can never happen, because we only consider reversing for
9616 // the maximally-rewritten operator (== or <=>).
9617 if (Cand1.RewriteKind != Cand2.RewriteKind)
9618 return Cand1.RewriteKind < Cand2.RewriteKind;
9619
9620 // Check C++17 tie-breakers for deduction guides.
9621 {
9622 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9623 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9624 if (Guide1 && Guide2) {
9625 // -- F1 is generated from a deduction-guide and F2 is not
9626 if (Guide1->isImplicit() != Guide2->isImplicit())
9627 return Guide2->isImplicit();
9628
9629 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9630 if (Guide1->isCopyDeductionCandidate())
9631 return true;
9632 }
9633 }
9634
9635 // Check for enable_if value-based overload resolution.
9636 if (Cand1.Function && Cand2.Function) {
9637 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9638 if (Cmp != Comparison::Equal)
9639 return Cmp == Comparison::Better;
9640 }
9641
9642 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9643 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9644 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9645 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9646 }
9647
9648 bool HasPS1 = Cand1.Function != nullptr &&
9649 functionHasPassObjectSizeParams(Cand1.Function);
9650 bool HasPS2 = Cand2.Function != nullptr &&
9651 functionHasPassObjectSizeParams(Cand2.Function);
9652 if (HasPS1 != HasPS2 && HasPS1)
9653 return true;
9654
9655 return isBetterMultiversionCandidate(Cand1, Cand2);
9656}
9657
9658/// Determine whether two declarations are "equivalent" for the purposes of
9659/// name lookup and overload resolution. This applies when the same internal/no
9660/// linkage entity is defined by two modules (probably by textually including
9661/// the same header). In such a case, we don't consider the declarations to
9662/// declare the same entity, but we also don't want lookups with both
9663/// declarations visible to be ambiguous in some cases (this happens when using
9664/// a modularized libstdc++).
9665bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9666 const NamedDecl *B) {
9667 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9668 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9669 if (!VA || !VB)
9670 return false;
9671
9672 // The declarations must be declaring the same name as an internal linkage
9673 // entity in different modules.
9674 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9675 VB->getDeclContext()->getRedeclContext()) ||
9676 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9677 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9678 VA->isExternallyVisible() || VB->isExternallyVisible())
9679 return false;
9680
9681 // Check that the declarations appear to be equivalent.
9682 //
9683 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9684 // For constants and functions, we should check the initializer or body is
9685 // the same. For non-constant variables, we shouldn't allow it at all.
9686 if (Context.hasSameType(VA->getType(), VB->getType()))
9687 return true;
9688
9689 // Enum constants within unnamed enumerations will have different types, but
9690 // may still be similar enough to be interchangeable for our purposes.
9691 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9692 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9693 // Only handle anonymous enums. If the enumerations were named and
9694 // equivalent, they would have been merged to the same type.
9695 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9696 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9697 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9698 !Context.hasSameType(EnumA->getIntegerType(),
9699 EnumB->getIntegerType()))
9700 return false;
9701 // Allow this only if the value is the same for both enumerators.
9702 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9703 }
9704 }
9705
9706 // Nothing else is sufficiently similar.
9707 return false;
9708}
9709
9710void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9711 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9712 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9713
9714 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
20
Passing null pointer value via 1st parameter 'Entity'
21
Calling 'Sema::getOwningModule'
9715 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9716 << !M << (M ? M->getFullModuleName() : "");
9717
9718 for (auto *E : Equiv) {
9719 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9720 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9721 << !M << (M ? M->getFullModuleName() : "");
9722 }
9723}
9724
9725/// Computes the best viable function (C++ 13.3.3)
9726/// within an overload candidate set.
9727///
9728/// \param Loc The location of the function name (or operator symbol) for
9729/// which overload resolution occurs.
9730///
9731/// \param Best If overload resolution was successful or found a deleted
9732/// function, \p Best points to the candidate function found.
9733///
9734/// \returns The result of overload resolution.
9735OverloadingResult
9736OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9737 iterator &Best) {
9738 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9739 std::transform(begin(), end(), std::back_inserter(Candidates),
9740 [](OverloadCandidate &Cand) { return &Cand; });
9741
9742 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9743 // are accepted by both clang and NVCC. However, during a particular
9744 // compilation mode only one call variant is viable. We need to
9745 // exclude non-viable overload candidates from consideration based
9746 // only on their host/device attributes. Specifically, if one
9747 // candidate call is WrongSide and the other is SameSide, we ignore
9748 // the WrongSide candidate.
9749 if (S.getLangOpts().CUDA) {
3
Assuming field 'CUDA' is 0
4
Taking false branch
9750 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9751 bool ContainsSameSideCandidate =
9752 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9753 // Check viable function only.
9754 return Cand->Viable && Cand->Function &&
9755 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9756 Sema::CFP_SameSide;
9757 });
9758 if (ContainsSameSideCandidate) {
9759 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9760 // Check viable function only to avoid unnecessary data copying/moving.
9761 return Cand->Viable && Cand->Function &&
9762 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9763 Sema::CFP_WrongSide;
9764 };
9765 llvm::erase_if(Candidates, IsWrongSideCandidate);
9766 }
9767 }
9768
9769 // Find the best viable function.
9770 Best = end();
9771 for (auto *Cand : Candidates) {
5
Assuming '__begin1' is equal to '__end1'
9772 Cand->Best = false;
9773 if (Cand->Viable)
9774 if (Best == end() ||
9775 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9776 Best = Cand;
9777 }
9778
9779 // If we didn't find any viable functions, abort.
9780 if (Best == end())
6
Assuming the condition is false
7
Taking false branch
9781 return OR_No_Viable_Function;
9782
9783 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9784
9785 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9786 PendingBest.push_back(&*Best);
8
Value assigned to field 'Function'
9787 Best->Best = true;
9788
9789 // Make sure that this function is better than every other viable
9790 // function. If not, we have an ambiguity.
9791 while (!PendingBest.empty()) {
9
Loop condition is false. Execution continues on line 9809
9792 auto *Curr = PendingBest.pop_back_val();
9793 for (auto *Cand : Candidates) {
9794 if (Cand->Viable && !Cand->Best &&
9795 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9796 PendingBest.push_back(Cand);
9797 Cand->Best = true;
9798
9799 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9800 Curr->Function))
9801 EquivalentCands.push_back(Cand->Function);
9802 else
9803 Best = end();
9804 }
9805 }
9806 }
9807
9808 // If we found more than one best candidate, this is ambiguous.
9809 if (Best == end())
10
Assuming the condition is false
11
Taking false branch
9810 return OR_Ambiguous;
9811
9812 // Best is the best viable function.
9813 if (Best->Function && Best->Function->isDeleted())
12
Assuming field 'Function' is null
9814 return OR_Deleted;
9815
9816 if (!EquivalentCands.empty())
13
Calling 'SmallVectorBase::empty'
16
Returning from 'SmallVectorBase::empty'
17
Taking true branch
9817 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
18
Passing null pointer value via 2nd parameter 'D'
19
Calling 'Sema::diagnoseEquivalentInternalLinkageDeclarations'
9818 EquivalentCands);
9819
9820 return OR_Success;
9821}
9822
9823namespace {
9824
9825enum OverloadCandidateKind {
9826 oc_function,
9827 oc_method,
9828 oc_reversed_binary_operator,
9829 oc_constructor,
9830 oc_implicit_default_constructor,
9831 oc_implicit_copy_constructor,
9832 oc_implicit_move_constructor,
9833 oc_implicit_copy_assignment,
9834 oc_implicit_move_assignment,
9835 oc_implicit_equality_comparison,
9836 oc_inherited_constructor
9837};
9838
9839enum OverloadCandidateSelect {
9840 ocs_non_template,
9841 ocs_template,
9842 ocs_described_template,
9843};
9844
9845static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9846ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9847 OverloadCandidateRewriteKind CRK,
9848 std::string &Description) {
9849
9850 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9851 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9852 isTemplate = true;
9853 Description = S.getTemplateArgumentBindingsText(
9854 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9855 }
9856
9857 OverloadCandidateSelect Select = [&]() {
9858 if (!Description.empty())
9859 return ocs_described_template;
9860 return isTemplate ? ocs_template : ocs_non_template;
9861 }();
9862
9863 OverloadCandidateKind Kind = [&]() {
9864 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9865 return oc_implicit_equality_comparison;
9866
9867 if (CRK & CRK_Reversed)
9868 return oc_reversed_binary_operator;
9869
9870 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9871 if (!Ctor->isImplicit()) {
9872 if (isa<ConstructorUsingShadowDecl>(Found))
9873 return oc_inherited_constructor;
9874 else
9875 return oc_constructor;
9876 }
9877
9878 if (Ctor->isDefaultConstructor())
9879 return oc_implicit_default_constructor;
9880
9881 if (Ctor->isMoveConstructor())
9882 return oc_implicit_move_constructor;
9883
9884 assert(Ctor->isCopyConstructor() &&((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9885, __PRETTY_FUNCTION__))
9885 "unexpected sort of implicit constructor")((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9885, __PRETTY_FUNCTION__))
;
9886 return oc_implicit_copy_constructor;
9887 }
9888
9889 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9890 // This actually gets spelled 'candidate function' for now, but
9891 // it doesn't hurt to split it out.
9892 if (!Meth->isImplicit())
9893 return oc_method;
9894
9895 if (Meth->isMoveAssignmentOperator())
9896 return oc_implicit_move_assignment;
9897
9898 if (Meth->isCopyAssignmentOperator())
9899 return oc_implicit_copy_assignment;
9900
9901 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")((isa<CXXConversionDecl>(Meth) && "expected conversion"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 9901, __PRETTY_FUNCTION__))
;
9902 return oc_method;
9903 }
9904
9905 return oc_function;
9906 }();
9907
9908 return std::make_pair(Kind, Select);
9909}
9910
9911void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9912 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9913 // set.
9914 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9915 S.Diag(FoundDecl->getLocation(),
9916 diag::note_ovl_candidate_inherited_constructor)
9917 << Shadow->getNominatedBaseClass();
9918}
9919
9920} // end anonymous namespace
9921
9922static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9923 const FunctionDecl *FD) {
9924 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9925 bool AlwaysTrue;
9926 if (EnableIf->getCond()->isValueDependent() ||
9927 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9928 return false;
9929 if (!AlwaysTrue)
9930 return false;
9931 }
9932 return true;
9933}
9934
9935/// Returns true if we can take the address of the function.
9936///
9937/// \param Complain - If true, we'll emit a diagnostic
9938/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9939/// we in overload resolution?
9940/// \param Loc - The location of the statement we're complaining about. Ignored
9941/// if we're not complaining, or if we're in overload resolution.
9942static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9943 bool Complain,
9944 bool InOverloadResolution,
9945 SourceLocation Loc) {
9946 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9947 if (Complain) {
9948 if (InOverloadResolution)
9949 S.Diag(FD->getBeginLoc(),
9950 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9951 else
9952 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9953 }
9954 return false;
9955 }
9956
9957 if (const Expr *RC = FD->getTrailingRequiresClause()) {
9958 ConstraintSatisfaction Satisfaction;
9959 if (S.CheckConstraintSatisfaction(RC, Satisfaction))
9960 return false;
9961 if (!Satisfaction.IsSatisfied) {
9962 if (Complain) {
9963 if (InOverloadResolution)
9964 S.Diag(FD->getBeginLoc(),
9965 diag::note_ovl_candidate_unsatisfied_constraints);
9966 else
9967 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
9968 << FD;
9969 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
9970 }
9971 return false;
9972 }
9973 }
9974
9975 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9976 return P->hasAttr<PassObjectSizeAttr>();
9977 });
9978 if (I == FD->param_end())
9979 return true;
9980
9981 if (Complain) {
9982 // Add one to ParamNo because it's user-facing
9983 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9984 if (InOverloadResolution)
9985 S.Diag(FD->getLocation(),
9986 diag::note_ovl_candidate_has_pass_object_size_params)
9987 << ParamNo;
9988 else
9989 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9990 << FD << ParamNo;
9991 }
9992 return false;
9993}
9994
9995static bool checkAddressOfCandidateIsAvailable(Sema &S,
9996 const FunctionDecl *FD) {
9997 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9998 /*InOverloadResolution=*/true,
9999 /*Loc=*/SourceLocation());
10000}
10001
10002bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10003 bool Complain,
10004 SourceLocation Loc) {
10005 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10006 /*InOverloadResolution=*/false,
10007 Loc);
10008}
10009
10010// Notes the location of an overload candidate.
10011void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10012 OverloadCandidateRewriteKind RewriteKind,
10013 QualType DestType, bool TakingAddress) {
10014 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10015 return;
10016 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10017 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10018 return;
10019
10020 std::string FnDesc;
10021 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10022 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10023 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10024 << (unsigned)KSPair.first << (unsigned)KSPair.second
10025 << Fn << FnDesc;
10026
10027 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10028 Diag(Fn->getLocation(), PD);
10029 MaybeEmitInheritedConstructorNote(*this, Found);
10030}
10031
10032static void
10033MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10034 // Perhaps the ambiguity was caused by two atomic constraints that are
10035 // 'identical' but not equivalent:
10036 //
10037 // void foo() requires (sizeof(T) > 4) { } // #1
10038 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10039 //
10040 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10041 // #2 to subsume #1, but these constraint are not considered equivalent
10042 // according to the subsumption rules because they are not the same
10043 // source-level construct. This behavior is quite confusing and we should try
10044 // to help the user figure out what happened.
10045
10046 SmallVector<const Expr *, 3> FirstAC, SecondAC;
10047 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10048 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10049 if (!I->Function)
10050 continue;
10051 SmallVector<const Expr *, 3> AC;
10052 if (auto *Template = I->Function->getPrimaryTemplate())
10053 Template->getAssociatedConstraints(AC);
10054 else
10055 I->Function->getAssociatedConstraints(AC);
10056 if (AC.empty())
10057 continue;
10058 if (FirstCand == nullptr) {
10059 FirstCand = I->Function;
10060 FirstAC = AC;
10061 } else if (SecondCand == nullptr) {
10062 SecondCand = I->Function;
10063 SecondAC = AC;
10064 } else {
10065 // We have more than one pair of constrained functions - this check is
10066 // expensive and we'd rather not try to diagnose it.
10067 return;
10068 }
10069 }
10070 if (!SecondCand)
10071 return;
10072 // The diagnostic can only happen if there are associated constraints on
10073 // both sides (there needs to be some identical atomic constraint).
10074 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10075 SecondCand, SecondAC))
10076 // Just show the user one diagnostic, they'll probably figure it out
10077 // from here.
10078 return;
10079}
10080
10081// Notes the location of all overload candidates designated through
10082// OverloadedExpr
10083void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10084 bool TakingAddress) {
10085 assert(OverloadedExpr->getType() == Context.OverloadTy)((OverloadedExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10085, __PRETTY_FUNCTION__))
;
10086
10087 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10088 OverloadExpr *OvlExpr = Ovl.Expression;
10089
10090 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10091 IEnd = OvlExpr->decls_end();
10092 I != IEnd; ++I) {
10093 if (FunctionTemplateDecl *FunTmpl =
10094 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10095 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10096 TakingAddress);
10097 } else if (FunctionDecl *Fun
10098 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10099 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10100 }
10101 }
10102}
10103
10104/// Diagnoses an ambiguous conversion. The partial diagnostic is the
10105/// "lead" diagnostic; it will be given two arguments, the source and
10106/// target types of the conversion.
10107void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10108 Sema &S,
10109 SourceLocation CaretLoc,
10110 const PartialDiagnostic &PDiag) const {
10111 S.Diag(CaretLoc, PDiag)
10112 << Ambiguous.getFromType() << Ambiguous.getToType();
10113 // FIXME: The note limiting machinery is borrowed from
10114 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10115 // refactoring here.
10116 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10117 unsigned CandsShown = 0;
10118 AmbiguousConversionSequence::const_iterator I, E;
10119 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10120 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10121 break;
10122 ++CandsShown;
10123 S.NoteOverloadCandidate(I->first, I->second);
10124 }
10125 if (I != E)
10126 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10127}
10128
10129static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10130 unsigned I, bool TakingCandidateAddress) {
10131 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10132 assert(Conv.isBad())((Conv.isBad()) ? static_cast<void> (0) : __assert_fail
("Conv.isBad()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10132, __PRETTY_FUNCTION__))
;
10133 assert(Cand->Function && "for now, candidate must be a function")((Cand->Function && "for now, candidate must be a function"
) ? static_cast<void> (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10133, __PRETTY_FUNCTION__))
;
10134 FunctionDecl *Fn = Cand->Function;
10135
10136 // There's a conversion slot for the object argument if this is a
10137 // non-constructor method. Note that 'I' corresponds the
10138 // conversion-slot index.
10139 bool isObjectArgument = false;
10140 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10141 if (I == 0)
10142 isObjectArgument = true;
10143 else
10144 I--;
10145 }
10146
10147 std::string FnDesc;
10148 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10149 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10150 FnDesc);
10151
10152 Expr *FromExpr = Conv.Bad.FromExpr;
10153 QualType FromTy = Conv.Bad.getFromType();
10154 QualType ToTy = Conv.Bad.getToType();
10155
10156 if (FromTy == S.Context.OverloadTy) {
10157 assert(FromExpr && "overload set argument came from implicit argument?")((FromExpr && "overload set argument came from implicit argument?"
) ? static_cast<void> (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10157, __PRETTY_FUNCTION__))
;
10158 Expr *E = FromExpr->IgnoreParens();
10159 if (isa<UnaryOperator>(E))
10160 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10161 DeclarationName Name = cast<OverloadExpr>(E)->getName();
10162
10163 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10164 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10166 << Name << I + 1;
10167 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10168 return;
10169 }
10170
10171 // Do some hand-waving analysis to see if the non-viability is due
10172 // to a qualifier mismatch.
10173 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10174 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10175 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10176 CToTy = RT->getPointeeType();
10177 else {
10178 // TODO: detect and diagnose the full richness of const mismatches.
10179 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10180 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10181 CFromTy = FromPT->getPointeeType();
10182 CToTy = ToPT->getPointeeType();
10183 }
10184 }
10185
10186 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10187 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10188 Qualifiers FromQs = CFromTy.getQualifiers();
10189 Qualifiers ToQs = CToTy.getQualifiers();
10190
10191 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10192 if (isObjectArgument)
10193 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10194 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10195 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10196 << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10197 else
10198 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10199 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10200 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10201 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10202 << ToTy->isReferenceType() << I + 1;
10203 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10204 return;
10205 }
10206
10207 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10208 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10209 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10210 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10211 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10212 << (unsigned)isObjectArgument << I + 1;
10213 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10214 return;
10215 }
10216
10217 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10218 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10219 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10220 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10221 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10222 << (unsigned)isObjectArgument << I + 1;
10223 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10224 return;
10225 }
10226
10227 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10229 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10230 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10231 << FromQs.hasUnaligned() << I + 1;
10232 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10233 return;
10234 }
10235
10236 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10237 assert(CVR && "unexpected qualifiers mismatch")((CVR && "unexpected qualifiers mismatch") ? static_cast
<void> (0) : __assert_fail ("CVR && \"unexpected qualifiers mismatch\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10237, __PRETTY_FUNCTION__))
;
10238
10239 if (isObjectArgument) {
10240 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10241 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10242 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10243 << (CVR - 1);
10244 } else {
10245 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10246 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10247 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10248 << (CVR - 1) << I + 1;
10249 }
10250 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10251 return;
10252 }
10253
10254 // Special diagnostic for failure to convert an initializer list, since
10255 // telling the user that it has type void is not useful.
10256 if (FromExpr && isa<InitListExpr>(FromExpr)) {
10257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10258 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10259 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10260 << ToTy << (unsigned)isObjectArgument << I + 1;
10261 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10262 return;
10263 }
10264
10265 // Diagnose references or pointers to incomplete types differently,
10266 // since it's far from impossible that the incompleteness triggered
10267 // the failure.
10268 QualType TempFromTy = FromTy.getNonReferenceType();
10269 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10270 TempFromTy = PTy->getPointeeType();
10271 if (TempFromTy->isIncompleteType()) {
10272 // Emit the generic diagnostic and, optionally, add the hints to it.
10273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10274 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10275 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10276 << ToTy << (unsigned)isObjectArgument << I + 1
10277 << (unsigned)(Cand->Fix.Kind);
10278
10279 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10280 return;
10281 }
10282
10283 // Diagnose base -> derived pointer conversions.
10284 unsigned BaseToDerivedConversion = 0;
10285 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10286 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10287 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10288 FromPtrTy->getPointeeType()) &&
10289 !FromPtrTy->getPointeeType()->isIncompleteType() &&
10290 !ToPtrTy->getPointeeType()->isIncompleteType() &&
10291 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10292 FromPtrTy->getPointeeType()))
10293 BaseToDerivedConversion = 1;
10294 }
10295 } else if (const ObjCObjectPointerType *FromPtrTy
10296 = FromTy->getAs<ObjCObjectPointerType>()) {
10297 if (const ObjCObjectPointerType *ToPtrTy
10298 = ToTy->getAs<ObjCObjectPointerType>())
10299 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10300 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10301 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10302 FromPtrTy->getPointeeType()) &&
10303 FromIface->isSuperClassOf(ToIface))
10304 BaseToDerivedConversion = 2;
10305 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10306 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10307 !FromTy->isIncompleteType() &&
10308 !ToRefTy->getPointeeType()->isIncompleteType() &&
10309 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10310 BaseToDerivedConversion = 3;
10311 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10312 ToTy.getNonReferenceType().getCanonicalType() ==
10313 FromTy.getNonReferenceType().getCanonicalType()) {
10314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10315 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10316 << (unsigned)isObjectArgument << I + 1
10317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10318 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10319 return;
10320 }
10321 }
10322
10323 if (BaseToDerivedConversion) {
10324 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10325 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10326 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10327 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10328 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10329 return;
10330 }
10331
10332 if (isa<ObjCObjectPointerType>(CFromTy) &&
10333 isa<PointerType>(CToTy)) {
10334 Qualifiers FromQs = CFromTy.getQualifiers();
10335 Qualifiers ToQs = CToTy.getQualifiers();
10336 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10338 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10339 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10340 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10341 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10342 return;
10343 }
10344 }
10345
10346 if (TakingCandidateAddress &&
10347 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10348 return;
10349
10350 // Emit the generic diagnostic and, optionally, add the hints to it.
10351 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10352 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10353 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10354 << ToTy << (unsigned)isObjectArgument << I + 1
10355 << (unsigned)(Cand->Fix.Kind);
10356
10357 // If we can fix the conversion, suggest the FixIts.
10358 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10359 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10360 FDiag << *HI;
10361 S.Diag(Fn->getLocation(), FDiag);
10362
10363 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10364}
10365
10366/// Additional arity mismatch diagnosis specific to a function overload
10367/// candidates. This is not covered by the more general DiagnoseArityMismatch()
10368/// over a candidate in any candidate set.
10369static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10370 unsigned NumArgs) {
10371 FunctionDecl *Fn = Cand->Function;
10372 unsigned MinParams = Fn->getMinRequiredArguments();
10373
10374 // With invalid overloaded operators, it's possible that we think we
10375 // have an arity mismatch when in fact it looks like we have the
10376 // right number of arguments, because only overloaded operators have
10377 // the weird behavior of overloading member and non-member functions.
10378 // Just don't report anything.
10379 if (Fn->isInvalidDecl() &&
10380 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10381 return true;
10382
10383 if (NumArgs < MinParams) {
10384 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10386, __PRETTY_FUNCTION__))
10385 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10386, __PRETTY_FUNCTION__))
10386 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10386, __PRETTY_FUNCTION__))
;
10387 } else {
10388 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10390, __PRETTY_FUNCTION__))
10389 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10390, __PRETTY_FUNCTION__))
10390 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10390, __PRETTY_FUNCTION__))
;
10391 }
10392
10393 return false;
10394}
10395
10396/// General arity mismatch diagnosis over a candidate in a candidate set.
10397static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10398 unsigned NumFormalArgs) {
10399 assert(isa<FunctionDecl>(D) &&((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
10400 "The templated declaration should at least be a function"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
10401 " when diagnosing bad template argument deduction due to too many"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
10402 " or too few arguments")((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10402, __PRETTY_FUNCTION__))
;
10403
10404 FunctionDecl *Fn = cast<FunctionDecl>(D);
10405
10406 // TODO: treat calls to a missing default constructor as a special case
10407 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
10408 unsigned MinParams = Fn->getMinRequiredArguments();
10409
10410 // at least / at most / exactly
10411 unsigned mode, modeCount;
10412 if (NumFormalArgs < MinParams) {
10413 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10414 FnTy->isTemplateVariadic())
10415 mode = 0; // "at least"
10416 else
10417 mode = 2; // "exactly"
10418 modeCount = MinParams;
10419 } else {
10420 if (MinParams != FnTy->getNumParams())
10421 mode = 1; // "at most"
10422 else
10423 mode = 2; // "exactly"
10424 modeCount = FnTy->getNumParams();
10425 }
10426
10427 std::string Description;
10428 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10429 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10430
10431 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10432 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10433 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10434 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10435 else
10436 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10437 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10438 << Description << mode << modeCount << NumFormalArgs;
10439
10440 MaybeEmitInheritedConstructorNote(S, Found);
10441}
10442
10443/// Arity mismatch diagnosis specific to a function overload candidate.
10444static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10445 unsigned NumFormalArgs) {
10446 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10447 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10448}
10449
10450static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10451 if (TemplateDecl *TD = Templated->getDescribedTemplate())
10452 return TD;
10453 llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10454)
10454 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10454)
;
10455}
10456
10457/// Diagnose a failed template-argument deduction.
10458static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10459 DeductionFailureInfo &DeductionFailure,
10460 unsigned NumArgs,
10461 bool TakingCandidateAddress) {
10462 TemplateParameter Param = DeductionFailure.getTemplateParameter();
10463 NamedDecl *ParamD;
10464 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10465 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10466 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10467 switch (DeductionFailure.Result) {
10468 case Sema::TDK_Success:
10469 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10469)
;
10470
10471 case Sema::TDK_Incomplete: {
10472 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10472, __PRETTY_FUNCTION__))
;
10473 S.Diag(Templated->getLocation(),
10474 diag::note_ovl_candidate_incomplete_deduction)
10475 << ParamD->getDeclName();
10476 MaybeEmitInheritedConstructorNote(S, Found);
10477 return;
10478 }
10479
10480 case Sema::TDK_IncompletePack: {
10481 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10481, __PRETTY_FUNCTION__))
;
10482 S.Diag(Templated->getLocation(),
10483 diag::note_ovl_candidate_incomplete_deduction_pack)
10484 << ParamD->getDeclName()
10485 << (DeductionFailure.getFirstArg()->pack_size() + 1)
10486 << *DeductionFailure.getFirstArg();
10487 MaybeEmitInheritedConstructorNote(S, Found);
10488 return;
10489 }
10490
10491 case Sema::TDK_Underqualified: {
10492 assert(ParamD && "no parameter found for bad qualifiers deduction result")((ParamD && "no parameter found for bad qualifiers deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10492, __PRETTY_FUNCTION__))
;
10493 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10494
10495 QualType Param = DeductionFailure.getFirstArg()->getAsType();
10496
10497 // Param will have been canonicalized, but it should just be a
10498 // qualified version of ParamD, so move the qualifiers to that.
10499 QualifierCollector Qs;
10500 Qs.strip(Param);
10501 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10502 assert(S.Context.hasSameType(Param, NonCanonParam))((S.Context.hasSameType(Param, NonCanonParam)) ? static_cast<
void> (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10502, __PRETTY_FUNCTION__))
;
10503
10504 // Arg has also been canonicalized, but there's nothing we can do
10505 // about that. It also doesn't matter as much, because it won't
10506 // have any template parameters in it (because deduction isn't
10507 // done on dependent types).
10508 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10509
10510 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10511 << ParamD->getDeclName() << Arg << NonCanonParam;
10512 MaybeEmitInheritedConstructorNote(S, Found);
10513 return;
10514 }
10515
10516 case Sema::TDK_Inconsistent: {
10517 assert(ParamD && "no parameter found for inconsistent deduction result")((ParamD && "no parameter found for inconsistent deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10517, __PRETTY_FUNCTION__))
;
10518 int which = 0;
10519 if (isa<TemplateTypeParmDecl>(ParamD))
10520 which = 0;
10521 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10522 // Deduction might have failed because we deduced arguments of two
10523 // different types for a non-type template parameter.
10524 // FIXME: Use a different TDK value for this.
10525 QualType T1 =
10526 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10527 QualType T2 =
10528 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10529 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10530 S.Diag(Templated->getLocation(),
10531 diag::note_ovl_candidate_inconsistent_deduction_types)
10532 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10533 << *DeductionFailure.getSecondArg() << T2;
10534 MaybeEmitInheritedConstructorNote(S, Found);
10535 return;
10536 }
10537
10538 which = 1;
10539 } else {
10540 which = 2;
10541 }
10542
10543 // Tweak the diagnostic if the problem is that we deduced packs of
10544 // different arities. We'll print the actual packs anyway in case that
10545 // includes additional useful information.
10546 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10547 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10548 DeductionFailure.getFirstArg()->pack_size() !=
10549 DeductionFailure.getSecondArg()->pack_size()) {
10550 which = 3;
10551 }
10552
10553 S.Diag(Templated->getLocation(),
10554 diag::note_ovl_candidate_inconsistent_deduction)
10555 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10556 << *DeductionFailure.getSecondArg();
10557 MaybeEmitInheritedConstructorNote(S, Found);
10558 return;
10559 }
10560
10561 case Sema::TDK_InvalidExplicitArguments:
10562 assert(ParamD && "no parameter found for invalid explicit arguments")((ParamD && "no parameter found for invalid explicit arguments"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10562, __PRETTY_FUNCTION__))
;
10563 if (ParamD->getDeclName())
10564 S.Diag(Templated->getLocation(),
10565 diag::note_ovl_candidate_explicit_arg_mismatch_named)
10566 << ParamD->getDeclName();
10567 else {
10568 int index = 0;
10569 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10570 index = TTP->getIndex();
10571 else if (NonTypeTemplateParmDecl *NTTP
10572 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10573 index = NTTP->getIndex();
10574 else
10575 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10576 S.Diag(Templated->getLocation(),
10577 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10578 << (index + 1);
10579 }
10580 MaybeEmitInheritedConstructorNote(S, Found);
10581 return;
10582
10583 case Sema::TDK_ConstraintsNotSatisfied: {
10584 // Format the template argument list into the argument string.
10585 SmallString<128> TemplateArgString;
10586 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10587 TemplateArgString = " ";
10588 TemplateArgString += S.getTemplateArgumentBindingsText(
10589 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10590 if (TemplateArgString.size() == 1)
10591 TemplateArgString.clear();
10592 S.Diag(Templated->getLocation(),
10593 diag::note_ovl_candidate_unsatisfied_constraints)
10594 << TemplateArgString;
10595
10596 S.DiagnoseUnsatisfiedConstraint(
10597 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10598 return;
10599 }
10600 case Sema::TDK_TooManyArguments:
10601 case Sema::TDK_TooFewArguments:
10602 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10603 return;
10604
10605 case Sema::TDK_InstantiationDepth:
10606 S.Diag(Templated->getLocation(),
10607 diag::note_ovl_candidate_instantiation_depth);
10608 MaybeEmitInheritedConstructorNote(S, Found);
10609 return;
10610
10611 case Sema::TDK_SubstitutionFailure: {
10612 // Format the template argument list into the argument string.
10613 SmallString<128> TemplateArgString;
10614 if (TemplateArgumentList *Args =
10615 DeductionFailure.getTemplateArgumentList()) {
10616 TemplateArgString = " ";
10617 TemplateArgString += S.getTemplateArgumentBindingsText(
10618 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10619 if (TemplateArgString.size() == 1)
10620 TemplateArgString.clear();
10621 }
10622
10623 // If this candidate was disabled by enable_if, say so.
10624 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10625 if (PDiag && PDiag->second.getDiagID() ==
10626 diag::err_typename_nested_not_found_enable_if) {
10627 // FIXME: Use the source range of the condition, and the fully-qualified
10628 // name of the enable_if template. These are both present in PDiag.
10629 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10630 << "'enable_if'" << TemplateArgString;
10631 return;
10632 }
10633
10634 // We found a specific requirement that disabled the enable_if.
10635 if (PDiag && PDiag->second.getDiagID() ==
10636 diag::err_typename_nested_not_found_requirement) {
10637 S.Diag(Templated->getLocation(),
10638 diag::note_ovl_candidate_disabled_by_requirement)
10639 << PDiag->second.getStringArg(0) << TemplateArgString;
10640 return;
10641 }
10642
10643 // Format the SFINAE diagnostic into the argument string.
10644 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10645 // formatted message in another diagnostic.
10646 SmallString<128> SFINAEArgString;
10647 SourceRange R;
10648 if (PDiag) {
10649 SFINAEArgString = ": ";
10650 R = SourceRange(PDiag->first, PDiag->first);
10651 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10652 }
10653
10654 S.Diag(Templated->getLocation(),
10655 diag::note_ovl_candidate_substitution_failure)
10656 << TemplateArgString << SFINAEArgString << R;
10657 MaybeEmitInheritedConstructorNote(S, Found);
10658 return;
10659 }
10660
10661 case Sema::TDK_DeducedMismatch:
10662 case Sema::TDK_DeducedMismatchNested: {
10663 // Format the template argument list into the argument string.
10664 SmallString<128> TemplateArgString;
10665 if (TemplateArgumentList *Args =
10666 DeductionFailure.getTemplateArgumentList()) {
10667 TemplateArgString = " ";
10668 TemplateArgString += S.getTemplateArgumentBindingsText(
10669 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10670 if (TemplateArgString.size() == 1)
10671 TemplateArgString.clear();
10672 }
10673
10674 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10675 << (*DeductionFailure.getCallArgIndex() + 1)
10676 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10677 << TemplateArgString
10678 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10679 break;
10680 }
10681
10682 case Sema::TDK_NonDeducedMismatch: {
10683 // FIXME: Provide a source location to indicate what we couldn't match.
10684 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10685 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10686 if (FirstTA.getKind() == TemplateArgument::Template &&
10687 SecondTA.getKind() == TemplateArgument::Template) {
10688 TemplateName FirstTN = FirstTA.getAsTemplate();
10689 TemplateName SecondTN = SecondTA.getAsTemplate();
10690 if (FirstTN.getKind() == TemplateName::Template &&
10691 SecondTN.getKind() == TemplateName::Template) {
10692 if (FirstTN.getAsTemplateDecl()->getName() ==
10693 SecondTN.getAsTemplateDecl()->getName()) {
10694 // FIXME: This fixes a bad diagnostic where both templates are named
10695 // the same. This particular case is a bit difficult since:
10696 // 1) It is passed as a string to the diagnostic printer.
10697 // 2) The diagnostic printer only attempts to find a better
10698 // name for types, not decls.
10699 // Ideally, this should folded into the diagnostic printer.
10700 S.Diag(Templated->getLocation(),
10701 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10702 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10703 return;
10704 }
10705 }
10706 }
10707
10708 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10709 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10710 return;
10711
10712 // FIXME: For generic lambda parameters, check if the function is a lambda
10713 // call operator, and if so, emit a prettier and more informative
10714 // diagnostic that mentions 'auto' and lambda in addition to
10715 // (or instead of?) the canonical template type parameters.
10716 S.Diag(Templated->getLocation(),
10717 diag::note_ovl_candidate_non_deduced_mismatch)
10718 << FirstTA << SecondTA;
10719 return;
10720 }
10721 // TODO: diagnose these individually, then kill off
10722 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10723 case Sema::TDK_MiscellaneousDeductionFailure:
10724 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10725 MaybeEmitInheritedConstructorNote(S, Found);
10726 return;
10727 case Sema::TDK_CUDATargetMismatch:
10728 S.Diag(Templated->getLocation(),
10729 diag::note_cuda_ovl_candidate_target_mismatch);
10730 return;
10731 }
10732}
10733
10734/// Diagnose a failed template-argument deduction, for function calls.
10735static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10736 unsigned NumArgs,
10737 bool TakingCandidateAddress) {
10738 unsigned TDK = Cand->DeductionFailure.Result;
10739 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10740 if (CheckArityMismatch(S, Cand, NumArgs))
10741 return;
10742 }
10743 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10744 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10745}
10746
10747/// CUDA: diagnose an invalid call across targets.
10748static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10749 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10750 FunctionDecl *Callee = Cand->Function;
10751
10752 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10753 CalleeTarget = S.IdentifyCUDATarget(Callee);
10754
10755 std::string FnDesc;
10756 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10757 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10758 Cand->getRewriteKind(), FnDesc);
10759
10760 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10761 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10762 << FnDesc /* Ignored */
10763 << CalleeTarget << CallerTarget;
10764
10765 // This could be an implicit constructor for which we could not infer the
10766 // target due to a collsion. Diagnose that case.
10767 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10768 if (Meth != nullptr && Meth->isImplicit()) {
10769 CXXRecordDecl *ParentClass = Meth->getParent();
10770 Sema::CXXSpecialMember CSM;
10771
10772 switch (FnKindPair.first) {
10773 default:
10774 return;
10775 case oc_implicit_default_constructor:
10776 CSM = Sema::CXXDefaultConstructor;
10777 break;
10778 case oc_implicit_copy_constructor:
10779 CSM = Sema::CXXCopyConstructor;
10780 break;
10781 case oc_implicit_move_constructor:
10782 CSM = Sema::CXXMoveConstructor;
10783 break;
10784 case oc_implicit_copy_assignment:
10785 CSM = Sema::CXXCopyAssignment;
10786 break;
10787 case oc_implicit_move_assignment:
10788 CSM = Sema::CXXMoveAssignment;
10789 break;
10790 };
10791
10792 bool ConstRHS = false;
10793 if (Meth->getNumParams()) {
10794 if (const ReferenceType *RT =
10795 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10796 ConstRHS = RT->getPointeeType().isConstQualified();
10797 }
10798 }
10799
10800 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10801 /* ConstRHS */ ConstRHS,
10802 /* Diagnose */ true);
10803 }
10804}
10805
10806static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10807 FunctionDecl *Callee = Cand->Function;
10808 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10809
10810 S.Diag(Callee->getLocation(),
10811 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10812 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10813}
10814
10815static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10816 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10817 assert(ES.isExplicit() && "not an explicit candidate")((ES.isExplicit() && "not an explicit candidate") ? static_cast
<void> (0) : __assert_fail ("ES.isExplicit() && \"not an explicit candidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10817, __PRETTY_FUNCTION__))
;
10818
10819 unsigned Kind;
10820 switch (Cand->Function->getDeclKind()) {
10821 case Decl::Kind::CXXConstructor:
10822 Kind = 0;
10823 break;
10824 case Decl::Kind::CXXConversion:
10825 Kind = 1;
10826 break;
10827 case Decl::Kind::CXXDeductionGuide:
10828 Kind = Cand->Function->isImplicit() ? 0 : 2;
10829 break;
10830 default:
10831 llvm_unreachable("invalid Decl")::llvm::llvm_unreachable_internal("invalid Decl", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10831)
;
10832 }
10833
10834 // Note the location of the first (in-class) declaration; a redeclaration
10835 // (particularly an out-of-class definition) will typically lack the
10836 // 'explicit' specifier.
10837 // FIXME: This is probably a good thing to do for all 'candidate' notes.
10838 FunctionDecl *First = Cand->Function->getFirstDecl();
10839 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10840 First = Pattern->getFirstDecl();
10841
10842 S.Diag(First->getLocation(),
10843 diag::note_ovl_candidate_explicit)
10844 << Kind << (ES.getExpr() ? 1 : 0)
10845 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10846}
10847
10848static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10849 FunctionDecl *Callee = Cand->Function;
10850
10851 S.Diag(Callee->getLocation(),
10852 diag::note_ovl_candidate_disabled_by_extension)
10853 << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10854}
10855
10856/// Generates a 'note' diagnostic for an overload candidate. We've
10857/// already generated a primary error at the call site.
10858///
10859/// It really does need to be a single diagnostic with its caret
10860/// pointed at the candidate declaration. Yes, this creates some
10861/// major challenges of technical writing. Yes, this makes pointing
10862/// out problems with specific arguments quite awkward. It's still
10863/// better than generating twenty screens of text for every failed
10864/// overload.
10865///
10866/// It would be great to be able to express per-candidate problems
10867/// more richly for those diagnostic clients that cared, but we'd
10868/// still have to be just as careful with the default diagnostics.
10869/// \param CtorDestAS Addr space of object being constructed (for ctor
10870/// candidates only).
10871static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10872 unsigned NumArgs,
10873 bool TakingCandidateAddress,
10874 LangAS CtorDestAS = LangAS::Default) {
10875 FunctionDecl *Fn = Cand->Function;
10876
10877 // Note deleted candidates, but only if they're viable.
10878 if (Cand->Viable) {
10879 if (Fn->isDeleted()) {
10880 std::string FnDesc;
10881 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10882 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10883 Cand->getRewriteKind(), FnDesc);
10884
10885 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10886 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10887 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10888 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10889 return;
10890 }
10891
10892 // We don't really have anything else to say about viable candidates.
10893 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10894 return;
10895 }
10896
10897 switch (Cand->FailureKind) {
10898 case ovl_fail_too_many_arguments:
10899 case ovl_fail_too_few_arguments:
10900 return DiagnoseArityMismatch(S, Cand, NumArgs);
10901
10902 case ovl_fail_bad_deduction:
10903 return DiagnoseBadDeduction(S, Cand, NumArgs,
10904 TakingCandidateAddress);
10905
10906 case ovl_fail_illegal_constructor: {
10907 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10908 << (Fn->getPrimaryTemplate() ? 1 : 0);
10909 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10910 return;
10911 }
10912
10913 case ovl_fail_object_addrspace_mismatch: {
10914 Qualifiers QualsForPrinting;
10915 QualsForPrinting.setAddressSpace(CtorDestAS);
10916 S.Diag(Fn->getLocation(),
10917 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10918 << QualsForPrinting;
10919 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10920 return;
10921 }
10922
10923 case ovl_fail_trivial_conversion:
10924 case ovl_fail_bad_final_conversion:
10925 case ovl_fail_final_conversion_not_exact:
10926 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10927
10928 case ovl_fail_bad_conversion: {
10929 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10930 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10931 if (Cand->Conversions[I].isBad())
10932 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10933
10934 // FIXME: this currently happens when we're called from SemaInit
10935 // when user-conversion overload fails. Figure out how to handle
10936 // those conditions and diagnose them well.
10937 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10938 }
10939
10940 case ovl_fail_bad_target:
10941 return DiagnoseBadTarget(S, Cand);
10942
10943 case ovl_fail_enable_if:
10944 return DiagnoseFailedEnableIfAttr(S, Cand);
10945
10946 case ovl_fail_explicit:
10947 return DiagnoseFailedExplicitSpec(S, Cand);
10948
10949 case ovl_fail_ext_disabled:
10950 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10951
10952 case ovl_fail_inhctor_slice:
10953 // It's generally not interesting to note copy/move constructors here.
10954 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10955 return;
10956 S.Diag(Fn->getLocation(),
10957 diag::note_ovl_candidate_inherited_constructor_slice)
10958 << (Fn->getPrimaryTemplate() ? 1 : 0)
10959 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10960 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10961 return;
10962
10963 case ovl_fail_addr_not_available: {
10964 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10965 (void)Available;
10966 assert(!Available)((!Available) ? static_cast<void> (0) : __assert_fail (
"!Available", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 10966, __PRETTY_FUNCTION__))
;
10967 break;
10968 }
10969 case ovl_non_default_multiversion_function:
10970 // Do nothing, these should simply be ignored.
10971 break;
10972
10973 case ovl_fail_constraints_not_satisfied: {
10974 std::string FnDesc;
10975 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10976 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10977 Cand->getRewriteKind(), FnDesc);
10978
10979 S.Diag(Fn->getLocation(),
10980 diag::note_ovl_candidate_constraints_not_satisfied)
10981 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10982 << FnDesc /* Ignored */;
10983 ConstraintSatisfaction Satisfaction;
10984 if (S.CheckConstraintSatisfaction(Fn->getTrailingRequiresClause(),
10985 Satisfaction))
10986 break;
10987 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10988 }
10989 }
10990}
10991
10992static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10993 // Desugar the type of the surrogate down to a function type,
10994 // retaining as many typedefs as possible while still showing
10995 // the function type (and, therefore, its parameter types).
10996 QualType FnType = Cand->Surrogate->getConversionType();
10997 bool isLValueReference = false;
10998 bool isRValueReference = false;
10999 bool isPointer = false;
11000 if (const LValueReferenceType *FnTypeRef =
11001 FnType->getAs<LValueReferenceType>()) {
11002 FnType = FnTypeRef->getPointeeType();
11003 isLValueReference = true;
11004 } else if (const RValueReferenceType *FnTypeRef =
11005 FnType->getAs<RValueReferenceType>()) {
11006 FnType = FnTypeRef->getPointeeType();
11007 isRValueReference = true;
11008 }
11009 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11010 FnType = FnTypePtr->getPointeeType();
11011 isPointer = true;
11012 }
11013 // Desugar down to a function type.
11014 FnType = QualType(FnType->getAs<FunctionType>(), 0);
11015 // Reconstruct the pointer/reference as appropriate.
11016 if (isPointer) FnType = S.Context.getPointerType(FnType);
11017 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11018 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11019
11020 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11021 << FnType;
11022}
11023
11024static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11025 SourceLocation OpLoc,
11026 OverloadCandidate *Cand) {
11027 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")((Cand->Conversions.size() <= 2 && "builtin operator is not binary"
) ? static_cast<void> (0) : __assert_fail ("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11027, __PRETTY_FUNCTION__))
;
11028 std::string TypeStr("operator");
11029 TypeStr += Opc;
11030 TypeStr += "(";
11031 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11032 if (Cand->Conversions.size() == 1) {
11033 TypeStr += ")";
11034 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11035 } else {
11036 TypeStr += ", ";
11037 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11038 TypeStr += ")";
11039 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11040 }
11041}
11042
11043static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11044 OverloadCandidate *Cand) {
11045 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11046 if (ICS.isBad()) break; // all meaningless after first invalid
11047 if (!ICS.isAmbiguous()) continue;
11048
11049 ICS.DiagnoseAmbiguousConversion(
11050 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11051 }
11052}
11053
11054static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11055 if (Cand->Function)
11056 return Cand->Function->getLocation();
11057 if (Cand->IsSurrogate)
11058 return Cand->Surrogate->getLocation();
11059 return SourceLocation();
11060}
11061
11062static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11063 switch ((Sema::TemplateDeductionResult)DFI.Result) {
11064 case Sema::TDK_Success:
11065 case Sema::TDK_NonDependentConversionFailure:
11066 llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11066)
;
11067
11068 case Sema::TDK_Invalid:
11069 case Sema::TDK_Incomplete:
11070 case Sema::TDK_IncompletePack:
11071 return 1;
11072
11073 case Sema::TDK_Underqualified:
11074 case Sema::TDK_Inconsistent:
11075 return 2;
11076
11077 case Sema::TDK_SubstitutionFailure:
11078 case Sema::TDK_DeducedMismatch:
11079 case Sema::TDK_ConstraintsNotSatisfied:
11080 case Sema::TDK_DeducedMismatchNested:
11081 case Sema::TDK_NonDeducedMismatch:
11082 case Sema::TDK_MiscellaneousDeductionFailure:
11083 case Sema::TDK_CUDATargetMismatch:
11084 return 3;
11085
11086 case Sema::TDK_InstantiationDepth:
11087 return 4;
11088
11089 case Sema::TDK_InvalidExplicitArguments:
11090 return 5;
11091
11092 case Sema::TDK_TooManyArguments:
11093 case Sema::TDK_TooFewArguments:
11094 return 6;
11095 }
11096 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11096)
;
11097}
11098
11099namespace {
11100struct CompareOverloadCandidatesForDisplay {
11101 Sema &S;
11102 SourceLocation Loc;
11103 size_t NumArgs;
11104 OverloadCandidateSet::CandidateSetKind CSK;
11105
11106 CompareOverloadCandidatesForDisplay(
11107 Sema &S, SourceLocation Loc, size_t NArgs,
11108 OverloadCandidateSet::CandidateSetKind CSK)
11109 : S(S), NumArgs(NArgs), CSK(CSK) {}
11110
11111 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11112 // If there are too many or too few arguments, that's the high-order bit we
11113 // want to sort by, even if the immediate failure kind was something else.
11114 if (C->FailureKind == ovl_fail_too_many_arguments ||
11115 C->FailureKind == ovl_fail_too_few_arguments)
11116 return static_cast<OverloadFailureKind>(C->FailureKind);
11117
11118 if (C->Function) {
11119 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11120 return ovl_fail_too_many_arguments;
11121 if (NumArgs < C->Function->getMinRequiredArguments())
11122 return ovl_fail_too_few_arguments;
11123 }
11124
11125 return static_cast<OverloadFailureKind>(C->FailureKind);
11126 }
11127
11128 bool operator()(const OverloadCandidate *L,
11129 const OverloadCandidate *R) {
11130 // Fast-path this check.
11131 if (L == R) return false;
11132
11133 // Order first by viability.
11134 if (L->Viable) {
11135 if (!R->Viable) return true;
11136
11137 // TODO: introduce a tri-valued comparison for overload
11138 // candidates. Would be more worthwhile if we had a sort
11139 // that could exploit it.
11140 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11141 return true;
11142 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11143 return false;
11144 } else if (R->Viable)
11145 return false;
11146
11147 assert(L->Viable == R->Viable)((L->Viable == R->Viable) ? static_cast<void> (0)
: __assert_fail ("L->Viable == R->Viable", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11147, __PRETTY_FUNCTION__))
;
11148
11149 // Criteria by which we can sort non-viable candidates:
11150 if (!L->Viable) {
11151 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11152 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11153
11154 // 1. Arity mismatches come after other candidates.
11155 if (LFailureKind == ovl_fail_too_many_arguments ||
11156 LFailureKind == ovl_fail_too_few_arguments) {
11157 if (RFailureKind == ovl_fail_too_many_arguments ||
11158 RFailureKind == ovl_fail_too_few_arguments) {
11159 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11160 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11161 if (LDist == RDist) {
11162 if (LFailureKind == RFailureKind)
11163 // Sort non-surrogates before surrogates.
11164 return !L->IsSurrogate && R->IsSurrogate;
11165 // Sort candidates requiring fewer parameters than there were
11166 // arguments given after candidates requiring more parameters
11167 // than there were arguments given.
11168 return LFailureKind == ovl_fail_too_many_arguments;
11169 }
11170 return LDist < RDist;
11171 }
11172 return false;
11173 }
11174 if (RFailureKind == ovl_fail_too_many_arguments ||
11175 RFailureKind == ovl_fail_too_few_arguments)
11176 return true;
11177
11178 // 2. Bad conversions come first and are ordered by the number
11179 // of bad conversions and quality of good conversions.
11180 if (LFailureKind == ovl_fail_bad_conversion) {
11181 if (RFailureKind != ovl_fail_bad_conversion)
11182 return true;
11183
11184 // The conversion that can be fixed with a smaller number of changes,
11185 // comes first.
11186 unsigned numLFixes = L->Fix.NumConversionsFixed;
11187 unsigned numRFixes = R->Fix.NumConversionsFixed;
11188 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes;
11189 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes;
11190 if (numLFixes != numRFixes) {
11191 return numLFixes < numRFixes;
11192 }
11193
11194 // If there's any ordering between the defined conversions...
11195 // FIXME: this might not be transitive.
11196 assert(L->Conversions.size() == R->Conversions.size())((L->Conversions.size() == R->Conversions.size()) ? static_cast
<void> (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11196, __PRETTY_FUNCTION__))
;
11197
11198 int leftBetter = 0;
11199 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11200 for (unsigned E = L->Conversions.size(); I != E; ++I) {
11201 switch (CompareImplicitConversionSequences(S, Loc,
11202 L->Conversions[I],
11203 R->Conversions[I])) {
11204 case ImplicitConversionSequence::Better:
11205 leftBetter++;
11206 break;
11207
11208 case ImplicitConversionSequence::Worse:
11209 leftBetter--;
11210 break;
11211
11212 case ImplicitConversionSequence::Indistinguishable:
11213 break;
11214 }
11215 }
11216 if (leftBetter > 0) return true;
11217 if (leftBetter < 0) return false;
11218
11219 } else if (RFailureKind == ovl_fail_bad_conversion)
11220 return false;
11221
11222 if (LFailureKind == ovl_fail_bad_deduction) {
11223 if (RFailureKind != ovl_fail_bad_deduction)
11224 return true;
11225
11226 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11227 return RankDeductionFailure(L->DeductionFailure)
11228 < RankDeductionFailure(R->DeductionFailure);
11229 } else if (RFailureKind == ovl_fail_bad_deduction)
11230 return false;
11231
11232 // TODO: others?
11233 }
11234
11235 // Sort everything else by location.
11236 SourceLocation LLoc = GetLocationForCandidate(L);
11237 SourceLocation RLoc = GetLocationForCandidate(R);
11238
11239 // Put candidates without locations (e.g. builtins) at the end.
11240 if (LLoc.isInvalid()) return false;
11241 if (RLoc.isInvalid()) return true;
11242
11243 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11244 }
11245};
11246}
11247
11248/// CompleteNonViableCandidate - Normally, overload resolution only
11249/// computes up to the first bad conversion. Produces the FixIt set if
11250/// possible.
11251static void
11252CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11253 ArrayRef<Expr *> Args,
11254 OverloadCandidateSet::CandidateSetKind CSK) {
11255 assert(!Cand->Viable)((!Cand->Viable) ? static_cast<void> (0) : __assert_fail
("!Cand->Viable", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11255, __PRETTY_FUNCTION__))
;
11256
11257 // Don't do anything on failures other than bad conversion.
11258 if (Cand->FailureKind != ovl_fail_bad_conversion)
11259 return;
11260
11261 // We only want the FixIts if all the arguments can be corrected.
11262 bool Unfixable = false;
11263 // Use a implicit copy initialization to check conversion fixes.
11264 Cand->Fix.setConversionChecker(TryCopyInitialization);
11265
11266 // Attempt to fix the bad conversion.
11267 unsigned ConvCount = Cand->Conversions.size();
11268 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11269 ++ConvIdx) {
11270 assert(ConvIdx != ConvCount && "no bad conversion in candidate")((ConvIdx != ConvCount && "no bad conversion in candidate"
) ? static_cast<void> (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11270, __PRETTY_FUNCTION__))
;
11271 if (Cand->Conversions[ConvIdx].isInitialized() &&
11272 Cand->Conversions[ConvIdx].isBad()) {
11273 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11274 break;
11275 }
11276 }
11277
11278 // FIXME: this should probably be preserved from the overload
11279 // operation somehow.
11280 bool SuppressUserConversions = false;
11281
11282 unsigned ConvIdx = 0;
11283 unsigned ArgIdx = 0;
11284 ArrayRef<QualType> ParamTypes;
11285 bool Reversed = Cand->RewriteKind & CRK_Reversed;
11286
11287 if (Cand->IsSurrogate) {
11288 QualType ConvType
11289 = Cand->Surrogate->getConversionType().getNonReferenceType();
11290 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11291 ConvType = ConvPtrType->getPointeeType();
11292 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11293 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11294 ConvIdx = 1;
11295 } else if (Cand->Function) {
11296 ParamTypes =
11297 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11298 if (isa<CXXMethodDecl>(Cand->Function) &&
11299 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11300 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11301 ConvIdx = 1;
11302 if (CSK == OverloadCandidateSet::CSK_Operator &&
11303 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11304 // Argument 0 is 'this', which doesn't have a corresponding parameter.
11305 ArgIdx = 1;
11306 }
11307 } else {
11308 // Builtin operator.
11309 assert(ConvCount <= 3)((ConvCount <= 3) ? static_cast<void> (0) : __assert_fail
("ConvCount <= 3", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11309, __PRETTY_FUNCTION__))
;
11310 ParamTypes = Cand->BuiltinParamTypes;
11311 }
11312
11313 // Fill in the rest of the conversions.
11314 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11315 ConvIdx != ConvCount;
11316 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11317 assert(ArgIdx < Args.size() && "no argument for this arg conversion")((ArgIdx < Args.size() && "no argument for this arg conversion"
) ? static_cast<void> (0) : __assert_fail ("ArgIdx < Args.size() && \"no argument for this arg conversion\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11317, __PRETTY_FUNCTION__))
;
11318 if (Cand->Conversions[ConvIdx].isInitialized()) {
11319 // We've already checked this conversion.
11320 } else if (ParamIdx < ParamTypes.size()) {
11321 if (ParamTypes[ParamIdx]->isDependentType())
11322 Cand->Conversions[ConvIdx].setAsIdentityConversion(
11323 Args[ArgIdx]->getType());
11324 else {
11325 Cand->Conversions[ConvIdx] =
11326 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11327 SuppressUserConversions,
11328 /*InOverloadResolution=*/true,
11329 /*AllowObjCWritebackConversion=*/
11330 S.getLangOpts().ObjCAutoRefCount);
11331 // Store the FixIt in the candidate if it exists.
11332 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11333 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11334 }
11335 } else
11336 Cand->Conversions[ConvIdx].setEllipsis();
11337 }
11338}
11339
11340SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11341 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11342 SourceLocation OpLoc,
11343 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11344 // Sort the candidates by viability and position. Sorting directly would
11345 // be prohibitive, so we make a set of pointers and sort those.
11346 SmallVector<OverloadCandidate*, 32> Cands;
11347 if (OCD == OCD_AllCandidates) Cands.reserve(size());
11348 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11349 if (!Filter(*Cand))
11350 continue;
11351 switch (OCD) {
11352 case OCD_AllCandidates:
11353 if (!Cand->Viable) {
11354 if (!Cand->Function && !Cand->IsSurrogate) {
11355 // This a non-viable builtin candidate. We do not, in general,
11356 // want to list every possible builtin candidate.
11357 continue;
11358 }
11359 CompleteNonViableCandidate(S, Cand, Args, Kind);
11360 }
11361 break;
11362
11363 case OCD_ViableCandidates:
11364 if (!Cand->Viable)
11365 continue;
11366 break;
11367
11368 case OCD_AmbiguousCandidates:
11369 if (!Cand->Best)
11370 continue;
11371 break;
11372 }
11373
11374 Cands.push_back(Cand);
11375 }
11376
11377 llvm::stable_sort(
11378 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11379
11380 return Cands;
11381}
11382
11383/// When overload resolution fails, prints diagnostic messages containing the
11384/// candidates in the candidate set.
11385void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11386 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11387 StringRef Opc, SourceLocation OpLoc,
11388 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11389
11390 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11391
11392 S.Diag(PD.first, PD.second);
11393
11394 NoteCandidates(S, Args, Cands, Opc, OpLoc);
11395
11396 if (OCD == OCD_AmbiguousCandidates)
11397 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11398}
11399
11400void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11401 ArrayRef<OverloadCandidate *> Cands,
11402 StringRef Opc, SourceLocation OpLoc) {
11403 bool ReportedAmbiguousConversions = false;
11404
11405 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11406 unsigned CandsShown = 0;
11407 auto I = Cands.begin(), E = Cands.end();
11408 for (; I != E; ++I) {
11409 OverloadCandidate *Cand = *I;
11410
11411 // Set an arbitrary limit on the number of candidate functions we'll spam
11412 // the user with. FIXME: This limit should depend on details of the
11413 // candidate list.
11414 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11415 break;
11416 }
11417 ++CandsShown;
11418
11419 if (Cand->Function)
11420 NoteFunctionCandidate(S, Cand, Args.size(),
11421 /*TakingCandidateAddress=*/false, DestAS);
11422 else if (Cand->IsSurrogate)
11423 NoteSurrogateCandidate(S, Cand);
11424 else {
11425 assert(Cand->Viable &&((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11426, __PRETTY_FUNCTION__))
11426 "Non-viable built-in candidates are not added to Cands.")((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11426, __PRETTY_FUNCTION__))
;
11427 // Generally we only see ambiguities including viable builtin
11428 // operators if overload resolution got screwed up by an
11429 // ambiguous user-defined conversion.
11430 //
11431 // FIXME: It's quite possible for different conversions to see
11432 // different ambiguities, though.
11433 if (!ReportedAmbiguousConversions) {
11434 NoteAmbiguousUserConversions(S, OpLoc, Cand);
11435 ReportedAmbiguousConversions = true;
11436 }
11437
11438 // If this is a viable builtin, print it.
11439 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11440 }
11441 }
11442
11443 if (I != E)
11444 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11445}
11446
11447static SourceLocation
11448GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11449 return Cand->Specialization ? Cand->Specialization->getLocation()
11450 : SourceLocation();
11451}
11452
11453namespace {
11454struct CompareTemplateSpecCandidatesForDisplay {
11455 Sema &S;
11456 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11457
11458 bool operator()(const TemplateSpecCandidate *L,
11459 const TemplateSpecCandidate *R) {
11460 // Fast-path this check.
11461 if (L == R)
11462 return false;
11463
11464 // Assuming that both candidates are not matches...
11465
11466 // Sort by the ranking of deduction failures.
11467 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11468 return RankDeductionFailure(L->DeductionFailure) <
11469 RankDeductionFailure(R->DeductionFailure);
11470
11471 // Sort everything else by location.
11472 SourceLocation LLoc = GetLocationForCandidate(L);
11473 SourceLocation RLoc = GetLocationForCandidate(R);
11474
11475 // Put candidates without locations (e.g. builtins) at the end.
11476 if (LLoc.isInvalid())
11477 return false;
11478 if (RLoc.isInvalid())
11479 return true;
11480
11481 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11482 }
11483};
11484}
11485
11486/// Diagnose a template argument deduction failure.
11487/// We are treating these failures as overload failures due to bad
11488/// deductions.
11489void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11490 bool ForTakingAddress) {
11491 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11492 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11493}
11494
11495void TemplateSpecCandidateSet::destroyCandidates() {
11496 for (iterator i = begin(), e = end(); i != e; ++i) {
11497 i->DeductionFailure.Destroy();
11498 }
11499}
11500
11501void TemplateSpecCandidateSet::clear() {
11502 destroyCandidates();
11503 Candidates.clear();
11504}
11505
11506/// NoteCandidates - When no template specialization match is found, prints
11507/// diagnostic messages containing the non-matching specializations that form
11508/// the candidate set.
11509/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11510/// OCD == OCD_AllCandidates and Cand->Viable == false.
11511void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11512 // Sort the candidates by position (assuming no candidate is a match).
11513 // Sorting directly would be prohibitive, so we make a set of pointers
11514 // and sort those.
11515 SmallVector<TemplateSpecCandidate *, 32> Cands;
11516 Cands.reserve(size());
11517 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11518 if (Cand->Specialization)
11519 Cands.push_back(Cand);
11520 // Otherwise, this is a non-matching builtin candidate. We do not,
11521 // in general, want to list every possible builtin candidate.
11522 }
11523
11524 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11525
11526 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11527 // for generalization purposes (?).
11528 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11529
11530 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11531 unsigned CandsShown = 0;
11532 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11533 TemplateSpecCandidate *Cand = *I;
11534
11535 // Set an arbitrary limit on the number of candidates we'll spam
11536 // the user with. FIXME: This limit should depend on details of the
11537 // candidate list.
11538 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11539 break;
11540 ++CandsShown;
11541
11542 assert(Cand->Specialization &&((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11543, __PRETTY_FUNCTION__))
11543 "Non-matching built-in candidates are not added to Cands.")((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11543, __PRETTY_FUNCTION__))
;
11544 Cand->NoteDeductionFailure(S, ForTakingAddress);
11545 }
11546
11547 if (I != E)
11548 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11549}
11550
11551// [PossiblyAFunctionType] --> [Return]
11552// NonFunctionType --> NonFunctionType
11553// R (A) --> R(A)
11554// R (*)(A) --> R (A)
11555// R (&)(A) --> R (A)
11556// R (S::*)(A) --> R (A)
11557QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11558 QualType Ret = PossiblyAFunctionType;
11559 if (const PointerType *ToTypePtr =
11560 PossiblyAFunctionType->getAs<PointerType>())
11561 Ret = ToTypePtr->getPointeeType();
11562 else if (const ReferenceType *ToTypeRef =
11563 PossiblyAFunctionType->getAs<ReferenceType>())
11564 Ret = ToTypeRef->getPointeeType();
11565 else if (const MemberPointerType *MemTypePtr =
11566 PossiblyAFunctionType->getAs<MemberPointerType>())
11567 Ret = MemTypePtr->getPointeeType();
11568 Ret =
11569 Context.getCanonicalType(Ret).getUnqualifiedType();
11570 return Ret;
11571}
11572
11573static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11574 bool Complain = true) {
11575 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11576 S.DeduceReturnType(FD, Loc, Complain))
11577 return true;
11578
11579 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11580 if (S.getLangOpts().CPlusPlus17 &&
11581 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11582 !S.ResolveExceptionSpec(Loc, FPT))
11583 return true;
11584
11585 return false;
11586}
11587
11588namespace {
11589// A helper class to help with address of function resolution
11590// - allows us to avoid passing around all those ugly parameters
11591class AddressOfFunctionResolver {
11592 Sema& S;
11593 Expr* SourceExpr;
11594 const QualType& TargetType;
11595 QualType TargetFunctionType; // Extracted function type from target type
11596
11597 bool Complain;
11598 //DeclAccessPair& ResultFunctionAccessPair;
11599 ASTContext& Context;
11600
11601 bool TargetTypeIsNonStaticMemberFunction;
11602 bool FoundNonTemplateFunction;
11603 bool StaticMemberFunctionFromBoundPointer;
11604 bool HasComplained;
11605
11606 OverloadExpr::FindResult OvlExprInfo;
11607 OverloadExpr *OvlExpr;
11608 TemplateArgumentListInfo OvlExplicitTemplateArgs;
11609 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11610 TemplateSpecCandidateSet FailedCandidates;
11611
11612public:
11613 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11614 const QualType &TargetType, bool Complain)
11615 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11616 Complain(Complain), Context(S.getASTContext()),
11617 TargetTypeIsNonStaticMemberFunction(
11618 !!TargetType->getAs<MemberPointerType>()),
11619 FoundNonTemplateFunction(false),
11620 StaticMemberFunctionFromBoundPointer(false),
11621 HasComplained(false),
11622 OvlExprInfo(OverloadExpr::find(SourceExpr)),
11623 OvlExpr(OvlExprInfo.Expression),
11624 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11625 ExtractUnqualifiedFunctionTypeFromTargetType();
11626
11627 if (TargetFunctionType->isFunctionType()) {
11628 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11629 if (!UME->isImplicitAccess() &&
11630 !S.ResolveSingleFunctionTemplateSpecialization(UME))
11631 StaticMemberFunctionFromBoundPointer = true;
11632 } else if (OvlExpr->hasExplicitTemplateArgs()) {
11633 DeclAccessPair dap;
11634 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11635 OvlExpr, false, &dap)) {
11636 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11637 if (!Method->isStatic()) {
11638 // If the target type is a non-function type and the function found
11639 // is a non-static member function, pretend as if that was the
11640 // target, it's the only possible type to end up with.
11641 TargetTypeIsNonStaticMemberFunction = true;
11642
11643 // And skip adding the function if its not in the proper form.
11644 // We'll diagnose this due to an empty set of functions.
11645 if (!OvlExprInfo.HasFormOfMemberPointer)
11646 return;
11647 }
11648
11649 Matches.push_back(std::make_pair(dap, Fn));
11650 }
11651 return;
11652 }
11653
11654 if (OvlExpr->hasExplicitTemplateArgs())
11655 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11656
11657 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11658 // C++ [over.over]p4:
11659 // If more than one function is selected, [...]
11660 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11661 if (FoundNonTemplateFunction)
11662 EliminateAllTemplateMatches();
11663 else
11664 EliminateAllExceptMostSpecializedTemplate();
11665 }
11666 }
11667
11668 if (S.getLangOpts().CUDA && Matches.size() > 1)
11669 EliminateSuboptimalCudaMatches();
11670 }
11671
11672 bool hasComplained() const { return HasComplained; }
11673
11674private:
11675 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11676 QualType Discard;
11677 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11678 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11679 }
11680
11681 /// \return true if A is considered a better overload candidate for the
11682 /// desired type than B.
11683 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11684 // If A doesn't have exactly the correct type, we don't want to classify it
11685 // as "better" than anything else. This way, the user is required to
11686 // disambiguate for us if there are multiple candidates and no exact match.
11687 return candidateHasExactlyCorrectType(A) &&
11688 (!candidateHasExactlyCorrectType(B) ||
11689 compareEnableIfAttrs(S, A, B) == Comparison::Better);
11690 }
11691
11692 /// \return true if we were able to eliminate all but one overload candidate,
11693 /// false otherwise.
11694 bool eliminiateSuboptimalOverloadCandidates() {
11695 // Same algorithm as overload resolution -- one pass to pick the "best",
11696 // another pass to be sure that nothing is better than the best.
11697 auto Best = Matches.begin();
11698 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11699 if (isBetterCandidate(I->second, Best->second))
11700 Best = I;
11701
11702 const FunctionDecl *BestFn = Best->second;
11703 auto IsBestOrInferiorToBest = [this, BestFn](
11704 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11705 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11706 };
11707
11708 // Note: We explicitly leave Matches unmodified if there isn't a clear best
11709 // option, so we can potentially give the user a better error
11710 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11711 return false;
11712 Matches[0] = *Best;
11713 Matches.resize(1);
11714 return true;
11715 }
11716
11717 bool isTargetTypeAFunction() const {
11718 return TargetFunctionType->isFunctionType();
11719 }
11720
11721 // [ToType] [Return]
11722
11723 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11724 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11725 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11726 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11727 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11728 }
11729
11730 // return true if any matching specializations were found
11731 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11732 const DeclAccessPair& CurAccessFunPair) {
11733 if (CXXMethodDecl *Method
11734 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11735 // Skip non-static function templates when converting to pointer, and
11736 // static when converting to member pointer.
11737 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11738 return false;
11739 }
11740 else if (TargetTypeIsNonStaticMemberFunction)
11741 return false;
11742
11743 // C++ [over.over]p2:
11744 // If the name is a function template, template argument deduction is
11745 // done (14.8.2.2), and if the argument deduction succeeds, the
11746 // resulting template argument list is used to generate a single
11747 // function template specialization, which is added to the set of
11748 // overloaded functions considered.
11749 FunctionDecl *Specialization = nullptr;
11750 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11751 if (Sema::TemplateDeductionResult Result
11752 = S.DeduceTemplateArguments(FunctionTemplate,
11753 &OvlExplicitTemplateArgs,
11754 TargetFunctionType, Specialization,
11755 Info, /*IsAddressOfFunction*/true)) {
11756 // Make a note of the failed deduction for diagnostics.
11757 FailedCandidates.addCandidate()
11758 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11759 MakeDeductionFailureInfo(Context, Result, Info));
11760 return false;
11761 }
11762
11763 // Template argument deduction ensures that we have an exact match or
11764 // compatible pointer-to-function arguments that would be adjusted by ICS.
11765 // This function template specicalization works.
11766 assert(S.isSameOrCompatibleFunctionType(((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11768, __PRETTY_FUNCTION__))
11767 Context.getCanonicalType(Specialization->getType()),((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11768, __PRETTY_FUNCTION__))
11768 Context.getCanonicalType(TargetFunctionType)))((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11768, __PRETTY_FUNCTION__))
;
11769
11770 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11771 return false;
11772
11773 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11774 return true;
11775 }
11776
11777 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11778 const DeclAccessPair& CurAccessFunPair) {
11779 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11780 // Skip non-static functions when converting to pointer, and static
11781 // when converting to member pointer.
11782 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11783 return false;
11784 }
11785 else if (TargetTypeIsNonStaticMemberFunction)
11786 return false;
11787
11788 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11789 if (S.getLangOpts().CUDA)
11790 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11791 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11792 return false;
11793 if (FunDecl->isMultiVersion()) {
11794 const auto *TA = FunDecl->getAttr<TargetAttr>();
11795 if (TA && !TA->isDefaultVersion())
11796 return false;
11797 }
11798
11799 // If any candidate has a placeholder return type, trigger its deduction
11800 // now.
11801 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11802 Complain)) {
11803 HasComplained |= Complain;
11804 return false;
11805 }
11806
11807 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11808 return false;
11809
11810 // If we're in C, we need to support types that aren't exactly identical.
11811 if (!S.getLangOpts().CPlusPlus ||
11812 candidateHasExactlyCorrectType(FunDecl)) {
11813 Matches.push_back(std::make_pair(
11814 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11815 FoundNonTemplateFunction = true;
11816 return true;
11817 }
11818 }
11819
11820 return false;
11821 }
11822
11823 bool FindAllFunctionsThatMatchTargetTypeExactly() {
11824 bool Ret = false;
11825
11826 // If the overload expression doesn't have the form of a pointer to
11827 // member, don't try to convert it to a pointer-to-member type.
11828 if (IsInvalidFormOfPointerToMemberFunction())
11829 return false;
11830
11831 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11832 E = OvlExpr->decls_end();
11833 I != E; ++I) {
11834 // Look through any using declarations to find the underlying function.
11835 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11836
11837 // C++ [over.over]p3:
11838 // Non-member functions and static member functions match
11839 // targets of type "pointer-to-function" or "reference-to-function."
11840 // Nonstatic member functions match targets of
11841 // type "pointer-to-member-function."
11842 // Note that according to DR 247, the containing class does not matter.
11843 if (FunctionTemplateDecl *FunctionTemplate
11844 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11845 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11846 Ret = true;
11847 }
11848 // If we have explicit template arguments supplied, skip non-templates.
11849 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11850 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11851 Ret = true;
11852 }
11853 assert(Ret || Matches.empty())((Ret || Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Ret || Matches.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11853, __PRETTY_FUNCTION__))
;
11854 return Ret;
11855 }
11856
11857 void EliminateAllExceptMostSpecializedTemplate() {
11858 // [...] and any given function template specialization F1 is
11859 // eliminated if the set contains a second function template
11860 // specialization whose function template is more specialized
11861 // than the function template of F1 according to the partial
11862 // ordering rules of 14.5.5.2.
11863
11864 // The algorithm specified above is quadratic. We instead use a
11865 // two-pass algorithm (similar to the one used to identify the
11866 // best viable function in an overload set) that identifies the
11867 // best function template (if it exists).
11868
11869 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11870 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11871 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11872
11873 // TODO: It looks like FailedCandidates does not serve much purpose
11874 // here, since the no_viable diagnostic has index 0.
11875 UnresolvedSetIterator Result = S.getMostSpecialized(
11876 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11877 SourceExpr->getBeginLoc(), S.PDiag(),
11878 S.PDiag(diag::err_addr_ovl_ambiguous)
11879 << Matches[0].second->getDeclName(),
11880 S.PDiag(diag::note_ovl_candidate)
11881 << (unsigned)oc_function << (unsigned)ocs_described_template,
11882 Complain, TargetFunctionType);
11883
11884 if (Result != MatchesCopy.end()) {
11885 // Make it the first and only element
11886 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11887 Matches[0].second = cast<FunctionDecl>(*Result);
11888 Matches.resize(1);
11889 } else
11890 HasComplained |= Complain;
11891 }
11892
11893 void EliminateAllTemplateMatches() {
11894 // [...] any function template specializations in the set are
11895 // eliminated if the set also contains a non-template function, [...]
11896 for (unsigned I = 0, N = Matches.size(); I != N; ) {
11897 if (Matches[I].second->getPrimaryTemplate() == nullptr)
11898 ++I;
11899 else {
11900 Matches[I] = Matches[--N];
11901 Matches.resize(N);
11902 }
11903 }
11904 }
11905
11906 void EliminateSuboptimalCudaMatches() {
11907 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11908 }
11909
11910public:
11911 void ComplainNoMatchesFound() const {
11912 assert(Matches.empty())((Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Matches.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11912, __PRETTY_FUNCTION__))
;
11913 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11914 << OvlExpr->getName() << TargetFunctionType
11915 << OvlExpr->getSourceRange();
11916 if (FailedCandidates.empty())
11917 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11918 /*TakingAddress=*/true);
11919 else {
11920 // We have some deduction failure messages. Use them to diagnose
11921 // the function templates, and diagnose the non-template candidates
11922 // normally.
11923 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11924 IEnd = OvlExpr->decls_end();
11925 I != IEnd; ++I)
11926 if (FunctionDecl *Fun =
11927 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11928 if (!functionHasPassObjectSizeParams(Fun))
11929 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11930 /*TakingAddress=*/true);
11931 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11932 }
11933 }
11934
11935 bool IsInvalidFormOfPointerToMemberFunction() const {
11936 return TargetTypeIsNonStaticMemberFunction &&
11937 !OvlExprInfo.HasFormOfMemberPointer;
11938 }
11939
11940 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11941 // TODO: Should we condition this on whether any functions might
11942 // have matched, or is it more appropriate to do that in callers?
11943 // TODO: a fixit wouldn't hurt.
11944 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11945 << TargetType << OvlExpr->getSourceRange();
11946 }
11947
11948 bool IsStaticMemberFunctionFromBoundPointer() const {
11949 return StaticMemberFunctionFromBoundPointer;
11950 }
11951
11952 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11953 S.Diag(OvlExpr->getBeginLoc(),
11954 diag::err_invalid_form_pointer_member_function)
11955 << OvlExpr->getSourceRange();
11956 }
11957
11958 void ComplainOfInvalidConversion() const {
11959 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11960 << OvlExpr->getName() << TargetType;
11961 }
11962
11963 void ComplainMultipleMatchesFound() const {
11964 assert(Matches.size() > 1)((Matches.size() > 1) ? static_cast<void> (0) : __assert_fail
("Matches.size() > 1", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 11964, __PRETTY_FUNCTION__))
;
11965 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11966 << OvlExpr->getName() << OvlExpr->getSourceRange();
11967 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11968 /*TakingAddress=*/true);
11969 }
11970
11971 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11972
11973 int getNumMatches() const { return Matches.size(); }
11974
11975 FunctionDecl* getMatchingFunctionDecl() const {
11976 if (Matches.size() != 1) return nullptr;
11977 return Matches[0].second;
11978 }
11979
11980 const DeclAccessPair* getMatchingFunctionAccessPair() const {
11981 if (Matches.size() != 1) return nullptr;
11982 return &Matches[0].first;
11983 }
11984};
11985}
11986
11987/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11988/// an overloaded function (C++ [over.over]), where @p From is an
11989/// expression with overloaded function type and @p ToType is the type
11990/// we're trying to resolve to. For example:
11991///
11992/// @code
11993/// int f(double);
11994/// int f(int);
11995///
11996/// int (*pfd)(double) = f; // selects f(double)
11997/// @endcode
11998///
11999/// This routine returns the resulting FunctionDecl if it could be
12000/// resolved, and NULL otherwise. When @p Complain is true, this
12001/// routine will emit diagnostics if there is an error.
12002FunctionDecl *
12003Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12004 QualType TargetType,
12005 bool Complain,
12006 DeclAccessPair &FoundResult,
12007 bool *pHadMultipleCandidates) {
12008 assert(AddressOfExpr->getType() == Context.OverloadTy)((AddressOfExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12008, __PRETTY_FUNCTION__))
;
12009
12010 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12011 Complain);
12012 int NumMatches = Resolver.getNumMatches();
12013 FunctionDecl *Fn = nullptr;
12014 bool ShouldComplain = Complain && !Resolver.hasComplained();
12015 if (NumMatches == 0 && ShouldComplain) {
12016 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12017 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12018 else
12019 Resolver.ComplainNoMatchesFound();
12020 }
12021 else if (NumMatches > 1 && ShouldComplain)
12022 Resolver.ComplainMultipleMatchesFound();
12023 else if (NumMatches == 1) {
12024 Fn = Resolver.getMatchingFunctionDecl();
12025 assert(Fn)((Fn) ? static_cast<void> (0) : __assert_fail ("Fn", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12025, __PRETTY_FUNCTION__))
;
12026 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12027 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12028 FoundResult = *Resolver.getMatchingFunctionAccessPair();
12029 if (Complain) {
12030 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12031 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12032 else
12033 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12034 }
12035 }
12036
12037 if (pHadMultipleCandidates)
12038 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12039 return Fn;
12040}
12041
12042/// Given an expression that refers to an overloaded function, try to
12043/// resolve that function to a single function that can have its address taken.
12044/// This will modify `Pair` iff it returns non-null.
12045///
12046/// This routine can only succeed if from all of the candidates in the overload
12047/// set for SrcExpr that can have their addresses taken, there is one candidate
12048/// that is more constrained than the rest.
12049FunctionDecl *
12050Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12051 OverloadExpr::FindResult R = OverloadExpr::find(E);
12052 OverloadExpr *Ovl = R.Expression;
12053 bool IsResultAmbiguous = false;
12054 FunctionDecl *Result = nullptr;
12055 DeclAccessPair DAP;
12056 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12057
12058 auto CheckMoreConstrained =
12059 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12060 SmallVector<const Expr *, 1> AC1, AC2;
12061 FD1->getAssociatedConstraints(AC1);
12062 FD2->getAssociatedConstraints(AC2);
12063 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12064 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12065 return None;
12066 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12067 return None;
12068 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12069 return None;
12070 return AtLeastAsConstrained1;
12071 };
12072
12073 // Don't use the AddressOfResolver because we're specifically looking for
12074 // cases where we have one overload candidate that lacks
12075 // enable_if/pass_object_size/...
12076 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12077 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12078 if (!FD)
12079 return nullptr;
12080
12081 if (!checkAddressOfFunctionIsAvailable(FD))
12082 continue;
12083
12084 // We have more than one result - see if it is more constrained than the
12085 // previous one.
12086 if (Result) {
12087 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12088 Result);
12089 if (!MoreConstrainedThanPrevious) {
12090 IsResultAmbiguous = true;
12091 AmbiguousDecls.push_back(FD);
12092 continue;
12093 }
12094 if (!*MoreConstrainedThanPrevious)
12095 continue;
12096 // FD is more constrained - replace Result with it.
12097 }
12098 IsResultAmbiguous = false;
12099 DAP = I.getPair();
12100 Result = FD;
12101 }
12102
12103 if (IsResultAmbiguous)
12104 return nullptr;
12105
12106 if (Result) {
12107 SmallVector<const Expr *, 1> ResultAC;
12108 // We skipped over some ambiguous declarations which might be ambiguous with
12109 // the selected result.
12110 for (FunctionDecl *Skipped : AmbiguousDecls)
12111 if (!CheckMoreConstrained(Skipped, Result).hasValue())
12112 return nullptr;
12113 Pair = DAP;
12114 }
12115 return Result;
12116}
12117
12118/// Given an overloaded function, tries to turn it into a non-overloaded
12119/// function reference using resolveAddressOfSingleOverloadCandidate. This
12120/// will perform access checks, diagnose the use of the resultant decl, and, if
12121/// requested, potentially perform a function-to-pointer decay.
12122///
12123/// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12124/// Otherwise, returns true. This may emit diagnostics and return true.
12125bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12126 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12127 Expr *E = SrcExpr.get();
12128 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")((E->getType() == Context.OverloadTy && "SrcExpr must be an overload"
) ? static_cast<void> (0) : __assert_fail ("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12128, __PRETTY_FUNCTION__))
;
12129
12130 DeclAccessPair DAP;
12131 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12132 if (!Found || Found->isCPUDispatchMultiVersion() ||
12133 Found->isCPUSpecificMultiVersion())
12134 return false;
12135
12136 // Emitting multiple diagnostics for a function that is both inaccessible and
12137 // unavailable is consistent with our behavior elsewhere. So, always check
12138 // for both.
12139 DiagnoseUseOfDecl(Found, E->getExprLoc());
12140 CheckAddressOfMemberAccess(E, DAP);
12141 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12142 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12143 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12144 else
12145 SrcExpr = Fixed;
12146 return true;
12147}
12148
12149/// Given an expression that refers to an overloaded function, try to
12150/// resolve that overloaded function expression down to a single function.
12151///
12152/// This routine can only resolve template-ids that refer to a single function
12153/// template, where that template-id refers to a single template whose template
12154/// arguments are either provided by the template-id or have defaults,
12155/// as described in C++0x [temp.arg.explicit]p3.
12156///
12157/// If no template-ids are found, no diagnostics are emitted and NULL is
12158/// returned.
12159FunctionDecl *
12160Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12161 bool Complain,
12162 DeclAccessPair *FoundResult) {
12163 // C++ [over.over]p1:
12164 // [...] [Note: any redundant set of parentheses surrounding the
12165 // overloaded function name is ignored (5.1). ]
12166 // C++ [over.over]p1:
12167 // [...] The overloaded function name can be preceded by the &
12168 // operator.
12169
12170 // If we didn't actually find any template-ids, we're done.
12171 if (!ovl->hasExplicitTemplateArgs())
12172 return nullptr;
12173
12174 TemplateArgumentListInfo ExplicitTemplateArgs;
12175 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12176 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12177
12178 // Look through all of the overloaded functions, searching for one
12179 // whose type matches exactly.
12180 FunctionDecl *Matched = nullptr;
12181 for (UnresolvedSetIterator I = ovl->decls_begin(),
12182 E = ovl->decls_end(); I != E; ++I) {
12183 // C++0x [temp.arg.explicit]p3:
12184 // [...] In contexts where deduction is done and fails, or in contexts
12185 // where deduction is not done, if a template argument list is
12186 // specified and it, along with any default template arguments,
12187 // identifies a single function template specialization, then the
12188 // template-id is an lvalue for the function template specialization.
12189 FunctionTemplateDecl *FunctionTemplate
12190 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12191
12192 // C++ [over.over]p2:
12193 // If the name is a function template, template argument deduction is
12194 // done (14.8.2.2), and if the argument deduction succeeds, the
12195 // resulting template argument list is used to generate a single
12196 // function template specialization, which is added to the set of
12197 // overloaded functions considered.
12198 FunctionDecl *Specialization = nullptr;
12199 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12200 if (TemplateDeductionResult Result
12201 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12202 Specialization, Info,
12203 /*IsAddressOfFunction*/true)) {
12204 // Make a note of the failed deduction for diagnostics.
12205 // TODO: Actually use the failed-deduction info?
12206 FailedCandidates.addCandidate()
12207 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12208 MakeDeductionFailureInfo(Context, Result, Info));
12209 continue;
12210 }
12211
12212 assert(Specialization && "no specialization and no error?")((Specialization && "no specialization and no error?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"no specialization and no error?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12212, __PRETTY_FUNCTION__))
;
12213
12214 // Multiple matches; we can't resolve to a single declaration.
12215 if (Matched) {
12216 if (Complain) {
12217 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12218 << ovl->getName();
12219 NoteAllOverloadCandidates(ovl);
12220 }
12221 return nullptr;
12222 }
12223
12224 Matched = Specialization;
12225 if (FoundResult) *FoundResult = I.getPair();
12226 }
12227
12228 if (Matched &&
12229 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12230 return nullptr;
12231
12232 return Matched;
12233}
12234
12235// Resolve and fix an overloaded expression that can be resolved
12236// because it identifies a single function template specialization.
12237//
12238// Last three arguments should only be supplied if Complain = true
12239//
12240// Return true if it was logically possible to so resolve the
12241// expression, regardless of whether or not it succeeded. Always
12242// returns true if 'complain' is set.
12243bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12244 ExprResult &SrcExpr, bool doFunctionPointerConverion,
12245 bool complain, SourceRange OpRangeForComplaining,
12246 QualType DestTypeForComplaining,
12247 unsigned DiagIDForComplaining) {
12248 assert(SrcExpr.get()->getType() == Context.OverloadTy)((SrcExpr.get()->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12248, __PRETTY_FUNCTION__))
;
12249
12250 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12251
12252 DeclAccessPair found;
12253 ExprResult SingleFunctionExpression;
12254 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12255 ovl.Expression, /*complain*/ false, &found)) {
12256 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12257 SrcExpr = ExprError();
12258 return true;
12259 }
12260
12261 // It is only correct to resolve to an instance method if we're
12262 // resolving a form that's permitted to be a pointer to member.
12263 // Otherwise we'll end up making a bound member expression, which
12264 // is illegal in all the contexts we resolve like this.
12265 if (!ovl.HasFormOfMemberPointer &&
12266 isa<CXXMethodDecl>(fn) &&
12267 cast<CXXMethodDecl>(fn)->isInstance()) {
12268 if (!complain) return false;
12269
12270 Diag(ovl.Expression->getExprLoc(),
12271 diag::err_bound_member_function)
12272 << 0 << ovl.Expression->getSourceRange();
12273
12274 // TODO: I believe we only end up here if there's a mix of
12275 // static and non-static candidates (otherwise the expression
12276 // would have 'bound member' type, not 'overload' type).
12277 // Ideally we would note which candidate was chosen and why
12278 // the static candidates were rejected.
12279 SrcExpr = ExprError();
12280 return true;
12281 }
12282
12283 // Fix the expression to refer to 'fn'.
12284 SingleFunctionExpression =
12285 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12286
12287 // If desired, do function-to-pointer decay.
12288 if (doFunctionPointerConverion) {
12289 SingleFunctionExpression =
12290 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12291 if (SingleFunctionExpression.isInvalid()) {
12292 SrcExpr = ExprError();
12293 return true;
12294 }
12295 }
12296 }
12297
12298 if (!SingleFunctionExpression.isUsable()) {
12299 if (complain) {
12300 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12301 << ovl.Expression->getName()
12302 << DestTypeForComplaining
12303 << OpRangeForComplaining
12304 << ovl.Expression->getQualifierLoc().getSourceRange();
12305 NoteAllOverloadCandidates(SrcExpr.get());
12306
12307 SrcExpr = ExprError();
12308 return true;
12309 }
12310
12311 return false;
12312 }
12313
12314 SrcExpr = SingleFunctionExpression;
12315 return true;
12316}
12317
12318/// Add a single candidate to the overload set.
12319static void AddOverloadedCallCandidate(Sema &S,
12320 DeclAccessPair FoundDecl,
12321 TemplateArgumentListInfo *ExplicitTemplateArgs,
12322 ArrayRef<Expr *> Args,
12323 OverloadCandidateSet &CandidateSet,
12324 bool PartialOverloading,
12325 bool KnownValid) {
12326 NamedDecl *Callee = FoundDecl.getDecl();
12327 if (isa<UsingShadowDecl>(Callee))
12328 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12329
12330 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12331 if (ExplicitTemplateArgs) {
12332 assert(!KnownValid && "Explicit template arguments?")((!KnownValid && "Explicit template arguments?") ? static_cast
<void> (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12332, __PRETTY_FUNCTION__))
;
12333 return;
12334 }
12335 // Prevent ill-formed function decls to be added as overload candidates.
12336 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12337 return;
12338
12339 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12340 /*SuppressUserConversions=*/false,
12341 PartialOverloading);
12342 return;
12343 }
12344
12345 if (FunctionTemplateDecl *FuncTemplate
12346 = dyn_cast<FunctionTemplateDecl>(Callee)) {
12347 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12348 ExplicitTemplateArgs, Args, CandidateSet,
12349 /*SuppressUserConversions=*/false,
12350 PartialOverloading);
12351 return;
12352 }
12353
12354 assert(!KnownValid && "unhandled case in overloaded call candidate")((!KnownValid && "unhandled case in overloaded call candidate"
) ? static_cast<void> (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12354, __PRETTY_FUNCTION__))
;
12355}
12356
12357/// Add the overload candidates named by callee and/or found by argument
12358/// dependent lookup to the given overload set.
12359void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12360 ArrayRef<Expr *> Args,
12361 OverloadCandidateSet &CandidateSet,
12362 bool PartialOverloading) {
12363
12364#ifndef NDEBUG
12365 // Verify that ArgumentDependentLookup is consistent with the rules
12366 // in C++0x [basic.lookup.argdep]p3:
12367 //
12368 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12369 // and let Y be the lookup set produced by argument dependent
12370 // lookup (defined as follows). If X contains
12371 //
12372 // -- a declaration of a class member, or
12373 //
12374 // -- a block-scope function declaration that is not a
12375 // using-declaration, or
12376 //
12377 // -- a declaration that is neither a function or a function
12378 // template
12379 //
12380 // then Y is empty.
12381
12382 if (ULE->requiresADL()) {
12383 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12384 E = ULE->decls_end(); I != E; ++I) {
12385 assert(!(*I)->getDeclContext()->isRecord())((!(*I)->getDeclContext()->isRecord()) ? static_cast<
void> (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12385, __PRETTY_FUNCTION__))
;
12386 assert(isa<UsingShadowDecl>(*I) ||((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12387, __PRETTY_FUNCTION__))
12387 !(*I)->getDeclContext()->isFunctionOrMethod())((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12387, __PRETTY_FUNCTION__))
;
12388 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? static_cast<void> (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12388, __PRETTY_FUNCTION__))
;
12389 }
12390 }
12391#endif
12392
12393 // It would be nice to avoid this copy.
12394 TemplateArgumentListInfo TABuffer;
12395 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12396 if (ULE->hasExplicitTemplateArgs()) {
12397 ULE->copyTemplateArgumentsInto(TABuffer);
12398 ExplicitTemplateArgs = &TABuffer;
12399 }
12400
12401 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12402 E = ULE->decls_end(); I != E; ++I)
12403 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12404 CandidateSet, PartialOverloading,
12405 /*KnownValid*/ true);
12406
12407 if (ULE->requiresADL())
12408 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12409 Args, ExplicitTemplateArgs,
12410 CandidateSet, PartialOverloading);
12411}
12412
12413/// Determine whether a declaration with the specified name could be moved into
12414/// a different namespace.
12415static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12416 switch (Name.getCXXOverloadedOperator()) {
12417 case OO_New: case OO_Array_New:
12418 case OO_Delete: case OO_Array_Delete:
12419 return false;
12420
12421 default:
12422 return true;
12423 }
12424}
12425
12426/// Attempt to recover from an ill-formed use of a non-dependent name in a
12427/// template, where the non-dependent name was declared after the template
12428/// was defined. This is common in code written for a compilers which do not
12429/// correctly implement two-stage name lookup.
12430///
12431/// Returns true if a viable candidate was found and a diagnostic was issued.
12432static bool
12433DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12434 const CXXScopeSpec &SS, LookupResult &R,
12435 OverloadCandidateSet::CandidateSetKind CSK,
12436 TemplateArgumentListInfo *ExplicitTemplateArgs,
12437 ArrayRef<Expr *> Args,
12438 bool *DoDiagnoseEmptyLookup = nullptr) {
12439 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12440 return false;
12441
12442 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12443 if (DC->isTransparentContext())
12444 continue;
12445
12446 SemaRef.LookupQualifiedName(R, DC);
12447
12448 if (!R.empty()) {
12449 R.suppressDiagnostics();
12450
12451 if (isa<CXXRecordDecl>(DC)) {
12452 // Don't diagnose names we find in classes; we get much better
12453 // diagnostics for these from DiagnoseEmptyLookup.
12454 R.clear();
12455 if (DoDiagnoseEmptyLookup)
12456 *DoDiagnoseEmptyLookup = true;
12457 return false;
12458 }
12459
12460 OverloadCandidateSet Candidates(FnLoc, CSK);
12461 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12462 AddOverloadedCallCandidate(SemaRef, I.getPair(),
12463 ExplicitTemplateArgs, Args,
12464 Candidates, false, /*KnownValid*/ false);
12465
12466 OverloadCandidateSet::iterator Best;
12467 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12468 // No viable functions. Don't bother the user with notes for functions
12469 // which don't work and shouldn't be found anyway.
12470 R.clear();
12471 return false;
12472 }
12473
12474 // Find the namespaces where ADL would have looked, and suggest
12475 // declaring the function there instead.
12476 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12477 Sema::AssociatedClassSet AssociatedClasses;
12478 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12479 AssociatedNamespaces,
12480 AssociatedClasses);
12481 Sema::AssociatedNamespaceSet SuggestedNamespaces;
12482 if (canBeDeclaredInNamespace(R.getLookupName())) {
12483 DeclContext *Std = SemaRef.getStdNamespace();
12484 for (Sema::AssociatedNamespaceSet::iterator
12485 it = AssociatedNamespaces.begin(),
12486 end = AssociatedNamespaces.end(); it != end; ++it) {
12487 // Never suggest declaring a function within namespace 'std'.
12488 if (Std && Std->Encloses(*it))
12489 continue;
12490
12491 // Never suggest declaring a function within a namespace with a
12492 // reserved name, like __gnu_cxx.
12493 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12494 if (NS &&
12495 NS->getQualifiedNameAsString().find("__") != std::string::npos)
12496 continue;
12497
12498 SuggestedNamespaces.insert(*it);
12499 }
12500 }
12501
12502 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12503 << R.getLookupName();
12504 if (SuggestedNamespaces.empty()) {
12505 SemaRef.Diag(Best->Function->getLocation(),
12506 diag::note_not_found_by_two_phase_lookup)
12507 << R.getLookupName() << 0;
12508 } else if (SuggestedNamespaces.size() == 1) {
12509 SemaRef.Diag(Best->Function->getLocation(),
12510 diag::note_not_found_by_two_phase_lookup)
12511 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12512 } else {
12513 // FIXME: It would be useful to list the associated namespaces here,
12514 // but the diagnostics infrastructure doesn't provide a way to produce
12515 // a localized representation of a list of items.
12516 SemaRef.Diag(Best->Function->getLocation(),
12517 diag::note_not_found_by_two_phase_lookup)
12518 << R.getLookupName() << 2;
12519 }
12520
12521 // Try to recover by calling this function.
12522 return true;
12523 }
12524
12525 R.clear();
12526 }
12527
12528 return false;
12529}
12530
12531/// Attempt to recover from ill-formed use of a non-dependent operator in a
12532/// template, where the non-dependent operator was declared after the template
12533/// was defined.
12534///
12535/// Returns true if a viable candidate was found and a diagnostic was issued.
12536static bool
12537DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12538 SourceLocation OpLoc,
12539 ArrayRef<Expr *> Args) {
12540 DeclarationName OpName =
12541 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12542 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12543 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12544 OverloadCandidateSet::CSK_Operator,
12545 /*ExplicitTemplateArgs=*/nullptr, Args);
12546}
12547
12548namespace {
12549class BuildRecoveryCallExprRAII {
12550 Sema &SemaRef;
12551public:
12552 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12553 assert(SemaRef.IsBuildingRecoveryCallExpr == false)((SemaRef.IsBuildingRecoveryCallExpr == false) ? static_cast<
void> (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12553, __PRETTY_FUNCTION__))
;
12554 SemaRef.IsBuildingRecoveryCallExpr = true;
12555 }
12556
12557 ~BuildRecoveryCallExprRAII() {
12558 SemaRef.IsBuildingRecoveryCallExpr = false;
12559 }
12560};
12561
12562}
12563
12564/// Attempts to recover from a call where no functions were found.
12565///
12566/// Returns true if new candidates were found.
12567static ExprResult
12568BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12569 UnresolvedLookupExpr *ULE,
12570 SourceLocation LParenLoc,
12571 MutableArrayRef<Expr *> Args,
12572 SourceLocation RParenLoc,
12573 bool EmptyLookup, bool AllowTypoCorrection) {
12574 // Do not try to recover if it is already building a recovery call.
12575 // This stops infinite loops for template instantiations like
12576 //
12577 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12578 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12579 //
12580 if (SemaRef.IsBuildingRecoveryCallExpr)
12581 return ExprError();
12582 BuildRecoveryCallExprRAII RCE(SemaRef);
12583
12584 CXXScopeSpec SS;
12585 SS.Adopt(ULE->getQualifierLoc());
12586 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12587
12588 TemplateArgumentListInfo TABuffer;
12589 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12590 if (ULE->hasExplicitTemplateArgs()) {
12591 ULE->copyTemplateArgumentsInto(TABuffer);
12592 ExplicitTemplateArgs = &TABuffer;
12593 }
12594
12595 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12596 Sema::LookupOrdinaryName);
12597 bool DoDiagnoseEmptyLookup = EmptyLookup;
12598 if (!DiagnoseTwoPhaseLookup(
12599 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12600 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12601 NoTypoCorrectionCCC NoTypoValidator{};
12602 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12603 ExplicitTemplateArgs != nullptr,
12604 dyn_cast<MemberExpr>(Fn));
12605 CorrectionCandidateCallback &Validator =
12606 AllowTypoCorrection
12607 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12608 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12609 if (!DoDiagnoseEmptyLookup ||
12610 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12611 Args))
12612 return ExprError();
12613 }
12614
12615 assert(!R.empty() && "lookup results empty despite recovery")((!R.empty() && "lookup results empty despite recovery"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12615, __PRETTY_FUNCTION__))
;
12616
12617 // If recovery created an ambiguity, just bail out.
12618 if (R.isAmbiguous()) {
12619 R.suppressDiagnostics();
12620 return ExprError();
12621 }
12622
12623 // Build an implicit member call if appropriate. Just drop the
12624 // casts and such from the call, we don't really care.
12625 ExprResult NewFn = ExprError();
12626 if ((*R.begin())->isCXXClassMember())
12627 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12628 ExplicitTemplateArgs, S);
12629 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12630 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12631 ExplicitTemplateArgs);
12632 else
12633 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12634
12635 if (NewFn.isInvalid())
12636 return ExprError();
12637
12638 // This shouldn't cause an infinite loop because we're giving it
12639 // an expression with viable lookup results, which should never
12640 // end up here.
12641 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12642 MultiExprArg(Args.data(), Args.size()),
12643 RParenLoc);
12644}
12645
12646/// Constructs and populates an OverloadedCandidateSet from
12647/// the given function.
12648/// \returns true when an the ExprResult output parameter has been set.
12649bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12650 UnresolvedLookupExpr *ULE,
12651 MultiExprArg Args,
12652 SourceLocation RParenLoc,
12653 OverloadCandidateSet *CandidateSet,
12654 ExprResult *Result) {
12655#ifndef NDEBUG
12656 if (ULE->requiresADL()) {
12657 // To do ADL, we must have found an unqualified name.
12658 assert(!ULE->getQualifier() && "qualified name with ADL")((!ULE->getQualifier() && "qualified name with ADL"
) ? static_cast<void> (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12658, __PRETTY_FUNCTION__))
;
12659
12660 // We don't perform ADL for implicit declarations of builtins.
12661 // Verify that this was correctly set up.
12662 FunctionDecl *F;
12663 if (ULE->decls_begin() != ULE->decls_end() &&
12664 ULE->decls_begin() + 1 == ULE->decls_end() &&
12665 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12666 F->getBuiltinID() && F->isImplicit())
12667 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12667)
;
12668
12669 // We don't perform ADL in C.
12670 assert(getLangOpts().CPlusPlus && "ADL enabled in C")((getLangOpts().CPlusPlus && "ADL enabled in C") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12670, __PRETTY_FUNCTION__))
;
12671 }
12672#endif
12673
12674 UnbridgedCastsSet UnbridgedCasts;
12675 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12676 *Result = ExprError();
12677 return true;
12678 }
12679
12680 // Add the functions denoted by the callee to the set of candidate
12681 // functions, including those from argument-dependent lookup.
12682 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12683
12684 if (getLangOpts().MSVCCompat &&
12685 CurContext->isDependentContext() && !isSFINAEContext() &&
12686 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12687
12688 OverloadCandidateSet::iterator Best;
12689 if (CandidateSet->empty() ||
12690 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12691 OR_No_Viable_Function) {
12692 // In Microsoft mode, if we are inside a template class member function
12693 // then create a type dependent CallExpr. The goal is to postpone name
12694 // lookup to instantiation time to be able to search into type dependent
12695 // base classes.
12696 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12697 VK_RValue, RParenLoc);
12698 CE->setTypeDependent(true);
12699 CE->setValueDependent(true);
12700 CE->setInstantiationDependent(true);
12701 *Result = CE;
12702 return true;
12703 }
12704 }
12705
12706 if (CandidateSet->empty())
12707 return false;
12708
12709 UnbridgedCasts.restore();
12710 return false;
12711}
12712
12713/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12714/// the completed call expression. If overload resolution fails, emits
12715/// diagnostics and returns ExprError()
12716static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12717 UnresolvedLookupExpr *ULE,
12718 SourceLocation LParenLoc,
12719 MultiExprArg Args,
12720 SourceLocation RParenLoc,
12721 Expr *ExecConfig,
12722 OverloadCandidateSet *CandidateSet,
12723 OverloadCandidateSet::iterator *Best,
12724 OverloadingResult OverloadResult,
12725 bool AllowTypoCorrection) {
12726 if (CandidateSet->empty())
12727 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12728 RParenLoc, /*EmptyLookup=*/true,
12729 AllowTypoCorrection);
12730
12731 switch (OverloadResult) {
12732 case OR_Success: {
12733 FunctionDecl *FDecl = (*Best)->Function;
12734 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12735 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12736 return ExprError();
12737 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12738 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12739 ExecConfig, /*IsExecConfig=*/false,
12740 (*Best)->IsADLCandidate);
12741 }
12742
12743 case OR_No_Viable_Function: {
12744 // Try to recover by looking for viable functions which the user might
12745 // have meant to call.
12746 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12747 Args, RParenLoc,
12748 /*EmptyLookup=*/false,
12749 AllowTypoCorrection);
12750 if (!Recovery.isInvalid())
12751 return Recovery;
12752
12753 // If the user passes in a function that we can't take the address of, we
12754 // generally end up emitting really bad error messages. Here, we attempt to
12755 // emit better ones.
12756 for (const Expr *Arg : Args) {
12757 if (!Arg->getType()->isFunctionType())
12758 continue;
12759 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12760 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12761 if (FD &&
12762 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12763 Arg->getExprLoc()))
12764 return ExprError();
12765 }
12766 }
12767
12768 CandidateSet->NoteCandidates(
12769 PartialDiagnosticAt(
12770 Fn->getBeginLoc(),
12771 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12772 << ULE->getName() << Fn->getSourceRange()),
12773 SemaRef, OCD_AllCandidates, Args);
12774 break;
12775 }
12776
12777 case OR_Ambiguous:
12778 CandidateSet->NoteCandidates(
12779 PartialDiagnosticAt(Fn->getBeginLoc(),
12780 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12781 << ULE->getName() << Fn->getSourceRange()),
12782 SemaRef, OCD_AmbiguousCandidates, Args);
12783 break;
12784
12785 case OR_Deleted: {
12786 CandidateSet->NoteCandidates(
12787 PartialDiagnosticAt(Fn->getBeginLoc(),
12788 SemaRef.PDiag(diag::err_ovl_deleted_call)
12789 << ULE->getName() << Fn->getSourceRange()),
12790 SemaRef, OCD_AllCandidates, Args);
12791
12792 // We emitted an error for the unavailable/deleted function call but keep
12793 // the call in the AST.
12794 FunctionDecl *FDecl = (*Best)->Function;
12795 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12796 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12797 ExecConfig, /*IsExecConfig=*/false,
12798 (*Best)->IsADLCandidate);
12799 }
12800 }
12801
12802 // Overload resolution failed.
12803 return ExprError();
12804}
12805
12806static void markUnaddressableCandidatesUnviable(Sema &S,
12807 OverloadCandidateSet &CS) {
12808 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12809 if (I->Viable &&
12810 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12811 I->Viable = false;
12812 I->FailureKind = ovl_fail_addr_not_available;
12813 }
12814 }
12815}
12816
12817/// BuildOverloadedCallExpr - Given the call expression that calls Fn
12818/// (which eventually refers to the declaration Func) and the call
12819/// arguments Args/NumArgs, attempt to resolve the function call down
12820/// to a specific function. If overload resolution succeeds, returns
12821/// the call expression produced by overload resolution.
12822/// Otherwise, emits diagnostics and returns ExprError.
12823ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12824 UnresolvedLookupExpr *ULE,
12825 SourceLocation LParenLoc,
12826 MultiExprArg Args,
12827 SourceLocation RParenLoc,
12828 Expr *ExecConfig,
12829 bool AllowTypoCorrection,
12830 bool CalleesAddressIsTaken) {
12831 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12832 OverloadCandidateSet::CSK_Normal);
12833 ExprResult result;
12834
12835 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12836 &result))
12837 return result;
12838
12839 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12840 // functions that aren't addressible are considered unviable.
12841 if (CalleesAddressIsTaken)
12842 markUnaddressableCandidatesUnviable(*this, CandidateSet);
12843
12844 OverloadCandidateSet::iterator Best;
12845 OverloadingResult OverloadResult =
12846 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12847
12848 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12849 ExecConfig, &CandidateSet, &Best,
12850 OverloadResult, AllowTypoCorrection);
12851}
12852
12853static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12854 return Functions.size() > 1 ||
12855 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12856}
12857
12858/// Create a unary operation that may resolve to an overloaded
12859/// operator.
12860///
12861/// \param OpLoc The location of the operator itself (e.g., '*').
12862///
12863/// \param Opc The UnaryOperatorKind that describes this operator.
12864///
12865/// \param Fns The set of non-member functions that will be
12866/// considered by overload resolution. The caller needs to build this
12867/// set based on the context using, e.g.,
12868/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12869/// set should not contain any member functions; those will be added
12870/// by CreateOverloadedUnaryOp().
12871///
12872/// \param Input The input argument.
12873ExprResult
12874Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12875 const UnresolvedSetImpl &Fns,
12876 Expr *Input, bool PerformADL) {
12877 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12878 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")((Op != OO_None && "Invalid opcode for overloaded unary operator"
) ? static_cast<void> (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 12878, __PRETTY_FUNCTION__))
;
12879 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12880 // TODO: provide better source location info.
12881 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12882
12883 if (checkPlaceholderForOverload(*this, Input))
12884 return ExprError();
12885
12886 Expr *Args[2] = { Input, nullptr };
12887 unsigned NumArgs = 1;
12888
12889 // For post-increment and post-decrement, add the implicit '0' as
12890 // the second argument, so that we know this is a post-increment or
12891 // post-decrement.
12892 if (Opc == UO_PostInc || Opc == UO_PostDec) {
12893 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12894 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12895 SourceLocation());
12896 NumArgs = 2;
12897 }
12898
12899 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12900
12901 if (Input->isTypeDependent()) {
12902 if (Fns.empty())
12903 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12904 VK_RValue, OK_Ordinary, OpLoc, false);
12905
12906 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12907 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12908 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12909 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12910 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12911 Context.DependentTy, VK_RValue, OpLoc,
12912 FPOptions());
12913 }
12914
12915 // Build an empty overload set.
12916 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12917
12918 // Add the candidates from the given function set.
12919 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12920
12921 // Add operator candidates that are member functions.
12922 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12923
12924 // Add candidates from ADL.
12925 if (PerformADL) {
12926 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12927 /*ExplicitTemplateArgs*/nullptr,
12928 CandidateSet);
12929 }
12930
12931 // Add builtin operator candidates.
12932 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12933
12934 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12935
12936 // Perform overload resolution.
12937 OverloadCandidateSet::iterator Best;
12938 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12939 case OR_Success: {
12940 // We found a built-in operator or an overloaded operator.
12941 FunctionDecl *FnDecl = Best->Function;
12942
12943 if (FnDecl) {
12944 Expr *Base = nullptr;
12945 // We matched an overloaded operator. Build a call to that
12946 // operator.
12947
12948 // Convert the arguments.
12949 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12950 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12951
12952 ExprResult InputRes =
12953 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12954 Best->FoundDecl, Method);
12955 if (InputRes.isInvalid())
12956 return ExprError();
12957 Base = Input = InputRes.get();
12958 } else {
12959 // Convert the arguments.
12960 ExprResult InputInit
12961 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12962 Context,
12963 FnDecl->getParamDecl(0)),
12964 SourceLocation(),
12965 Input);
12966 if (InputInit.isInvalid())
12967 return ExprError();
12968 Input = InputInit.get();
12969 }
12970
12971 // Build the actual expression node.
12972 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12973 Base, HadMultipleCandidates,
12974 OpLoc);
12975 if (FnExpr.isInvalid())
12976 return ExprError();
12977
12978 // Determine the result type.
12979 QualType ResultTy = FnDecl->getReturnType();
12980 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12981 ResultTy = ResultTy.getNonLValueExprType(Context);
12982
12983 Args[0] = Input;
12984 CallExpr *TheCall = CXXOperatorCallExpr::Create(
12985 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12986 FPOptions(), Best->IsADLCandidate);
12987
12988 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12989 return ExprError();
12990
12991 if (CheckFunctionCall(FnDecl, TheCall,
12992 FnDecl->getType()->castAs<FunctionProtoType>()))
12993 return ExprError();
12994
12995 return MaybeBindToTemporary(TheCall);
12996 } else {
12997 // We matched a built-in operator. Convert the arguments, then
12998 // break out so that we will build the appropriate built-in
12999 // operator node.
13000 ExprResult InputRes = PerformImplicitConversion(
13001 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13002 CCK_ForBuiltinOverloadedOp);
13003 if (InputRes.isInvalid())
13004 return ExprError();
13005 Input = InputRes.get();
13006 break;
13007 }
13008 }
13009
13010 case OR_No_Viable_Function:
13011 // This is an erroneous use of an operator which can be overloaded by
13012 // a non-member function. Check for non-member operators which were
13013 // defined too late to be candidates.
13014 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13015 // FIXME: Recover by calling the found function.
13016 return ExprError();
13017
13018 // No viable function; fall through to handling this as a
13019 // built-in operator, which will produce an error message for us.
13020 break;
13021
13022 case OR_Ambiguous:
13023 CandidateSet.NoteCandidates(
13024 PartialDiagnosticAt(OpLoc,
13025 PDiag(diag::err_ovl_ambiguous_oper_unary)
13026 << UnaryOperator::getOpcodeStr(Opc)
13027 << Input->getType() << Input->getSourceRange()),
13028 *this, OCD_AmbiguousCandidates, ArgsArray,
13029 UnaryOperator::getOpcodeStr(Opc), OpLoc);
13030 return ExprError();
13031
13032 case OR_Deleted:
13033 CandidateSet.NoteCandidates(
13034 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13035 << UnaryOperator::getOpcodeStr(Opc)
13036 << Input->getSourceRange()),
13037 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13038 OpLoc);
13039 return ExprError();
13040 }
13041
13042 // Either we found no viable overloaded operator or we matched a
13043 // built-in operator. In either case, fall through to trying to
13044 // build a built-in operation.
13045 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13046}
13047
13048/// Perform lookup for an overloaded binary operator.
13049void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13050 OverloadedOperatorKind Op,
13051 const UnresolvedSetImpl &Fns,
13052 ArrayRef<Expr *> Args, bool PerformADL) {
13053 SourceLocation OpLoc = CandidateSet.getLocation();
13054
13055 OverloadedOperatorKind ExtraOp =
13056 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13057 ? getRewrittenOverloadedOperator(Op)
13058 : OO_None;
13059
13060 // Add the candidates from the given function set. This also adds the
13061 // rewritten candidates using these functions if necessary.
13062 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13063
13064 // Add operator candidates that are member functions.
13065 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13066 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13067 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13068 OverloadCandidateParamOrder::Reversed);
13069
13070 // In C++20, also add any rewritten member candidates.
13071 if (ExtraOp) {
13072 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13073 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13074 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13075 CandidateSet,
13076 OverloadCandidateParamOrder::Reversed);
13077 }
13078
13079 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13080 // performed for an assignment operator (nor for operator[] nor operator->,
13081 // which don't get here).
13082 if (Op != OO_Equal && PerformADL) {
13083 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13084 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13085 /*ExplicitTemplateArgs*/ nullptr,
13086 CandidateSet);
13087 if (ExtraOp) {
13088 DeclarationName ExtraOpName =
13089 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13090 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13091 /*ExplicitTemplateArgs*/ nullptr,
13092 CandidateSet);
13093 }
13094 }
13095
13096 // Add builtin operator candidates.
13097 //
13098 // FIXME: We don't add any rewritten candidates here. This is strictly
13099 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13100 // resulting in our selecting a rewritten builtin candidate. For example:
13101 //
13102 // enum class E { e };
13103 // bool operator!=(E, E) requires false;
13104 // bool k = E::e != E::e;
13105 //
13106 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13107 // it seems unreasonable to consider rewritten builtin candidates. A core
13108 // issue has been filed proposing to removed this requirement.
13109 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13110}
13111
13112/// Create a binary operation that may resolve to an overloaded
13113/// operator.
13114///
13115/// \param OpLoc The location of the operator itself (e.g., '+').
13116///
13117/// \param Opc The BinaryOperatorKind that describes this operator.
13118///
13119/// \param Fns The set of non-member functions that will be
13120/// considered by overload resolution. The caller needs to build this
13121/// set based on the context using, e.g.,
13122/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13123/// set should not contain any member functions; those will be added
13124/// by CreateOverloadedBinOp().
13125///
13126/// \param LHS Left-hand argument.
13127/// \param RHS Right-hand argument.
13128/// \param PerformADL Whether to consider operator candidates found by ADL.
13129/// \param AllowRewrittenCandidates Whether to consider candidates found by
13130/// C++20 operator rewrites.
13131/// \param DefaultedFn If we are synthesizing a defaulted operator function,
13132/// the function in question. Such a function is never a candidate in
13133/// our overload resolution. This also enables synthesizing a three-way
13134/// comparison from < and == as described in C++20 [class.spaceship]p1.
13135ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13136 BinaryOperatorKind Opc,
13137 const UnresolvedSetImpl &Fns, Expr *LHS,
13138 Expr *RHS, bool PerformADL,
13139 bool AllowRewrittenCandidates,
13140 FunctionDecl *DefaultedFn) {
13141 Expr *Args[2] = { LHS, RHS };
13142 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13143
13144 if (!getLangOpts().CPlusPlus2a)
13145 AllowRewrittenCandidates = false;
13146
13147 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13148
13149 // If either side is type-dependent, create an appropriate dependent
13150 // expression.
13151 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13152 if (Fns.empty()) {
13153 // If there are no functions to store, just build a dependent
13154 // BinaryOperator or CompoundAssignment.
13155 if (Opc <= BO_Assign || Opc > BO_OrAssign)
13156 return new (Context) BinaryOperator(
13157 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
13158 OpLoc, FPFeatures);
13159
13160 return new (Context) CompoundAssignOperator(
13161 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
13162 Context.DependentTy, Context.DependentTy, OpLoc,
13163 FPFeatures);
13164 }
13165
13166 // FIXME: save results of ADL from here?
13167 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13168 // TODO: provide better source location info in DNLoc component.
13169 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13170 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13171 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13172 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13173 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13174 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13175 Context.DependentTy, VK_RValue, OpLoc,
13176 FPFeatures);
13177 }
13178
13179 // Always do placeholder-like conversions on the RHS.
13180 if (checkPlaceholderForOverload(*this, Args[1]))
13181 return ExprError();
13182
13183 // Do placeholder-like conversion on the LHS; note that we should
13184 // not get here with a PseudoObject LHS.
13185 assert(Args[0]->getObjectKind() != OK_ObjCProperty)((Args[0]->getObjectKind() != OK_ObjCProperty) ? static_cast
<void> (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13185, __PRETTY_FUNCTION__))
;
13186 if (checkPlaceholderForOverload(*this, Args[0]))
13187 return ExprError();
13188
13189 // If this is the assignment operator, we only perform overload resolution
13190 // if the left-hand side is a class or enumeration type. This is actually
13191 // a hack. The standard requires that we do overload resolution between the
13192 // various built-in candidates, but as DR507 points out, this can lead to
13193 // problems. So we do it this way, which pretty much follows what GCC does.
13194 // Note that we go the traditional code path for compound assignment forms.
13195 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13196 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13197
13198 // If this is the .* operator, which is not overloadable, just
13199 // create a built-in binary operator.
13200 if (Opc == BO_PtrMemD)
13201 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13202
13203 // Build the overload set.
13204 OverloadCandidateSet CandidateSet(
13205 OpLoc, OverloadCandidateSet::CSK_Operator,
13206 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13207 if (DefaultedFn)
13208 CandidateSet.exclude(DefaultedFn);
13209 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13210
13211 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13212
13213 // Perform overload resolution.
13214 OverloadCandidateSet::iterator Best;
13215 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13216 case OR_Success: {
13217 // We found a built-in operator or an overloaded operator.
13218 FunctionDecl *FnDecl = Best->Function;
13219
13220 bool IsReversed = (Best->RewriteKind & CRK_Reversed);
13221 if (IsReversed)
13222 std::swap(Args[0], Args[1]);
13223
13224 if (FnDecl) {
13225 Expr *Base = nullptr;
13226 // We matched an overloaded operator. Build a call to that
13227 // operator.
13228
13229 OverloadedOperatorKind ChosenOp =
13230 FnDecl->getDeclName().getCXXOverloadedOperator();
13231
13232 // C++2a [over.match.oper]p9:
13233 // If a rewritten operator== candidate is selected by overload
13234 // resolution for an operator@, its return type shall be cv bool
13235 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13236 !FnDecl->getReturnType()->isBooleanType()) {
13237 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
13238 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13239 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13240 Diag(FnDecl->getLocation(), diag::note_declared_at);
13241 return ExprError();
13242 }
13243
13244 if (AllowRewrittenCandidates && !IsReversed &&
13245 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
13246 // We could have reversed this operator, but didn't. Check if the
13247 // reversed form was a viable candidate, and if so, if it had a
13248 // better conversion for either parameter. If so, this call is
13249 // formally ambiguous, and allowing it is an extension.
13250 for (OverloadCandidate &Cand : CandidateSet) {
13251 if (Cand.Viable && Cand.Function == FnDecl &&
13252 Cand.RewriteKind & CRK_Reversed) {
13253 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13254 if (CompareImplicitConversionSequences(
13255 *this, OpLoc, Cand.Conversions[ArgIdx],
13256 Best->Conversions[ArgIdx]) ==
13257 ImplicitConversionSequence::Better) {
13258 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13259 << BinaryOperator::getOpcodeStr(Opc)
13260 << Args[0]->getType() << Args[1]->getType()
13261 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13262 Diag(FnDecl->getLocation(),
13263 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13264 }
13265 }
13266 break;
13267 }
13268 }
13269 }
13270
13271 // Convert the arguments.
13272 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13273 // Best->Access is only meaningful for class members.
13274 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13275
13276 ExprResult Arg1 =
13277 PerformCopyInitialization(
13278 InitializedEntity::InitializeParameter(Context,
13279 FnDecl->getParamDecl(0)),
13280 SourceLocation(), Args[1]);
13281 if (Arg1.isInvalid())
13282 return ExprError();
13283
13284 ExprResult Arg0 =
13285 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13286 Best->FoundDecl, Method);
13287 if (Arg0.isInvalid())
13288 return ExprError();
13289 Base = Args[0] = Arg0.getAs<Expr>();
13290 Args[1] = RHS = Arg1.getAs<Expr>();
13291 } else {
13292 // Convert the arguments.
13293 ExprResult Arg0 = PerformCopyInitialization(
13294 InitializedEntity::InitializeParameter(Context,
13295 FnDecl->getParamDecl(0)),
13296 SourceLocation(), Args[0]);
13297 if (Arg0.isInvalid())
13298 return ExprError();
13299
13300 ExprResult Arg1 =
13301 PerformCopyInitialization(
13302 InitializedEntity::InitializeParameter(Context,
13303 FnDecl->getParamDecl(1)),
13304 SourceLocation(), Args[1]);
13305 if (Arg1.isInvalid())
13306 return ExprError();
13307 Args[0] = LHS = Arg0.getAs<Expr>();
13308 Args[1] = RHS = Arg1.getAs<Expr>();
13309 }
13310
13311 // Build the actual expression node.
13312 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13313 Best->FoundDecl, Base,
13314 HadMultipleCandidates, OpLoc);
13315 if (FnExpr.isInvalid())
13316 return ExprError();
13317
13318 // Determine the result type.
13319 QualType ResultTy = FnDecl->getReturnType();
13320 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13321 ResultTy = ResultTy.getNonLValueExprType(Context);
13322
13323 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13324 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13325 FPFeatures, Best->IsADLCandidate);
13326
13327 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13328 FnDecl))
13329 return ExprError();
13330
13331 ArrayRef<const Expr *> ArgsArray(Args, 2);
13332 const Expr *ImplicitThis = nullptr;
13333 // Cut off the implicit 'this'.
13334 if (isa<CXXMethodDecl>(FnDecl)) {
13335 ImplicitThis = ArgsArray[0];
13336 ArgsArray = ArgsArray.slice(1);
13337 }
13338
13339 // Check for a self move.
13340 if (Op == OO_Equal)
13341 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13342
13343 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13344 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13345 VariadicDoesNotApply);
13346
13347 ExprResult R = MaybeBindToTemporary(TheCall);
13348 if (R.isInvalid())
13349 return ExprError();
13350
13351 // For a rewritten candidate, we've already reversed the arguments
13352 // if needed. Perform the rest of the rewrite now.
13353 if ((Best->RewriteKind & CRK_DifferentOperator) ||
13354 (Op == OO_Spaceship && IsReversed)) {
13355 if (Op == OO_ExclaimEqual) {
13356 assert(ChosenOp == OO_EqualEqual && "unexpected operator name")((ChosenOp == OO_EqualEqual && "unexpected operator name"
) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_EqualEqual && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13356, __PRETTY_FUNCTION__))
;
13357 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13358 } else {
13359 assert(ChosenOp == OO_Spaceship && "unexpected operator name")((ChosenOp == OO_Spaceship && "unexpected operator name"
) ? static_cast<void> (0) : __assert_fail ("ChosenOp == OO_Spaceship && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13359, __PRETTY_FUNCTION__))
;
13360 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13361 Expr *ZeroLiteral =
13362 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13363
13364 Sema::CodeSynthesisContext Ctx;
13365 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13366 Ctx.Entity = FnDecl;
13367 pushCodeSynthesisContext(Ctx);
13368
13369 R = CreateOverloadedBinOp(
13370 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13371 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13372 /*AllowRewrittenCandidates=*/false);
13373
13374 popCodeSynthesisContext();
13375 }
13376 if (R.isInvalid())
13377 return ExprError();
13378 } else {
13379 assert(ChosenOp == Op && "unexpected operator name")((ChosenOp == Op && "unexpected operator name") ? static_cast
<void> (0) : __assert_fail ("ChosenOp == Op && \"unexpected operator name\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13379, __PRETTY_FUNCTION__))
;
13380 }
13381
13382 // Make a note in the AST if we did any rewriting.
13383 if (Best->RewriteKind != CRK_None)
13384 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13385
13386 return R;
13387 } else {
13388 // We matched a built-in operator. Convert the arguments, then
13389 // break out so that we will build the appropriate built-in
13390 // operator node.
13391 ExprResult ArgsRes0 = PerformImplicitConversion(
13392 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13393 AA_Passing, CCK_ForBuiltinOverloadedOp);
13394 if (ArgsRes0.isInvalid())
13395 return ExprError();
13396 Args[0] = ArgsRes0.get();
13397
13398 ExprResult ArgsRes1 = PerformImplicitConversion(
13399 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13400 AA_Passing, CCK_ForBuiltinOverloadedOp);
13401 if (ArgsRes1.isInvalid())
13402 return ExprError();
13403 Args[1] = ArgsRes1.get();
13404 break;
13405 }
13406 }
13407
13408 case OR_No_Viable_Function: {
13409 // C++ [over.match.oper]p9:
13410 // If the operator is the operator , [...] and there are no
13411 // viable functions, then the operator is assumed to be the
13412 // built-in operator and interpreted according to clause 5.
13413 if (Opc == BO_Comma)
13414 break;
13415
13416 // When defaulting an 'operator<=>', we can try to synthesize a three-way
13417 // compare result using '==' and '<'.
13418 if (DefaultedFn && Opc == BO_Cmp) {
13419 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13420 Args[1], DefaultedFn);
13421 if (E.isInvalid() || E.isUsable())
13422 return E;
13423 }
13424
13425 // For class as left operand for assignment or compound assignment
13426 // operator do not fall through to handling in built-in, but report that
13427 // no overloaded assignment operator found
13428 ExprResult Result = ExprError();
13429 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13430 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13431 Args, OpLoc);
13432 if (Args[0]->getType()->isRecordType() &&
13433 Opc >= BO_Assign && Opc <= BO_OrAssign) {
13434 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13435 << BinaryOperator::getOpcodeStr(Opc)
13436 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13437 if (Args[0]->getType()->isIncompleteType()) {
13438 Diag(OpLoc, diag::note_assign_lhs_incomplete)
13439 << Args[0]->getType()
13440 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13441 }
13442 } else {
13443 // This is an erroneous use of an operator which can be overloaded by
13444 // a non-member function. Check for non-member operators which were
13445 // defined too late to be candidates.
13446 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13447 // FIXME: Recover by calling the found function.
13448 return ExprError();
13449
13450 // No viable function; try to create a built-in operation, which will
13451 // produce an error. Then, show the non-viable candidates.
13452 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13453 }
13454 assert(Result.isInvalid() &&((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13455, __PRETTY_FUNCTION__))
13455 "C++ binary operator overloading is missing candidates!")((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13455, __PRETTY_FUNCTION__))
;
13456 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13457 return Result;
13458 }
13459
13460 case OR_Ambiguous:
13461 CandidateSet.NoteCandidates(
13462 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13463 << BinaryOperator::getOpcodeStr(Opc)
13464 << Args[0]->getType()
13465 << Args[1]->getType()
13466 << Args[0]->getSourceRange()
13467 << Args[1]->getSourceRange()),
13468 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13469 OpLoc);
13470 return ExprError();
13471
13472 case OR_Deleted:
13473 if (isImplicitlyDeleted(Best->Function)) {
13474 FunctionDecl *DeletedFD = Best->Function;
13475 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13476 if (DFK.isSpecialMember()) {
13477 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13478 << Args[0]->getType() << DFK.asSpecialMember();
13479 } else {
13480 assert(DFK.isComparison())((DFK.isComparison()) ? static_cast<void> (0) : __assert_fail
("DFK.isComparison()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13480, __PRETTY_FUNCTION__))
;
13481 Diag(OpLoc, diag::err_ovl_deleted_comparison)
13482 << Args[0]->getType() << DeletedFD;
13483 }
13484
13485 // The user probably meant to call this special member. Just
13486 // explain why it's deleted.
13487 NoteDeletedFunction(DeletedFD);
13488 return ExprError();
13489 }
13490 CandidateSet.NoteCandidates(
13491 PartialDiagnosticAt(
13492 OpLoc, PDiag(diag::err_ovl_deleted_oper)
13493 << getOperatorSpelling(Best->Function->getDeclName()
13494 .getCXXOverloadedOperator())
13495 << Args[0]->getSourceRange()
13496 << Args[1]->getSourceRange()),
13497 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13498 OpLoc);
13499 return ExprError();
13500 }
13501
13502 // We matched a built-in operator; build it.
13503 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13504}
13505
13506ExprResult Sema::BuildSynthesizedThreeWayComparison(
13507 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13508 FunctionDecl *DefaultedFn) {
13509 const ComparisonCategoryInfo *Info =
13510 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13511 // If we're not producing a known comparison category type, we can't
13512 // synthesize a three-way comparison. Let the caller diagnose this.
13513 if (!Info)
13514 return ExprResult((Expr*)nullptr);
13515
13516 // If we ever want to perform this synthesis more generally, we will need to
13517 // apply the temporary materialization conversion to the operands.
13518 assert(LHS->isGLValue() && RHS->isGLValue() &&((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13519, __PRETTY_FUNCTION__))
13519 "cannot use prvalue expressions more than once")((LHS->isGLValue() && RHS->isGLValue() &&
"cannot use prvalue expressions more than once") ? static_cast
<void> (0) : __assert_fail ("LHS->isGLValue() && RHS->isGLValue() && \"cannot use prvalue expressions more than once\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13519, __PRETTY_FUNCTION__))
;
13520 Expr *OrigLHS = LHS;
13521 Expr *OrigRHS = RHS;
13522
13523 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13524 // each of them multiple times below.
13525 LHS = new (Context)
13526 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13527 LHS->getObjectKind(), LHS);
13528 RHS = new (Context)
13529 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13530 RHS->getObjectKind(), RHS);
13531
13532 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13533 DefaultedFn);
13534 if (Eq.isInvalid())
13535 return ExprError();
13536
13537 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13538 true, DefaultedFn);
13539 if (Less.isInvalid())
13540 return ExprError();
13541
13542 ExprResult Greater;
13543 if (Info->isPartial()) {
13544 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13545 DefaultedFn);
13546 if (Greater.isInvalid())
13547 return ExprError();
13548 }
13549
13550 // Form the list of comparisons we're going to perform.
13551 struct Comparison {
13552 ExprResult Cmp;
13553 ComparisonCategoryResult Result;
13554 } Comparisons[4] =
13555 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13556 : ComparisonCategoryResult::Equivalent},
13557 {Less, ComparisonCategoryResult::Less},
13558 {Greater, ComparisonCategoryResult::Greater},
13559 {ExprResult(), ComparisonCategoryResult::Unordered},
13560 };
13561
13562 int I = Info->isPartial() ? 3 : 2;
13563
13564 // Combine the comparisons with suitable conditional expressions.
13565 ExprResult Result;
13566 for (; I >= 0; --I) {
13567 // Build a reference to the comparison category constant.
13568 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13569 // FIXME: Missing a constant for a comparison category. Diagnose this?
13570 if (!VI)
13571 return ExprResult((Expr*)nullptr);
13572 ExprResult ThisResult =
13573 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13574 if (ThisResult.isInvalid())
13575 return ExprError();
13576
13577 // Build a conditional unless this is the final case.
13578 if (Result.get()) {
13579 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13580 ThisResult.get(), Result.get());
13581 if (Result.isInvalid())
13582 return ExprError();
13583 } else {
13584 Result = ThisResult;
13585 }
13586 }
13587
13588 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13589 // bind the OpaqueValueExprs before they're (repeatedly) used.
13590 Expr *SyntacticForm = new (Context)
13591 BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13592 Result.get()->getValueKind(),
13593 Result.get()->getObjectKind(), OpLoc, FPFeatures);
13594 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13595 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13596}
13597
13598ExprResult
13599Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13600 SourceLocation RLoc,
13601 Expr *Base, Expr *Idx) {
13602 Expr *Args[2] = { Base, Idx };
13603 DeclarationName OpName =
13604 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13605
13606 // If either side is type-dependent, create an appropriate dependent
13607 // expression.
13608 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13609
13610 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13611 // CHECKME: no 'operator' keyword?
13612 DeclarationNameInfo OpNameInfo(OpName, LLoc);
13613 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13614 UnresolvedLookupExpr *Fn
13615 = UnresolvedLookupExpr::Create(Context, NamingClass,
13616 NestedNameSpecifierLoc(), OpNameInfo,
13617 /*ADL*/ true, /*Overloaded*/ false,
13618 UnresolvedSetIterator(),
13619 UnresolvedSetIterator());
13620 // Can't add any actual overloads yet
13621
13622 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13623 Context.DependentTy, VK_RValue, RLoc,
13624 FPOptions());
13625 }
13626
13627 // Handle placeholders on both operands.
13628 if (checkPlaceholderForOverload(*this, Args[0]))
13629 return ExprError();
13630 if (checkPlaceholderForOverload(*this, Args[1]))
13631 return ExprError();
13632
13633 // Build an empty overload set.
13634 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13635
13636 // Subscript can only be overloaded as a member function.
13637
13638 // Add operator candidates that are member functions.
13639 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13640
13641 // Add builtin operator candidates.
13642 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13643
13644 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13645
13646 // Perform overload resolution.
13647 OverloadCandidateSet::iterator Best;
13648 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13649 case OR_Success: {
13650 // We found a built-in operator or an overloaded operator.
13651 FunctionDecl *FnDecl = Best->Function;
13652
13653 if (FnDecl) {
13654 // We matched an overloaded operator. Build a call to that
13655 // operator.
13656
13657 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13658
13659 // Convert the arguments.
13660 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13661 ExprResult Arg0 =
13662 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13663 Best->FoundDecl, Method);
13664 if (Arg0.isInvalid())
13665 return ExprError();
13666 Args[0] = Arg0.get();
13667
13668 // Convert the arguments.
13669 ExprResult InputInit
13670 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13671 Context,
13672 FnDecl->getParamDecl(0)),
13673 SourceLocation(),
13674 Args[1]);
13675 if (InputInit.isInvalid())
13676 return ExprError();
13677
13678 Args[1] = InputInit.getAs<Expr>();
13679
13680 // Build the actual expression node.
13681 DeclarationNameInfo OpLocInfo(OpName, LLoc);
13682 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13683 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13684 Best->FoundDecl,
13685 Base,
13686 HadMultipleCandidates,
13687 OpLocInfo.getLoc(),
13688 OpLocInfo.getInfo());
13689 if (FnExpr.isInvalid())
13690 return ExprError();
13691
13692 // Determine the result type
13693 QualType ResultTy = FnDecl->getReturnType();
13694 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13695 ResultTy = ResultTy.getNonLValueExprType(Context);
13696
13697 CXXOperatorCallExpr *TheCall =
13698 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13699 Args, ResultTy, VK, RLoc, FPOptions());
13700
13701 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13702 return ExprError();
13703
13704 if (CheckFunctionCall(Method, TheCall,
13705 Method->getType()->castAs<FunctionProtoType>()))
13706 return ExprError();
13707
13708 return MaybeBindToTemporary(TheCall);
13709 } else {
13710 // We matched a built-in operator. Convert the arguments, then
13711 // break out so that we will build the appropriate built-in
13712 // operator node.
13713 ExprResult ArgsRes0 = PerformImplicitConversion(
13714 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13715 AA_Passing, CCK_ForBuiltinOverloadedOp);
13716 if (ArgsRes0.isInvalid())
13717 return ExprError();
13718 Args[0] = ArgsRes0.get();
13719
13720 ExprResult ArgsRes1 = PerformImplicitConversion(
13721 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13722 AA_Passing, CCK_ForBuiltinOverloadedOp);
13723 if (ArgsRes1.isInvalid())
13724 return ExprError();
13725 Args[1] = ArgsRes1.get();
13726
13727 break;
13728 }
13729 }
13730
13731 case OR_No_Viable_Function: {
13732 PartialDiagnostic PD = CandidateSet.empty()
13733 ? (PDiag(diag::err_ovl_no_oper)
13734 << Args[0]->getType() << /*subscript*/ 0
13735 << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13736 : (PDiag(diag::err_ovl_no_viable_subscript)
13737 << Args[0]->getType() << Args[0]->getSourceRange()
13738 << Args[1]->getSourceRange());
13739 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13740 OCD_AllCandidates, Args, "[]", LLoc);
13741 return ExprError();
13742 }
13743
13744 case OR_Ambiguous:
13745 CandidateSet.NoteCandidates(
13746 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13747 << "[]" << Args[0]->getType()
13748 << Args[1]->getType()
13749 << Args[0]->getSourceRange()
13750 << Args[1]->getSourceRange()),
13751 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13752 return ExprError();
13753
13754 case OR_Deleted:
13755 CandidateSet.NoteCandidates(
13756 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13757 << "[]" << Args[0]->getSourceRange()
13758 << Args[1]->getSourceRange()),
13759 *this, OCD_AllCandidates, Args, "[]", LLoc);
13760 return ExprError();
13761 }
13762
13763 // We matched a built-in operator; build it.
13764 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13765}
13766
13767/// BuildCallToMemberFunction - Build a call to a member
13768/// function. MemExpr is the expression that refers to the member
13769/// function (and includes the object parameter), Args/NumArgs are the
13770/// arguments to the function call (not including the object
13771/// parameter). The caller needs to validate that the member
13772/// expression refers to a non-static member function or an overloaded
13773/// member function.
13774ExprResult
13775Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13776 SourceLocation LParenLoc,
13777 MultiExprArg Args,
13778 SourceLocation RParenLoc) {
13779 assert(MemExprE->getType() == Context.BoundMemberTy ||((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13780, __PRETTY_FUNCTION__))
13780 MemExprE->getType() == Context.OverloadTy)((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13780, __PRETTY_FUNCTION__))
;
13781
13782 // Dig out the member expression. This holds both the object
13783 // argument and the member function we're referring to.
13784 Expr *NakedMemExpr = MemExprE->IgnoreParens();
13785
13786 // Determine whether this is a call to a pointer-to-member function.
13787 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13788 assert(op->getType() == Context.BoundMemberTy)((op->getType() == Context.BoundMemberTy) ? static_cast<
void> (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13788, __PRETTY_FUNCTION__))
;
13789 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)((op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI
) ? static_cast<void> (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13789, __PRETTY_FUNCTION__))
;
13790
13791 QualType fnType =
13792 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13793
13794 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13795 QualType resultType = proto->getCallResultType(Context);
13796 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13797
13798 // Check that the object type isn't more qualified than the
13799 // member function we're calling.
13800 Qualifiers funcQuals = proto->getMethodQuals();
13801
13802 QualType objectType = op->getLHS()->getType();
13803 if (op->getOpcode() == BO_PtrMemI)
13804 objectType = objectType->castAs<PointerType>()->getPointeeType();
13805 Qualifiers objectQuals = objectType.getQualifiers();
13806
13807 Qualifiers difference = objectQuals - funcQuals;
13808 difference.removeObjCGCAttr();
13809 difference.removeAddressSpace();
13810 if (difference) {
13811 std::string qualsString = difference.getAsString();
13812 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13813 << fnType.getUnqualifiedType()
13814 << qualsString
13815 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13816 }
13817
13818 CXXMemberCallExpr *call =
13819 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13820 valueKind, RParenLoc, proto->getNumParams());
13821
13822 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13823 call, nullptr))
13824 return ExprError();
13825
13826 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13827 return ExprError();
13828
13829 if (CheckOtherCall(call, proto))
13830 return ExprError();
13831
13832 return MaybeBindToTemporary(call);
13833 }
13834
13835 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13836 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13837 RParenLoc);
13838
13839 UnbridgedCastsSet UnbridgedCasts;
13840 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13841 return ExprError();
13842
13843 MemberExpr *MemExpr;
13844 CXXMethodDecl *Method = nullptr;
13845 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13846 NestedNameSpecifier *Qualifier = nullptr;
13847 if (isa<MemberExpr>(NakedMemExpr)) {
13848 MemExpr = cast<MemberExpr>(NakedMemExpr);
13849 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13850 FoundDecl = MemExpr->getFoundDecl();
13851 Qualifier = MemExpr->getQualifier();
13852 UnbridgedCasts.restore();
13853 } else {
13854 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13855 Qualifier = UnresExpr->getQualifier();
13856
13857 QualType ObjectType = UnresExpr->getBaseType();
13858 Expr::Classification ObjectClassification
13859 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13860 : UnresExpr->getBase()->Classify(Context);
13861
13862 // Add overload candidates
13863 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13864 OverloadCandidateSet::CSK_Normal);
13865
13866 // FIXME: avoid copy.
13867 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13868 if (UnresExpr->hasExplicitTemplateArgs()) {
13869 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13870 TemplateArgs = &TemplateArgsBuffer;
13871 }
13872
13873 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13874 E = UnresExpr->decls_end(); I != E; ++I) {
13875
13876 NamedDecl *Func = *I;
13877 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13878 if (isa<UsingShadowDecl>(Func))
13879 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13880
13881
13882 // Microsoft supports direct constructor calls.
13883 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13884 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13885 CandidateSet,
13886 /*SuppressUserConversions*/ false);
13887 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13888 // If explicit template arguments were provided, we can't call a
13889 // non-template member function.
13890 if (TemplateArgs)
13891 continue;
13892
13893 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13894 ObjectClassification, Args, CandidateSet,
13895 /*SuppressUserConversions=*/false);
13896 } else {
13897 AddMethodTemplateCandidate(
13898 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13899 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13900 /*SuppressUserConversions=*/false);
13901 }
13902 }
13903
13904 DeclarationName DeclName = UnresExpr->getMemberName();
13905
13906 UnbridgedCasts.restore();
13907
13908 OverloadCandidateSet::iterator Best;
13909 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13910 Best)) {
13911 case OR_Success:
13912 Method = cast<CXXMethodDecl>(Best->Function);
13913 FoundDecl = Best->FoundDecl;
13914 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13915 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13916 return ExprError();
13917 // If FoundDecl is different from Method (such as if one is a template
13918 // and the other a specialization), make sure DiagnoseUseOfDecl is
13919 // called on both.
13920 // FIXME: This would be more comprehensively addressed by modifying
13921 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13922 // being used.
13923 if (Method != FoundDecl.getDecl() &&
13924 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13925 return ExprError();
13926 break;
13927
13928 case OR_No_Viable_Function:
13929 CandidateSet.NoteCandidates(
13930 PartialDiagnosticAt(
13931 UnresExpr->getMemberLoc(),
13932 PDiag(diag::err_ovl_no_viable_member_function_in_call)
13933 << DeclName << MemExprE->getSourceRange()),
13934 *this, OCD_AllCandidates, Args);
13935 // FIXME: Leaking incoming expressions!
13936 return ExprError();
13937
13938 case OR_Ambiguous:
13939 CandidateSet.NoteCandidates(
13940 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13941 PDiag(diag::err_ovl_ambiguous_member_call)
13942 << DeclName << MemExprE->getSourceRange()),
13943 *this, OCD_AmbiguousCandidates, Args);
13944 // FIXME: Leaking incoming expressions!
13945 return ExprError();
13946
13947 case OR_Deleted:
13948 CandidateSet.NoteCandidates(
13949 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13950 PDiag(diag::err_ovl_deleted_member_call)
13951 << DeclName << MemExprE->getSourceRange()),
13952 *this, OCD_AllCandidates, Args);
13953 // FIXME: Leaking incoming expressions!
13954 return ExprError();
13955 }
13956
13957 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13958
13959 // If overload resolution picked a static member, build a
13960 // non-member call based on that function.
13961 if (Method->isStatic()) {
13962 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13963 RParenLoc);
13964 }
13965
13966 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13967 }
13968
13969 QualType ResultType = Method->getReturnType();
13970 ExprValueKind VK = Expr::getValueKindForType(ResultType);
13971 ResultType = ResultType.getNonLValueExprType(Context);
13972
13973 assert(Method && "Member call to something that isn't a method?")((Method && "Member call to something that isn't a method?"
) ? static_cast<void> (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 13973, __PRETTY_FUNCTION__))
;
13974 const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13975 CXXMemberCallExpr *TheCall =
13976 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13977 RParenLoc, Proto->getNumParams());
13978
13979 // Check for a valid return type.
13980 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13981 TheCall, Method))
13982 return ExprError();
13983
13984 // Convert the object argument (for a non-static member function call).
13985 // We only need to do this if there was actually an overload; otherwise
13986 // it was done at lookup.
13987 if (!Method->isStatic()) {
13988 ExprResult ObjectArg =
13989 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13990 FoundDecl, Method);
13991 if (ObjectArg.isInvalid())
13992 return ExprError();
13993 MemExpr->setBase(ObjectArg.get());
13994 }
13995
13996 // Convert the rest of the arguments
13997 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13998 RParenLoc))
13999 return ExprError();
14000
14001 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14002
14003 if (CheckFunctionCall(Method, TheCall, Proto))
14004 return ExprError();
14005
14006 // In the case the method to call was not selected by the overloading
14007 // resolution process, we still need to handle the enable_if attribute. Do
14008 // that here, so it will not hide previous -- and more relevant -- errors.
14009 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14010 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
14011 Diag(MemE->getMemberLoc(),
14012 diag::err_ovl_no_viable_member_function_in_call)
14013 << Method << Method->getSourceRange();
14014 Diag(Method->getLocation(),
14015 diag::note_ovl_candidate_disabled_by_function_cond_attr)
14016 << Attr->getCond()->getSourceRange() << Attr->getMessage();
14017 return ExprError();
14018 }
14019 }
14020
14021 if ((isa<CXXConstructorDecl>(CurContext) ||
14022 isa<CXXDestructorDecl>(CurContext)) &&
14023 TheCall->getMethodDecl()->isPure()) {
14024 const CXXMethodDecl *MD = TheCall->getMethodDecl();
14025
14026 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14027 MemExpr->performsVirtualDispatch(getLangOpts())) {
14028 Diag(MemExpr->getBeginLoc(),
14029 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14030 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14031 << MD->getParent()->getDeclName();
14032
14033 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14034 if (getLangOpts().AppleKext)
14035 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14036 << MD->getParent()->getDeclName() << MD->getDeclName();
14037 }
14038 }
14039
14040 if (CXXDestructorDecl *DD =
14041 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14042 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14043 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14044 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14045 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14046 MemExpr->getMemberLoc());
14047 }
14048
14049 return MaybeBindToTemporary(TheCall);
14050}
14051
14052/// BuildCallToObjectOfClassType - Build a call to an object of class
14053/// type (C++ [over.call.object]), which can end up invoking an
14054/// overloaded function call operator (@c operator()) or performing a
14055/// user-defined conversion on the object argument.
14056ExprResult
14057Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14058 SourceLocation LParenLoc,
14059 MultiExprArg Args,
14060 SourceLocation RParenLoc) {
14061 if (checkPlaceholderForOverload(*this, Obj))
14062 return ExprError();
14063 ExprResult Object = Obj;
14064
14065 UnbridgedCastsSet UnbridgedCasts;
14066 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14067 return ExprError();
14068
14069 assert(Object.get()->getType()->isRecordType() &&((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14070, __PRETTY_FUNCTION__))
14070 "Requires object type argument")((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14070, __PRETTY_FUNCTION__))
;
14071 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
14072
14073 // C++ [over.call.object]p1:
14074 // If the primary-expression E in the function call syntax
14075 // evaluates to a class object of type "cv T", then the set of
14076 // candidate functions includes at least the function call
14077 // operators of T. The function call operators of T are obtained by
14078 // ordinary lookup of the name operator() in the context of
14079 // (E).operator().
14080 OverloadCandidateSet CandidateSet(LParenLoc,
14081 OverloadCandidateSet::CSK_Operator);
14082 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14083
14084 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14085 diag::err_incomplete_object_call, Object.get()))
14086 return true;
14087
14088 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14089 LookupQualifiedName(R, Record->getDecl());
14090 R.suppressDiagnostics();
14091
14092 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14093 Oper != OperEnd; ++Oper) {
14094 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14095 Object.get()->Classify(Context), Args, CandidateSet,
14096 /*SuppressUserConversion=*/false);
14097 }
14098
14099 // C++ [over.call.object]p2:
14100 // In addition, for each (non-explicit in C++0x) conversion function
14101 // declared in T of the form
14102 //
14103 // operator conversion-type-id () cv-qualifier;
14104 //
14105 // where cv-qualifier is the same cv-qualification as, or a
14106 // greater cv-qualification than, cv, and where conversion-type-id
14107 // denotes the type "pointer to function of (P1,...,Pn) returning
14108 // R", or the type "reference to pointer to function of
14109 // (P1,...,Pn) returning R", or the type "reference to function
14110 // of (P1,...,Pn) returning R", a surrogate call function [...]
14111 // is also considered as a candidate function. Similarly,
14112 // surrogate call functions are added to the set of candidate
14113 // functions for each conversion function declared in an
14114 // accessible base class provided the function is not hidden
14115 // within T by another intervening declaration.
14116 const auto &Conversions =
14117 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14118 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14119 NamedDecl *D = *I;
14120 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14121 if (isa<UsingShadowDecl>(D))
14122 D = cast<UsingShadowDecl>(D)->getTargetDecl();
14123
14124 // Skip over templated conversion functions; they aren't
14125 // surrogates.
14126 if (isa<FunctionTemplateDecl>(D))
14127 continue;
14128
14129 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14130 if (!Conv->isExplicit()) {
14131 // Strip the reference type (if any) and then the pointer type (if
14132 // any) to get down to what might be a function type.
14133 QualType ConvType = Conv->getConversionType().getNonReferenceType();
14134 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14135 ConvType = ConvPtrType->getPointeeType();
14136
14137 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14138 {
14139 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14140 Object.get(), Args, CandidateSet);
14141 }
14142 }
14143 }
14144
14145 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14146
14147 // Perform overload resolution.
14148 OverloadCandidateSet::iterator Best;
14149 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14150 Best)) {
14151 case OR_Success:
14152 // Overload resolution succeeded; we'll build the appropriate call
14153 // below.
14154 break;
14155
14156 case OR_No_Viable_Function: {
14157 PartialDiagnostic PD =
14158 CandidateSet.empty()
14159 ? (PDiag(diag::err_ovl_no_oper)
14160 << Object.get()->getType() << /*call*/ 1
14161 << Object.get()->getSourceRange())
14162 : (PDiag(diag::err_ovl_no_viable_object_call)
14163 << Object.get()->getType() << Object.get()->getSourceRange());
14164 CandidateSet.NoteCandidates(
14165 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14166 OCD_AllCandidates, Args);
14167 break;
14168 }
14169 case OR_Ambiguous:
14170 CandidateSet.NoteCandidates(
14171 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14172 PDiag(diag::err_ovl_ambiguous_object_call)
14173 << Object.get()->getType()
14174 << Object.get()->getSourceRange()),
14175 *this, OCD_AmbiguousCandidates, Args);
14176 break;
14177
14178 case OR_Deleted:
14179 CandidateSet.NoteCandidates(
14180 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14181 PDiag(diag::err_ovl_deleted_object_call)
14182 << Object.get()->getType()
14183 << Object.get()->getSourceRange()),
14184 *this, OCD_AllCandidates, Args);
14185 break;
14186 }
14187
14188 if (Best == CandidateSet.end())
14189 return true;
14190
14191 UnbridgedCasts.restore();
14192
14193 if (Best->Function == nullptr) {
14194 // Since there is no function declaration, this is one of the
14195 // surrogate candidates. Dig out the conversion function.
14196 CXXConversionDecl *Conv
14197 = cast<CXXConversionDecl>(
14198 Best->Conversions[0].UserDefined.ConversionFunction);
14199
14200 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14201 Best->FoundDecl);
14202 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14203 return ExprError();
14204 assert(Conv == Best->FoundDecl.getDecl() &&((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14205, __PRETTY_FUNCTION__))
14205 "Found Decl & conversion-to-functionptr should be same, right?!")((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14205, __PRETTY_FUNCTION__))
;
14206 // We selected one of the surrogate functions that converts the
14207 // object parameter to a function pointer. Perform the conversion
14208 // on the object argument, then let BuildCallExpr finish the job.
14209
14210 // Create an implicit member expr to refer to the conversion operator.
14211 // and then call it.
14212 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14213 Conv, HadMultipleCandidates);
14214 if (Call.isInvalid())
14215 return ExprError();
14216 // Record usage of conversion in an implicit cast.
14217 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14218 CK_UserDefinedConversion, Call.get(),
14219 nullptr, VK_RValue);
14220
14221 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14222 }
14223
14224 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14225
14226 // We found an overloaded operator(). Build a CXXOperatorCallExpr
14227 // that calls this method, using Object for the implicit object
14228 // parameter and passing along the remaining arguments.
14229 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14230
14231 // An error diagnostic has already been printed when parsing the declaration.
14232 if (Method->isInvalidDecl())
14233 return ExprError();
14234
14235 const FunctionProtoType *Proto =
14236 Method->getType()->getAs<FunctionProtoType>();
14237
14238 unsigned NumParams = Proto->getNumParams();
14239
14240 DeclarationNameInfo OpLocInfo(
14241 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14242 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14243 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14244 Obj, HadMultipleCandidates,
14245 OpLocInfo.getLoc(),
14246 OpLocInfo.getInfo());
14247 if (NewFn.isInvalid())
14248 return true;
14249
14250 // The number of argument slots to allocate in the call. If we have default
14251 // arguments we need to allocate space for them as well. We additionally
14252 // need one more slot for the object parameter.
14253 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14254
14255 // Build the full argument list for the method call (the implicit object
14256 // parameter is placed at the beginning of the list).
14257 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14258
14259 bool IsError = false;
14260
14261 // Initialize the implicit object parameter.
14262 ExprResult ObjRes =
14263 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14264 Best->FoundDecl, Method);
14265 if (ObjRes.isInvalid())
14266 IsError = true;
14267 else
14268 Object = ObjRes;
14269 MethodArgs[0] = Object.get();
14270
14271 // Check the argument types.
14272 for (unsigned i = 0; i != NumParams; i++) {
14273 Expr *Arg;
14274 if (i < Args.size()) {
14275 Arg = Args[i];
14276
14277 // Pass the argument.
14278
14279 ExprResult InputInit
14280 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14281 Context,
14282 Method->getParamDecl(i)),
14283 SourceLocation(), Arg);
14284
14285 IsError |= InputInit.isInvalid();
14286 Arg = InputInit.getAs<Expr>();
14287 } else {
14288 ExprResult DefArg
14289 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14290 if (DefArg.isInvalid()) {
14291 IsError = true;
14292 break;
14293 }
14294
14295 Arg = DefArg.getAs<Expr>();
14296 }
14297
14298 MethodArgs[i + 1] = Arg;
14299 }
14300
14301 // If this is a variadic call, handle args passed through "...".
14302 if (Proto->isVariadic()) {
14303 // Promote the arguments (C99 6.5.2.2p7).
14304 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14305 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14306 nullptr);
14307 IsError |= Arg.isInvalid();
14308 MethodArgs[i + 1] = Arg.get();
14309 }
14310 }
14311
14312 if (IsError)
14313 return true;
14314
14315 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14316
14317 // Once we've built TheCall, all of the expressions are properly owned.
14318 QualType ResultTy = Method->getReturnType();
14319 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14320 ResultTy = ResultTy.getNonLValueExprType(Context);
14321
14322 CXXOperatorCallExpr *TheCall =
14323 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14324 ResultTy, VK, RParenLoc, FPOptions());
14325
14326 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14327 return true;
14328
14329 if (CheckFunctionCall(Method, TheCall, Proto))
14330 return true;
14331
14332 return MaybeBindToTemporary(TheCall);
14333}
14334
14335/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14336/// (if one exists), where @c Base is an expression of class type and
14337/// @c Member is the name of the member we're trying to find.
14338ExprResult
14339Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14340 bool *NoArrowOperatorFound) {
14341 assert(Base->getType()->isRecordType() &&((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14342, __PRETTY_FUNCTION__))
14342 "left-hand side must have class type")((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14342, __PRETTY_FUNCTION__))
;
14343
14344 if (checkPlaceholderForOverload(*this, Base))
14345 return ExprError();
14346
14347 SourceLocation Loc = Base->getExprLoc();
14348
14349 // C++ [over.ref]p1:
14350 //
14351 // [...] An expression x->m is interpreted as (x.operator->())->m
14352 // for a class object x of type T if T::operator->() exists and if
14353 // the operator is selected as the best match function by the
14354 // overload resolution mechanism (13.3).
14355 DeclarationName OpName =
14356 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14357 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14358 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
14359
14360 if (RequireCompleteType(Loc, Base->getType(),
14361 diag::err_typecheck_incomplete_tag, Base))
14362 return ExprError();
14363
14364 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14365 LookupQualifiedName(R, BaseRecord->getDecl());
14366 R.suppressDiagnostics();
14367
14368 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14369 Oper != OperEnd; ++Oper) {
14370 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14371 None, CandidateSet, /*SuppressUserConversion=*/false);
14372 }
14373
14374 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14375
14376 // Perform overload resolution.
14377 OverloadCandidateSet::iterator Best;
14378 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14379 case OR_Success:
14380 // Overload resolution succeeded; we'll build the call below.
14381 break;
14382
14383 case OR_No_Viable_Function: {
14384 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14385 if (CandidateSet.empty()) {
14386 QualType BaseType = Base->getType();
14387 if (NoArrowOperatorFound) {
14388 // Report this specific error to the caller instead of emitting a
14389 // diagnostic, as requested.
14390 *NoArrowOperatorFound = true;
14391 return ExprError();
14392 }
14393 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14394 << BaseType << Base->getSourceRange();
14395 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14396 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14397 << FixItHint::CreateReplacement(OpLoc, ".");
14398 }
14399 } else
14400 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14401 << "operator->" << Base->getSourceRange();
14402 CandidateSet.NoteCandidates(*this, Base, Cands);
14403 return ExprError();
14404 }
14405 case OR_Ambiguous:
14406 CandidateSet.NoteCandidates(
14407 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14408 << "->" << Base->getType()
14409 << Base->getSourceRange()),
14410 *this, OCD_AmbiguousCandidates, Base);
14411 return ExprError();
14412
14413 case OR_Deleted:
14414 CandidateSet.NoteCandidates(
14415 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14416 << "->" << Base->getSourceRange()),
14417 *this, OCD_AllCandidates, Base);
14418 return ExprError();
14419 }
14420
14421 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14422
14423 // Convert the object parameter.
14424 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14425 ExprResult BaseResult =
14426 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14427 Best->FoundDecl, Method);
14428 if (BaseResult.isInvalid())
14429 return ExprError();
14430 Base = BaseResult.get();
14431
14432 // Build the operator call.
14433 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14434 Base, HadMultipleCandidates, OpLoc);
14435 if (FnExpr.isInvalid())
14436 return ExprError();
14437
14438 QualType ResultTy = Method->getReturnType();
14439 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14440 ResultTy = ResultTy.getNonLValueExprType(Context);
14441 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14442 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14443
14444 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14445 return ExprError();
14446
14447 if (CheckFunctionCall(Method, TheCall,
14448 Method->getType()->castAs<FunctionProtoType>()))
14449 return ExprError();
14450
14451 return MaybeBindToTemporary(TheCall);
14452}
14453
14454/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14455/// a literal operator described by the provided lookup results.
14456ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14457 DeclarationNameInfo &SuffixInfo,
14458 ArrayRef<Expr*> Args,
14459 SourceLocation LitEndLoc,
14460 TemplateArgumentListInfo *TemplateArgs) {
14461 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14462
14463 OverloadCandidateSet CandidateSet(UDSuffixLoc,
14464 OverloadCandidateSet::CSK_Normal);
14465 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14466 TemplateArgs);
14467
14468 bool HadMultipleCandidates = (CandidateSet.size() > 1);
1
Assuming the condition is false
14469
14470 // Perform overload resolution. This will usually be trivial, but might need
14471 // to perform substitutions for a literal operator template.
14472 OverloadCandidateSet::iterator Best;
14473 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
2
Calling 'OverloadCandidateSet::BestViableFunction'
14474 case OR_Success:
14475 case OR_Deleted:
14476 break;
14477
14478 case OR_No_Viable_Function:
14479 CandidateSet.NoteCandidates(
14480 PartialDiagnosticAt(UDSuffixLoc,
14481 PDiag(diag::err_ovl_no_viable_function_in_call)
14482 << R.getLookupName()),
14483 *this, OCD_AllCandidates, Args);
14484 return ExprError();
14485
14486 case OR_Ambiguous:
14487 CandidateSet.NoteCandidates(
14488 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14489 << R.getLookupName()),
14490 *this, OCD_AmbiguousCandidates, Args);
14491 return ExprError();
14492 }
14493
14494 FunctionDecl *FD = Best->Function;
14495 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14496 nullptr, HadMultipleCandidates,
14497 SuffixInfo.getLoc(),
14498 SuffixInfo.getInfo());
14499 if (Fn.isInvalid())
14500 return true;
14501
14502 // Check the argument types. This should almost always be a no-op, except
14503 // that array-to-pointer decay is applied to string literals.
14504 Expr *ConvArgs[2];
14505 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14506 ExprResult InputInit = PerformCopyInitialization(
14507 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14508 SourceLocation(), Args[ArgIdx]);
14509 if (InputInit.isInvalid())
14510 return true;
14511 ConvArgs[ArgIdx] = InputInit.get();
14512 }
14513
14514 QualType ResultTy = FD->getReturnType();
14515 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14516 ResultTy = ResultTy.getNonLValueExprType(Context);
14517
14518 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14519 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14520 VK, LitEndLoc, UDSuffixLoc);
14521
14522 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14523 return ExprError();
14524
14525 if (CheckFunctionCall(FD, UDL, nullptr))
14526 return ExprError();
14527
14528 return MaybeBindToTemporary(UDL);
14529}
14530
14531/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14532/// given LookupResult is non-empty, it is assumed to describe a member which
14533/// will be invoked. Otherwise, the function will be found via argument
14534/// dependent lookup.
14535/// CallExpr is set to a valid expression and FRS_Success returned on success,
14536/// otherwise CallExpr is set to ExprError() and some non-success value
14537/// is returned.
14538Sema::ForRangeStatus
14539Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14540 SourceLocation RangeLoc,
14541 const DeclarationNameInfo &NameInfo,
14542 LookupResult &MemberLookup,
14543 OverloadCandidateSet *CandidateSet,
14544 Expr *Range, ExprResult *CallExpr) {
14545 Scope *S = nullptr;
14546
14547 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14548 if (!MemberLookup.empty()) {
14549 ExprResult MemberRef =
14550 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14551 /*IsPtr=*/false, CXXScopeSpec(),
14552 /*TemplateKWLoc=*/SourceLocation(),
14553 /*FirstQualifierInScope=*/nullptr,
14554 MemberLookup,
14555 /*TemplateArgs=*/nullptr, S);
14556 if (MemberRef.isInvalid()) {
14557 *CallExpr = ExprError();
14558 return FRS_DiagnosticIssued;
14559 }
14560 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14561 if (CallExpr->isInvalid()) {
14562 *CallExpr = ExprError();
14563 return FRS_DiagnosticIssued;
14564 }
14565 } else {
14566 UnresolvedSet<0> FoundNames;
14567 UnresolvedLookupExpr *Fn =
14568 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14569 NestedNameSpecifierLoc(), NameInfo,
14570 /*NeedsADL=*/true, /*Overloaded=*/false,
14571 FoundNames.begin(), FoundNames.end());
14572
14573 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14574 CandidateSet, CallExpr);
14575 if (CandidateSet->empty() || CandidateSetError) {
14576 *CallExpr = ExprError();
14577 return FRS_NoViableFunction;
14578 }
14579 OverloadCandidateSet::iterator Best;
14580 OverloadingResult OverloadResult =
14581 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14582
14583 if (OverloadResult == OR_No_Viable_Function) {
14584 *CallExpr = ExprError();
14585 return FRS_NoViableFunction;
14586 }
14587 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14588 Loc, nullptr, CandidateSet, &Best,
14589 OverloadResult,
14590 /*AllowTypoCorrection=*/false);
14591 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14592 *CallExpr = ExprError();
14593 return FRS_DiagnosticIssued;
14594 }
14595 }
14596 return FRS_Success;
14597}
14598
14599
14600/// FixOverloadedFunctionReference - E is an expression that refers to
14601/// a C++ overloaded function (possibly with some parentheses and
14602/// perhaps a '&' around it). We have resolved the overloaded function
14603/// to the function declaration Fn, so patch up the expression E to
14604/// refer (possibly indirectly) to Fn. Returns the new expr.
14605Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14606 FunctionDecl *Fn) {
14607 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14608 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14609 Found, Fn);
14610 if (SubExpr == PE->getSubExpr())
14611 return PE;
14612
14613 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14614 }
14615
14616 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14617 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14618 Found, Fn);
14619 assert(Context.hasSameType(ICE->getSubExpr()->getType(),((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14621, __PRETTY_FUNCTION__))
14620 SubExpr->getType()) &&((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14621, __PRETTY_FUNCTION__))
14621 "Implicit cast type cannot be determined from overload")((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14621, __PRETTY_FUNCTION__))
;
14622 assert(ICE->path_empty() && "fixing up hierarchy conversion?")((ICE->path_empty() && "fixing up hierarchy conversion?"
) ? static_cast<void> (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14622, __PRETTY_FUNCTION__))
;
14623 if (SubExpr == ICE->getSubExpr())
14624 return ICE;
14625
14626 return ImplicitCastExpr::Create(Context, ICE->getType(),
14627 ICE->getCastKind(),
14628 SubExpr, nullptr,
14629 ICE->getValueKind());
14630 }
14631
14632 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14633 if (!GSE->isResultDependent()) {
14634 Expr *SubExpr =
14635 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14636 if (SubExpr == GSE->getResultExpr())
14637 return GSE;
14638
14639 // Replace the resulting type information before rebuilding the generic
14640 // selection expression.
14641 ArrayRef<Expr *> A = GSE->getAssocExprs();
14642 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14643 unsigned ResultIdx = GSE->getResultIndex();
14644 AssocExprs[ResultIdx] = SubExpr;
14645
14646 return GenericSelectionExpr::Create(
14647 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14648 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14649 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14650 ResultIdx);
14651 }
14652 // Rather than fall through to the unreachable, return the original generic
14653 // selection expression.
14654 return GSE;
14655 }
14656
14657 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14658 assert(UnOp->getOpcode() == UO_AddrOf &&((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14659, __PRETTY_FUNCTION__))
14659 "Can only take the address of an overloaded function")((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14659, __PRETTY_FUNCTION__))
;
14660 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14661 if (Method->isStatic()) {
14662 // Do nothing: static member functions aren't any different
14663 // from non-member functions.
14664 } else {
14665 // Fix the subexpression, which really has to be an
14666 // UnresolvedLookupExpr holding an overloaded member function
14667 // or template.
14668 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14669 Found, Fn);
14670 if (SubExpr == UnOp->getSubExpr())
14671 return UnOp;
14672
14673 assert(isa<DeclRefExpr>(SubExpr)((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14674, __PRETTY_FUNCTION__))
14674 && "fixed to something other than a decl ref")((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14674, __PRETTY_FUNCTION__))
;
14675 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14676, __PRETTY_FUNCTION__))
14676 && "fixed to a member ref with no nested name qualifier")((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14676, __PRETTY_FUNCTION__))
;
14677
14678 // We have taken the address of a pointer to member
14679 // function. Perform the computation here so that we get the
14680 // appropriate pointer to member type.
14681 QualType ClassType
14682 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14683 QualType MemPtrType
14684 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14685 // Under the MS ABI, lock down the inheritance model now.
14686 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14687 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14688
14689 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14690 VK_RValue, OK_Ordinary,
14691 UnOp->getOperatorLoc(), false);
14692 }
14693 }
14694 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14695 Found, Fn);
14696 if (SubExpr == UnOp->getSubExpr())
14697 return UnOp;
14698
14699 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14700 Context.getPointerType(SubExpr->getType()),
14701 VK_RValue, OK_Ordinary,
14702 UnOp->getOperatorLoc(), false);
14703 }
14704
14705 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14706 // FIXME: avoid copy.
14707 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14708 if (ULE->hasExplicitTemplateArgs()) {
14709 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14710 TemplateArgs = &TemplateArgsBuffer;
14711 }
14712
14713 DeclRefExpr *DRE =
14714 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14715 ULE->getQualifierLoc(), Found.getDecl(),
14716 ULE->getTemplateKeywordLoc(), TemplateArgs);
14717 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14718 return DRE;
14719 }
14720
14721 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14722 // FIXME: avoid copy.
14723 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14724 if (MemExpr->hasExplicitTemplateArgs()) {
14725 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14726 TemplateArgs = &TemplateArgsBuffer;
14727 }
14728
14729 Expr *Base;
14730
14731 // If we're filling in a static method where we used to have an
14732 // implicit member access, rewrite to a simple decl ref.
14733 if (MemExpr->isImplicitAccess()) {
14734 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14735 DeclRefExpr *DRE = BuildDeclRefExpr(
14736 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14737 MemExpr->getQualifierLoc(), Found.getDecl(),
14738 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14739 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14740 return DRE;
14741 } else {
14742 SourceLocation Loc = MemExpr->getMemberLoc();
14743 if (MemExpr->getQualifier())
14744 Loc = MemExpr->getQualifierLoc().getBeginLoc();
14745 Base =
14746 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14747 }
14748 } else
14749 Base = MemExpr->getBase();
14750
14751 ExprValueKind valueKind;
14752 QualType type;
14753 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14754 valueKind = VK_LValue;
14755 type = Fn->getType();
14756 } else {
14757 valueKind = VK_RValue;
14758 type = Context.BoundMemberTy;
14759 }
14760
14761 return BuildMemberExpr(
14762 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14763 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14764 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14765 type, valueKind, OK_Ordinary, TemplateArgs);
14766 }
14767
14768 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaOverload.cpp"
, 14768)
;
14769}
14770
14771ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14772 DeclAccessPair Found,
14773 FunctionDecl *Fn) {
14774 return FixOverloadedFunctionReference(E.get(), Found, Fn);
14775}

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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/AlignOf.h"
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Support/MemAlloc.h"
21#include "llvm/Support/type_traits.h"
22#include "llvm/Support/ErrorHandling.h"
23#include <algorithm>
24#include <cassert>
25#include <cstddef>
26#include <cstdlib>
27#include <cstring>
28#include <initializer_list>
29#include <iterator>
30#include <memory>
31#include <new>
32#include <type_traits>
33#include <utility>
34
35namespace llvm {
36
37/// This is all the non-templated stuff common to all SmallVectors.
38class SmallVectorBase {
39protected:
40 void *BeginX;
41 unsigned Size = 0, Capacity;
42
43 SmallVectorBase() = delete;
44 SmallVectorBase(void *FirstEl, size_t TotalCapacity)
45 : BeginX(FirstEl), Capacity(TotalCapacity) {}
46
47 /// This is an implementation of the grow() method which only works
48 /// on POD-like data types and is out of line to reduce code duplication.
49 void grow_pod(void *FirstEl, size_t MinCapacity, size_t TSize);
50
51public:
52 size_t size() const { return Size; }
53 size_t capacity() const { return Capacity; }
54
55 LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const { return !Size; }
14
Assuming field 'Size' is not equal to 0
15
Returning zero, which participates in a condition later
56
57 /// Set the array size to \p N, which the current array must have enough
58 /// capacity for.
59 ///
60 /// This does not construct or destroy any elements in the vector.
61 ///
62 /// Clients can use this in conjunction with capacity() to write past the end
63 /// of the buffer when they know that more elements are available, and only
64 /// update the size later. This avoids the cost of value initializing elements
65 /// which will only be overwritten.
66 void set_size(size_t N) {
67 assert(N <= capacity())((N <= capacity()) ? static_cast<void> (0) : __assert_fail
("N <= capacity()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 67, __PRETTY_FUNCTION__))
;
68 Size = N;
69 }
70};
71
72/// Figure out the offset of the first element.
73template <class T, typename = void> struct SmallVectorAlignmentAndSize {
74 AlignedCharArrayUnion<SmallVectorBase> Base;
75 AlignedCharArrayUnion<T> FirstEl;
76};
77
78/// This is the part of SmallVectorTemplateBase which does not depend on whether
79/// the type T is a POD. The extra dummy template argument is used by ArrayRef
80/// to avoid unnecessarily requiring T to be complete.
81template <typename T, typename = void>
82class SmallVectorTemplateCommon : public SmallVectorBase {
83 /// Find the address of the first element. For this pointer math to be valid
84 /// with small-size of 0 for T with lots of alignment, it's important that
85 /// SmallVectorStorage is properly-aligned even for small-size of 0.
86 void *getFirstEl() const {
87 return const_cast<void *>(reinterpret_cast<const void *>(
88 reinterpret_cast<const char *>(this) +
89 offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)__builtin_offsetof(SmallVectorAlignmentAndSize<T>, FirstEl
)
));
90 }
91 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
92
93protected:
94 SmallVectorTemplateCommon(size_t Size)
95 : SmallVectorBase(getFirstEl(), Size) {}
96
97 void grow_pod(size_t MinCapacity, size_t TSize) {
98 SmallVectorBase::grow_pod(getFirstEl(), MinCapacity, TSize);
99 }
100
101 /// Return true if this is a smallvector which has not had dynamic
102 /// memory allocated for it.
103 bool isSmall() const { return BeginX == getFirstEl(); }
104
105 /// Put this vector in a state of being small.
106 void resetToSmall() {
107 BeginX = getFirstEl();
108 Size = Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
109 }
110
111public:
112 using size_type = size_t;
113 using difference_type = ptrdiff_t;
114 using value_type = T;
115 using iterator = T *;
116 using const_iterator = const T *;
117
118 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
119 using reverse_iterator = std::reverse_iterator<iterator>;
120
121 using reference = T &;
122 using const_reference = const T &;
123 using pointer = T *;
124 using const_pointer = const T *;
125
126 // forward iterator creation methods.
127 iterator begin() { return (iterator)this->BeginX; }
128 const_iterator begin() const { return (const_iterator)this->BeginX; }
129 iterator end() { return begin() + size(); }
130 const_iterator end() const { return begin() + size(); }
131
132 // reverse iterator creation methods.
133 reverse_iterator rbegin() { return reverse_iterator(end()); }
134 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
135 reverse_iterator rend() { return reverse_iterator(begin()); }
136 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
137
138 size_type size_in_bytes() const { return size() * sizeof(T); }
139 size_type max_size() const { return size_type(-1) / sizeof(T); }
140
141 size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
142
143 /// Return a pointer to the vector's buffer, even if empty().
144 pointer data() { return pointer(begin()); }
145 /// Return a pointer to the vector's buffer, even if empty().
146 const_pointer data() const { return const_pointer(begin()); }
147
148 reference operator[](size_type idx) {
149 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 149, __PRETTY_FUNCTION__))
;
150 return begin()[idx];
151 }
152 const_reference operator[](size_type idx) const {
153 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 153, __PRETTY_FUNCTION__))
;
154 return begin()[idx];
155 }
156
157 reference front() {
158 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 158, __PRETTY_FUNCTION__))
;
159 return begin()[0];
160 }
161 const_reference front() const {
162 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 162, __PRETTY_FUNCTION__))
;
163 return begin()[0];
164 }
165
166 reference back() {
167 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 167, __PRETTY_FUNCTION__))
;
168 return end()[-1];
169 }
170 const_reference back() const {
171 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 171, __PRETTY_FUNCTION__))
;
172 return end()[-1];
173 }
174};
175
176/// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put method
177/// implementations that are designed to work with non-POD-like T's.
178template <typename T, bool = is_trivially_copyable<T>::value>
179class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
180protected:
181 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
182
183 static void destroy_range(T *S, T *E) {
184 while (S != E) {
185 --E;
186 E->~T();
187 }
188 }
189
190 /// Move the range [I, E) into the uninitialized memory starting with "Dest",
191 /// constructing elements as needed.
192 template<typename It1, typename It2>
193 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
194 std::uninitialized_copy(std::make_move_iterator(I),
195 std::make_move_iterator(E), Dest);
196 }
197
198 /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
199 /// constructing elements as needed.
200 template<typename It1, typename It2>
201 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
202 std::uninitialized_copy(I, E, Dest);
203 }
204
205 /// Grow the allocated memory (without initializing new elements), doubling
206 /// the size of the allocated memory. Guarantees space for at least one more
207 /// element, or MinSize more elements if specified.
208 void grow(size_t MinSize = 0);
209
210public:
211 void push_back(const T &Elt) {
212 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
213 this->grow();
214 ::new ((void*) this->end()) T(Elt);
215 this->set_size(this->size() + 1);
216 }
217
218 void push_back(T &&Elt) {
219 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
220 this->grow();
221 ::new ((void*) this->end()) T(::std::move(Elt));
222 this->set_size(this->size() + 1);
223 }
224
225 void pop_back() {
226 this->set_size(this->size() - 1);
227 this->end()->~T();
228 }
229};
230
231// Define this out-of-line to dissuade the C++ compiler from inlining it.
232template <typename T, bool TriviallyCopyable>
233void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
234 if (MinSize > UINT32_MAX(4294967295U))
235 report_bad_alloc_error("SmallVector capacity overflow during allocation");
236
237 // Always grow, even from zero.
238 size_t NewCapacity = size_t(NextPowerOf2(this->capacity() + 2));
239 NewCapacity = std::min(std::max(NewCapacity, MinSize), size_t(UINT32_MAX(4294967295U)));
240 T *NewElts = static_cast<T*>(llvm::safe_malloc(NewCapacity*sizeof(T)));
241
242 // Move the elements over.
243 this->uninitialized_move(this->begin(), this->end(), NewElts);
244
245 // Destroy the original elements.
246 destroy_range(this->begin(), this->end());
247
248 // If this wasn't grown from the inline copy, deallocate the old space.
249 if (!this->isSmall())
250 free(this->begin());
251
252 this->BeginX = NewElts;
253 this->Capacity = NewCapacity;
254}
255
256/// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put
257/// method implementations that are designed to work with POD-like T's.
258template <typename T>
259class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
260protected:
261 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
262
263 // No need to do a destroy loop for POD's.
264 static void destroy_range(T *, T *) {}
265
266 /// Move the range [I, E) onto the uninitialized memory
267 /// starting with "Dest", constructing elements into it as needed.
268 template<typename It1, typename It2>
269 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
270 // Just do a copy.
271 uninitialized_copy(I, E, Dest);
272 }
273
274 /// Copy the range [I, E) onto the uninitialized memory
275 /// starting with "Dest", constructing elements into it as needed.
276 template<typename It1, typename It2>
277 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
278 // Arbitrary iterator types; just use the basic implementation.
279 std::uninitialized_copy(I, E, Dest);
280 }
281
282 /// Copy the range [I, E) onto the uninitialized memory
283 /// starting with "Dest", constructing elements into it as needed.
284 template <typename T1, typename T2>
285 static void uninitialized_copy(
286 T1 *I, T1 *E, T2 *Dest,
287 typename std::enable_if<std::is_same<typename std::remove_const<T1>::type,
288 T2>::value>::type * = nullptr) {
289 // Use memcpy for PODs iterated by pointers (which includes SmallVector
290 // iterators): std::uninitialized_copy optimizes to memmove, but we can
291 // use memcpy here. Note that I and E are iterators and thus might be
292 // invalid for memcpy if they are equal.
293 if (I != E)
294 memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T));
295 }
296
297 /// Double the size of the allocated memory, guaranteeing space for at
298 /// least one more element or MinSize if specified.
299 void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); }
300
301public:
302 void push_back(const T &Elt) {
303 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
304 this->grow();
305 memcpy(reinterpret_cast<void *>(this->end()), &Elt, sizeof(T));
306 this->set_size(this->size() + 1);
307 }
308
309 void pop_back() { this->set_size(this->size() - 1); }
310};
311
312/// This class consists of common code factored out of the SmallVector class to
313/// reduce code duplication based on the SmallVector 'N' template parameter.
314template <typename T>
315class SmallVectorImpl : public SmallVectorTemplateBase<T> {
316 using SuperClass = SmallVectorTemplateBase<T>;
317
318public:
319 using iterator = typename SuperClass::iterator;
320 using const_iterator = typename SuperClass::const_iterator;
321 using reference = typename SuperClass::reference;
322 using size_type = typename SuperClass::size_type;
323
324protected:
325 // Default ctor - Initialize to empty.
326 explicit SmallVectorImpl(unsigned N)
327 : SmallVectorTemplateBase<T>(N) {}
328
329public:
330 SmallVectorImpl(const SmallVectorImpl &) = delete;
331
332 ~SmallVectorImpl() {
333 // Subclass has already destructed this vector's elements.
334 // If this wasn't grown from the inline copy, deallocate the old space.
335 if (!this->isSmall())
336 free(this->begin());
337 }
338
339 void clear() {
340 this->destroy_range(this->begin(), this->end());
341 this->Size = 0;
342 }
343
344 void resize(size_type N) {
345 if (N < this->size()) {
346 this->destroy_range(this->begin()+N, this->end());
347 this->set_size(N);
348 } else if (N > this->size()) {
349 if (this->capacity() < N)
350 this->grow(N);
351 for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
352 new (&*I) T();
353 this->set_size(N);
354 }
355 }
356
357 void resize(size_type N, const T &NV) {
358 if (N < this->size()) {
359 this->destroy_range(this->begin()+N, this->end());
360 this->set_size(N);
361 } else if (N > this->size()) {
362 if (this->capacity() < N)
363 this->grow(N);
364 std::uninitialized_fill(this->end(), this->begin()+N, NV);
365 this->set_size(N);
366 }
367 }
368
369 void reserve(size_type N) {
370 if (this->capacity() < N)
371 this->grow(N);
372 }
373
374 LLVM_NODISCARD[[clang::warn_unused_result]] T pop_back_val() {
375 T Result = ::std::move(this->back());
376 this->pop_back();
377 return Result;
378 }
379
380 void swap(SmallVectorImpl &RHS);
381
382 /// Add the specified range to the end of the SmallVector.
383 template <typename in_iter,
384 typename = typename std::enable_if<std::is_convertible<
385 typename std::iterator_traits<in_iter>::iterator_category,
386 std::input_iterator_tag>::value>::type>
387 void append(in_iter in_start, in_iter in_end) {
388 size_type NumInputs = std::distance(in_start, in_end);
389 if (NumInputs > this->capacity() - this->size())
390 this->grow(this->size()+NumInputs);
391
392 this->uninitialized_copy(in_start, in_end, this->end());
393 this->set_size(this->size() + NumInputs);
394 }
395
396 /// Append \p NumInputs copies of \p Elt to the end.
397 void append(size_type NumInputs, const T &Elt) {
398 if (NumInputs > this->capacity() - this->size())
399 this->grow(this->size()+NumInputs);
400
401 std::uninitialized_fill_n(this->end(), NumInputs, Elt);
402 this->set_size(this->size() + NumInputs);
403 }
404
405 void append(std::initializer_list<T> IL) {
406 append(IL.begin(), IL.end());
407 }
408
409 // FIXME: Consider assigning over existing elements, rather than clearing &
410 // re-initializing them - for all assign(...) variants.
411
412 void assign(size_type NumElts, const T &Elt) {
413 clear();
414 if (this->capacity() < NumElts)
415 this->grow(NumElts);
416 this->set_size(NumElts);
417 std::uninitialized_fill(this->begin(), this->end(), Elt);
418 }
419
420 template <typename in_iter,
421 typename = typename std::enable_if<std::is_convertible<
422 typename std::iterator_traits<in_iter>::iterator_category,
423 std::input_iterator_tag>::value>::type>
424 void assign(in_iter in_start, in_iter in_end) {
425 clear();
426 append(in_start, in_end);
427 }
428
429 void assign(std::initializer_list<T> IL) {
430 clear();
431 append(IL);
432 }
433
434 iterator erase(const_iterator CI) {
435 // Just cast away constness because this is a non-const member function.
436 iterator I = const_cast<iterator>(CI);
437
438 assert(I >= this->begin() && "Iterator to erase is out of bounds.")((I >= this->begin() && "Iterator to erase is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Iterator to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 438, __PRETTY_FUNCTION__))
;
439 assert(I < this->end() && "Erasing at past-the-end iterator.")((I < this->end() && "Erasing at past-the-end iterator."
) ? static_cast<void> (0) : __assert_fail ("I < this->end() && \"Erasing at past-the-end iterator.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 439, __PRETTY_FUNCTION__))
;
440
441 iterator N = I;
442 // Shift all elts down one.
443 std::move(I+1, this->end(), I);
444 // Drop the last elt.
445 this->pop_back();
446 return(N);
447 }
448
449 iterator erase(const_iterator CS, const_iterator CE) {
450 // Just cast away constness because this is a non-const member function.
451 iterator S = const_cast<iterator>(CS);
452 iterator E = const_cast<iterator>(CE);
453
454 assert(S >= this->begin() && "Range to erase is out of bounds.")((S >= this->begin() && "Range to erase is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("S >= this->begin() && \"Range to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 454, __PRETTY_FUNCTION__))
;
455 assert(S <= E && "Trying to erase invalid range.")((S <= E && "Trying to erase invalid range.") ? static_cast
<void> (0) : __assert_fail ("S <= E && \"Trying to erase invalid range.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(E <= this->end() && "Trying to erase past the end.")((E <= this->end() && "Trying to erase past the end."
) ? static_cast<void> (0) : __assert_fail ("E <= this->end() && \"Trying to erase past the end.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 456, __PRETTY_FUNCTION__))
;
457
458 iterator N = S;
459 // Shift all elts down.
460 iterator I = std::move(E, this->end(), S);
461 // Drop the last elts.
462 this->destroy_range(I, this->end());
463 this->set_size(I - this->begin());
464 return(N);
465 }
466
467 iterator insert(iterator I, T &&Elt) {
468 if (I == this->end()) { // Important special case for empty vector.
469 this->push_back(::std::move(Elt));
470 return this->end()-1;
471 }
472
473 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 473, __PRETTY_FUNCTION__))
;
474 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 474, __PRETTY_FUNCTION__))
;
475
476 if (this->size() >= this->capacity()) {
477 size_t EltNo = I-this->begin();
478 this->grow();
479 I = this->begin()+EltNo;
480 }
481
482 ::new ((void*) this->end()) T(::std::move(this->back()));
483 // Push everything else over.
484 std::move_backward(I, this->end()-1, this->end());
485 this->set_size(this->size() + 1);
486
487 // If we just moved the element we're inserting, be sure to update
488 // the reference.
489 T *EltPtr = &Elt;
490 if (I <= EltPtr && EltPtr < this->end())
491 ++EltPtr;
492
493 *I = ::std::move(*EltPtr);
494 return I;
495 }
496
497 iterator insert(iterator I, const T &Elt) {
498 if (I == this->end()) { // Important special case for empty vector.
499 this->push_back(Elt);
500 return this->end()-1;
501 }
502
503 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 503, __PRETTY_FUNCTION__))
;
504 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 504, __PRETTY_FUNCTION__))
;
505
506 if (this->size() >= this->capacity()) {
507 size_t EltNo = I-this->begin();
508 this->grow();
509 I = this->begin()+EltNo;
510 }
511 ::new ((void*) this->end()) T(std::move(this->back()));
512 // Push everything else over.
513 std::move_backward(I, this->end()-1, this->end());
514 this->set_size(this->size() + 1);
515
516 // If we just moved the element we're inserting, be sure to update
517 // the reference.
518 const T *EltPtr = &Elt;
519 if (I <= EltPtr && EltPtr < this->end())
520 ++EltPtr;
521
522 *I = *EltPtr;
523 return I;
524 }
525
526 iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
527 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
528 size_t InsertElt = I - this->begin();
529
530 if (I == this->end()) { // Important special case for empty vector.
531 append(NumToInsert, Elt);
532 return this->begin()+InsertElt;
533 }
534
535 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 535, __PRETTY_FUNCTION__))
;
536 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 536, __PRETTY_FUNCTION__))
;
537
538 // Ensure there is enough space.
539 reserve(this->size() + NumToInsert);
540
541 // Uninvalidate the iterator.
542 I = this->begin()+InsertElt;
543
544 // If there are more elements between the insertion point and the end of the
545 // range than there are being inserted, we can use a simple approach to
546 // insertion. Since we already reserved space, we know that this won't
547 // reallocate the vector.
548 if (size_t(this->end()-I) >= NumToInsert) {
549 T *OldEnd = this->end();
550 append(std::move_iterator<iterator>(this->end() - NumToInsert),
551 std::move_iterator<iterator>(this->end()));
552
553 // Copy the existing elements that get replaced.
554 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
555
556 std::fill_n(I, NumToInsert, Elt);
557 return I;
558 }
559
560 // Otherwise, we're inserting more elements than exist already, and we're
561 // not inserting at the end.
562
563 // Move over the elements that we're about to overwrite.
564 T *OldEnd = this->end();
565 this->set_size(this->size() + NumToInsert);
566 size_t NumOverwritten = OldEnd-I;
567 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
568
569 // Replace the overwritten part.
570 std::fill_n(I, NumOverwritten, Elt);
571
572 // Insert the non-overwritten middle part.
573 std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
574 return I;
575 }
576
577 template <typename ItTy,
578 typename = typename std::enable_if<std::is_convertible<
579 typename std::iterator_traits<ItTy>::iterator_category,
580 std::input_iterator_tag>::value>::type>
581 iterator insert(iterator I, ItTy From, ItTy To) {
582 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
583 size_t InsertElt = I - this->begin();
584
585 if (I == this->end()) { // Important special case for empty vector.
586 append(From, To);
587 return this->begin()+InsertElt;
588 }
589
590 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 590, __PRETTY_FUNCTION__))
;
591 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/ADT/SmallVector.h"
, 591, __PRETTY_FUNCTION__))
;
592
593 size_t NumToInsert = std::distance(From, To);
594
595 // Ensure there is enough space.
596 reserve(this->size() + NumToInsert);
597
598 // Uninvalidate the iterator.
599 I = this->begin()+InsertElt;
600
601 // If there are more elements between the insertion point and the end of the
602 // range than there are being inserted, we can use a simple approach to
603 // insertion. Since we already reserved space, we know that this won't
604 // reallocate the vector.
605 if (size_t(this->end()-I) >= NumToInsert) {
606 T *OldEnd = this->end();
607 append(std::move_iterator<iterator>(this->end() - NumToInsert),
608 std::move_iterator<iterator>(this->end()));
609
610 // Copy the existing elements that get replaced.
611 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
612
613 std::copy(From, To, I);
614 return I;
615 }
616
617 // Otherwise, we're inserting more elements than exist already, and we're
618 // not inserting at the end.
619
620 // Move over the elements that we're about to overwrite.
621 T *OldEnd = this->end();
622 this->set_size(this->size() + NumToInsert);
623 size_t NumOverwritten = OldEnd-I;
624 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
625
626 // Replace the overwritten part.
627 for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
628 *J = *From;
629 ++J; ++From;
630 }
631
632 // Insert the non-overwritten middle part.
633 this->uninitialized_copy(From, To, OldEnd);
634 return I;
635 }
636
637 void insert(iterator I, std::initializer_list<T> IL) {
638 insert(I, IL.begin(), IL.end());
639 }
640
641 template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) {
642 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
643 this->grow();
644 ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
645 this->set_size(this->size() + 1);
646 return this->back();
647 }
648
649 SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
650
651 SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
652
653 bool operator==(const SmallVectorImpl &RHS) const {
654 if (this->size() != RHS.size()) return false;
655 return std::equal(this->begin(), this->end(), RHS.begin());
656 }
657 bool operator!=(const SmallVectorImpl &RHS) const {
658 return !(*this == RHS);
659 }
660
661 bool operator<(const SmallVectorImpl &RHS) const {
662 return std::lexicographical_compare(this->begin(), this->end(),
663 RHS.begin(), RHS.end());
664 }
665};
666
667template <typename T>
668void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
669 if (this == &RHS) return;
670
671 // We can only avoid copying elements if neither vector is small.
672 if (!this->isSmall() && !RHS.isSmall()) {
673 std::swap(this->BeginX, RHS.BeginX);
674 std::swap(this->Size, RHS.Size);
675 std::swap(this->Capacity, RHS.Capacity);
676 return;
677 }
678 if (RHS.size() > this->capacity())
679 this->grow(RHS.size());
680 if (this->size() > RHS.capacity())
681 RHS.grow(this->size());
682
683 // Swap the shared elements.
684 size_t NumShared = this->size();
685 if (NumShared > RHS.size()) NumShared = RHS.size();
686 for (size_type i = 0; i != NumShared; ++i)
687 std::swap((*this)[i], RHS[i]);
688
689 // Copy over the extra elts.
690 if (this->size() > RHS.size()) {
691 size_t EltDiff = this->size() - RHS.size();
692 this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
693 RHS.set_size(RHS.size() + EltDiff);
694 this->destroy_range(this->begin()+NumShared, this->end());
695 this->set_size(NumShared);
696 } else if (RHS.size() > this->size()) {
697 size_t EltDiff = RHS.size() - this->size();
698 this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
699 this->set_size(this->size() + EltDiff);
700 this->destroy_range(RHS.begin()+NumShared, RHS.end());
701 RHS.set_size(NumShared);
702 }
703}
704
705template <typename T>
706SmallVectorImpl<T> &SmallVectorImpl<T>::
707 operator=(const SmallVectorImpl<T> &RHS) {
708 // Avoid self-assignment.
709 if (this == &RHS) return *this;
710
711 // If we already have sufficient space, assign the common elements, then
712 // destroy any excess.
713 size_t RHSSize = RHS.size();
714 size_t CurSize = this->size();
715 if (CurSize >= RHSSize) {
716 // Assign common elements.
717 iterator NewEnd;
718 if (RHSSize)
719 NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
720 else
721 NewEnd = this->begin();
722
723 // Destroy excess elements.
724 this->destroy_range(NewEnd, this->end());
725
726 // Trim.
727 this->set_size(RHSSize);
728 return *this;
729 }
730
731 // If we have to grow to have enough elements, destroy the current elements.
732 // This allows us to avoid copying them during the grow.
733 // FIXME: don't do this if they're efficiently moveable.
734 if (this->capacity() < RHSSize) {
735 // Destroy current elements.
736 this->destroy_range(this->begin(), this->end());
737 this->set_size(0);
738 CurSize = 0;
739 this->grow(RHSSize);
740 } else if (CurSize) {
741 // Otherwise, use assignment for the already-constructed elements.
742 std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
743 }
744
745 // Copy construct the new elements in place.
746 this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
747 this->begin()+CurSize);
748
749 // Set end.
750 this->set_size(RHSSize);
751 return *this;
752}
753
754template <typename T>
755SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
756 // Avoid self-assignment.
757 if (this == &RHS) return *this;
758
759 // If the RHS isn't small, clear this vector and then steal its buffer.
760 if (!RHS.isSmall()) {
761 this->destroy_range(this->begin(), this->end());
762 if (!this->isSmall()) free(this->begin());
763 this->BeginX = RHS.BeginX;
764 this->Size = RHS.Size;
765 this->Capacity = RHS.Capacity;
766 RHS.resetToSmall();
767 return *this;
768 }
769
770 // If we already have sufficient space, assign the common elements, then
771 // destroy any excess.
772 size_t RHSSize = RHS.size();
773 size_t CurSize = this->size();
774 if (CurSize >= RHSSize) {
775 // Assign common elements.
776 iterator NewEnd = this->begin();
777 if (RHSSize)
778 NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
779
780 // Destroy excess elements and trim the bounds.
781 this->destroy_range(NewEnd, this->end());
782 this->set_size(RHSSize);
783
784 // Clear the RHS.
785 RHS.clear();
786
787 return *this;
788 }
789
790 // If we have to grow to have enough elements, destroy the current elements.
791 // This allows us to avoid copying them during the grow.
792 // FIXME: this may not actually make any sense if we can efficiently move
793 // elements.
794 if (this->capacity() < RHSSize) {
795 // Destroy current elements.
796 this->destroy_range(this->begin(), this->end());
797 this->set_size(0);
798 CurSize = 0;
799 this->grow(RHSSize);
800 } else if (CurSize) {
801 // Otherwise, use assignment for the already-constructed elements.
802 std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
803 }
804
805 // Move-construct the new elements in place.
806 this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
807 this->begin()+CurSize);
808
809 // Set end.
810 this->set_size(RHSSize);
811
812 RHS.clear();
813 return *this;
814}
815
816/// Storage for the SmallVector elements. This is specialized for the N=0 case
817/// to avoid allocating unnecessary storage.
818template <typename T, unsigned N>
819struct SmallVectorStorage {
820 AlignedCharArrayUnion<T> InlineElts[N];
821};
822
823/// We need the storage to be properly aligned even for small-size of 0 so that
824/// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
825/// well-defined.
826template <typename T> struct alignas(alignof(T)) SmallVectorStorage<T, 0> {};
827
828/// This is a 'vector' (really, a variable-sized array), optimized
829/// for the case when the array is small. It contains some number of elements
830/// in-place, which allows it to avoid heap allocation when the actual number of
831/// elements is below that threshold. This allows normal "small" cases to be
832/// fast without losing generality for large inputs.
833///
834/// Note that this does not attempt to be exception safe.
835///
836template <typename T, unsigned N>
837class SmallVector : public SmallVectorImpl<T>, SmallVectorStorage<T, N> {
838public:
839 SmallVector() : SmallVectorImpl<T>(N) {}
840
841 ~SmallVector() {
842 // Destroy the constructed elements in the vector.
843 this->destroy_range(this->begin(), this->end());
844 }
845
846 explicit SmallVector(size_t Size, const T &Value = T())
847 : SmallVectorImpl<T>(N) {
848 this->assign(Size, Value);
849 }
850
851 template <typename ItTy,
852 typename = typename std::enable_if<std::is_convertible<
853 typename std::iterator_traits<ItTy>::iterator_category,
854 std::input_iterator_tag>::value>::type>
855 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
856 this->append(S, E);
857 }
858
859 template <typename RangeTy>
860 explicit SmallVector(const iterator_range<RangeTy> &R)
861 : SmallVectorImpl<T>(N) {
862 this->append(R.begin(), R.end());
863 }
864
865 SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
866 this->assign(IL);
867 }
868
869 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
870 if (!RHS.empty())
871 SmallVectorImpl<T>::operator=(RHS);
872 }
873
874 const SmallVector &operator=(const SmallVector &RHS) {
875 SmallVectorImpl<T>::operator=(RHS);
876 return *this;
877 }
878
879 SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
880 if (!RHS.empty())
881 SmallVectorImpl<T>::operator=(::std::move(RHS));
882 }
883
884 SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
885 if (!RHS.empty())
886 SmallVectorImpl<T>::operator=(::std::move(RHS));
887 }
888
889 const SmallVector &operator=(SmallVector &&RHS) {
890 SmallVectorImpl<T>::operator=(::std::move(RHS));
891 return *this;
892 }
893
894 const SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
895 SmallVectorImpl<T>::operator=(::std::move(RHS));
896 return *this;
897 }
898
899 const SmallVector &operator=(std::initializer_list<T> IL) {
900 this->assign(IL);
901 return *this;
902 }
903};
904
905template <typename T, unsigned N>
906inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
907 return X.capacity_in_bytes();
908}
909
910/// Given a range of type R, iterate the entire range and return a
911/// SmallVector with elements of the vector. This is useful, for example,
912/// when you want to iterate a range and then sort the results.
913template <unsigned Size, typename R>
914SmallVector<typename std::remove_const<typename std::remove_reference<
915 decltype(*std::begin(std::declval<R &>()))>::type>::type,
916 Size>
917to_vector(R &&Range) {
918 return {std::begin(Range), std::end(Range)};
919}
920
921} // end namespace llvm
922
923namespace std {
924
925 /// Implement std::swap in terms of SmallVector swap.
926 template<typename T>
927 inline void
928 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
929 LHS.swap(RHS);
930 }
931
932 /// Implement std::swap in terms of SmallVector swap.
933 template<typename T, unsigned N>
934 inline void
935 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
936 LHS.swap(RHS);
937 }
938
939} // end namespace std
940
941#endif // LLVM_ADT_SMALLVECTOR_H

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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/Attr.h"
19#include "clang/AST/Availability.h"
20#include "clang/AST/ComparisonCategories.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExternalASTSource.h"
27#include "clang/AST/LocInfoType.h"
28#include "clang/AST/MangleNumberingContext.h"
29#include "clang/AST/NSAPI.h"
30#include "clang/AST/PrettyPrinter.h"
31#include "clang/AST/StmtCXX.h"
32#include "clang/AST/TypeLoc.h"
33#include "clang/AST/TypeOrdering.h"
34#include "clang/Basic/BitmaskEnum.h"
35#include "clang/Basic/ExpressionTraits.h"
36#include "clang/Basic/Module.h"
37#include "clang/Basic/OpenMPKinds.h"
38#include "clang/Basic/PragmaKinds.h"
39#include "clang/Basic/Specifiers.h"
40#include "clang/Basic/TemplateKinds.h"
41#include "clang/Basic/TypeTraits.h"
42#include "clang/Sema/AnalysisBasedWarnings.h"
43#include "clang/Sema/CleanupInfo.h"
44#include "clang/Sema/DeclSpec.h"
45#include "clang/Sema/ExternalSemaSource.h"
46#include "clang/Sema/IdentifierResolver.h"
47#include "clang/Sema/ObjCMethodList.h"
48#include "clang/Sema/Ownership.h"
49#include "clang/Sema/Scope.h"
50#include "clang/Sema/SemaConcept.h"
51#include "clang/Sema/TypoCorrection.h"
52#include "clang/Sema/Weak.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/Optional.h"
55#include "llvm/ADT/SetVector.h"
56#include "llvm/ADT/SmallBitVector.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/SmallVector.h"
59#include "llvm/ADT/TinyPtrVector.h"
60#include "llvm/Frontend/OpenMP/OMPConstants.h"
61#include <deque>
62#include <memory>
63#include <string>
64#include <tuple>
65#include <vector>
66
67namespace llvm {
68 class APSInt;
69 template <typename ValueT> struct DenseMapInfo;
70 template <typename ValueT, typename ValueInfoT> class DenseSet;
71 class SmallBitVector;
72 struct InlineAsmIdentifierInfo;
73}
74
75namespace clang {
76 class ADLResult;
77 class ASTConsumer;
78 class ASTContext;
79 class ASTMutationListener;
80 class ASTReader;
81 class ASTWriter;
82 class ArrayType;
83 class ParsedAttr;
84 class BindingDecl;
85 class BlockDecl;
86 class CapturedDecl;
87 class CXXBasePath;
88 class CXXBasePaths;
89 class CXXBindTemporaryExpr;
90 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
91 class CXXConstructorDecl;
92 class CXXConversionDecl;
93 class CXXDeleteExpr;
94 class CXXDestructorDecl;
95 class CXXFieldCollector;
96 class CXXMemberCallExpr;
97 class CXXMethodDecl;
98 class CXXScopeSpec;
99 class CXXTemporary;
100 class CXXTryStmt;
101 class CallExpr;
102 class ClassTemplateDecl;
103 class ClassTemplatePartialSpecializationDecl;
104 class ClassTemplateSpecializationDecl;
105 class VarTemplatePartialSpecializationDecl;
106 class CodeCompleteConsumer;
107 class CodeCompletionAllocator;
108 class CodeCompletionTUInfo;
109 class CodeCompletionResult;
110 class CoroutineBodyStmt;
111 class Decl;
112 class DeclAccessPair;
113 class DeclContext;
114 class DeclRefExpr;
115 class DeclaratorDecl;
116 class DeducedTemplateArgument;
117 class DependentDiagnostic;
118 class DesignatedInitExpr;
119 class Designation;
120 class EnableIfAttr;
121 class EnumConstantDecl;
122 class Expr;
123 class ExtVectorType;
124 class FormatAttr;
125 class FriendDecl;
126 class FunctionDecl;
127 class FunctionProtoType;
128 class FunctionTemplateDecl;
129 class ImplicitConversionSequence;
130 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
131 class InitListExpr;
132 class InitializationKind;
133 class InitializationSequence;
134 class InitializedEntity;
135 class IntegerLiteral;
136 class LabelStmt;
137 class LambdaExpr;
138 class LangOptions;
139 class LocalInstantiationScope;
140 class LookupResult;
141 class MacroInfo;
142 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
143 class ModuleLoader;
144 class MultiLevelTemplateArgumentList;
145 class NamedDecl;
146 class ObjCCategoryDecl;
147 class ObjCCategoryImplDecl;
148 class ObjCCompatibleAliasDecl;
149 class ObjCContainerDecl;
150 class ObjCImplDecl;
151 class ObjCImplementationDecl;
152 class ObjCInterfaceDecl;
153 class ObjCIvarDecl;
154 template <class T> class ObjCList;
155 class ObjCMessageExpr;
156 class ObjCMethodDecl;
157 class ObjCPropertyDecl;
158 class ObjCProtocolDecl;
159 class OMPThreadPrivateDecl;
160 class OMPRequiresDecl;
161 class OMPDeclareReductionDecl;
162 class OMPDeclareSimdDecl;
163 class OMPClause;
164 struct OMPVarListLocTy;
165 struct OverloadCandidate;
166 enum class OverloadCandidateParamOrder : char;
167 enum OverloadCandidateRewriteKind : unsigned;
168 class OverloadCandidateSet;
169 class OverloadExpr;
170 class ParenListExpr;
171 class ParmVarDecl;
172 class Preprocessor;
173 class PseudoDestructorTypeStorage;
174 class PseudoObjectExpr;
175 class QualType;
176 class StandardConversionSequence;
177 class Stmt;
178 class StringLiteral;
179 class SwitchStmt;
180 class TemplateArgument;
181 class TemplateArgumentList;
182 class TemplateArgumentLoc;
183 class TemplateDecl;
184 class TemplateInstantiationCallback;
185 class TemplateParameterList;
186 class TemplatePartialOrderingContext;
187 class TemplateTemplateParmDecl;
188 class Token;
189 class TypeAliasDecl;
190 class TypedefDecl;
191 class TypedefNameDecl;
192 class TypeLoc;
193 class TypoCorrectionConsumer;
194 class UnqualifiedId;
195 class UnresolvedLookupExpr;
196 class UnresolvedMemberExpr;
197 class UnresolvedSetImpl;
198 class UnresolvedSetIterator;
199 class UsingDecl;
200 class UsingShadowDecl;
201 class ValueDecl;
202 class VarDecl;
203 class VarTemplateSpecializationDecl;
204 class VisibilityAttr;
205 class VisibleDeclConsumer;
206 class IndirectFieldDecl;
207 struct DeductionFailureInfo;
208 class TemplateSpecCandidateSet;
209
210namespace sema {
211 class AccessedEntity;
212 class BlockScopeInfo;
213 class Capture;
214 class CapturedRegionScopeInfo;
215 class CapturingScopeInfo;
216 class CompoundScopeInfo;
217 class DelayedDiagnostic;
218 class DelayedDiagnosticPool;
219 class FunctionScopeInfo;
220 class LambdaScopeInfo;
221 class PossiblyUnreachableDiag;
222 class SemaPPCallbacks;
223 class TemplateDeductionInfo;
224}
225
226namespace threadSafety {
227 class BeforeSet;
228 void threadSafetyCleanup(BeforeSet* Cache);
229}
230
231// FIXME: No way to easily map from TemplateTypeParmTypes to
232// TemplateTypeParmDecls, so we have this horrible PointerUnion.
233typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
234 SourceLocation> UnexpandedParameterPack;
235
236/// Describes whether we've seen any nullability information for the given
237/// file.
238struct FileNullability {
239 /// The first pointer declarator (of any pointer kind) in the file that does
240 /// not have a corresponding nullability annotation.
241 SourceLocation PointerLoc;
242
243 /// The end location for the first pointer declarator in the file. Used for
244 /// placing fix-its.
245 SourceLocation PointerEndLoc;
246
247 /// Which kind of pointer declarator we saw.
248 uint8_t PointerKind;
249
250 /// Whether we saw any type nullability annotations in the given file.
251 bool SawTypeNullability = false;
252};
253
254/// A mapping from file IDs to a record of whether we've seen nullability
255/// information in that file.
256class FileNullabilityMap {
257 /// A mapping from file IDs to the nullability information for each file ID.
258 llvm::DenseMap<FileID, FileNullability> Map;
259
260 /// A single-element cache based on the file ID.
261 struct {
262 FileID File;
263 FileNullability Nullability;
264 } Cache;
265
266public:
267 FileNullability &operator[](FileID file) {
268 // Check the single-element cache.
269 if (file == Cache.File)
270 return Cache.Nullability;
271
272 // It's not in the single-element cache; flush the cache if we have one.
273 if (!Cache.File.isInvalid()) {
274 Map[Cache.File] = Cache.Nullability;
275 }
276
277 // Pull this entry into the cache.
278 Cache.File = file;
279 Cache.Nullability = Map[file];
280 return Cache.Nullability;
281 }
282};
283
284/// Keeps track of expected type during expression parsing. The type is tied to
285/// a particular token, all functions that update or consume the type take a
286/// start location of the token they are looking at as a parameter. This allows
287/// to avoid updating the type on hot paths in the parser.
288class PreferredTypeBuilder {
289public:
290 PreferredTypeBuilder() = default;
291 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
292
293 void enterCondition(Sema &S, SourceLocation Tok);
294 void enterReturn(Sema &S, SourceLocation Tok);
295 void enterVariableInit(SourceLocation Tok, Decl *D);
296 /// Computing a type for the function argument may require running
297 /// overloading, so we postpone its computation until it is actually needed.
298 ///
299 /// Clients should be very careful when using this funciton, as it stores a
300 /// function_ref, clients should make sure all calls to get() with the same
301 /// location happen while function_ref is alive.
302 void enterFunctionArgument(SourceLocation Tok,
303 llvm::function_ref<QualType()> ComputeType);
304
305 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
306 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
307 SourceLocation OpLoc);
308 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
309 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
310 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
311 /// Handles all type casts, including C-style cast, C++ casts, etc.
312 void enterTypeCast(SourceLocation Tok, QualType CastType);
313
314 QualType get(SourceLocation Tok) const {
315 if (Tok != ExpectedLoc)
316 return QualType();
317 if (!Type.isNull())
318 return Type;
319 if (ComputeType)
320 return ComputeType();
321 return QualType();
322 }
323
324private:
325 /// Start position of a token for which we store expected type.
326 SourceLocation ExpectedLoc;
327 /// Expected type for a token starting at ExpectedLoc.
328 QualType Type;
329 /// A function to compute expected type at ExpectedLoc. It is only considered
330 /// if Type is null.
331 llvm::function_ref<QualType()> ComputeType;
332};
333
334/// Sema - This implements semantic analysis and AST building for C.
335class Sema final {
336 Sema(const Sema &) = delete;
337 void operator=(const Sema &) = delete;
338
339 /// A key method to reduce duplicate debug info from Sema.
340 virtual void anchor();
341
342 ///Source of additional semantic information.
343 ExternalSemaSource *ExternalSource;
344
345 ///Whether Sema has generated a multiplexer and has to delete it.
346 bool isMultiplexExternalSource;
347
348 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
349
350 bool isVisibleSlow(const NamedDecl *D);
351
352 /// Determine whether two declarations should be linked together, given that
353 /// the old declaration might not be visible and the new declaration might
354 /// not have external linkage.
355 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
356 const NamedDecl *New) {
357 if (isVisible(Old))
358 return true;
359 // See comment in below overload for why it's safe to compute the linkage
360 // of the new declaration here.
361 if (New->isExternallyDeclarable()) {
362 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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 363, __PRETTY_FUNCTION__))
363 "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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 363, __PRETTY_FUNCTION__))
;
364 return true;
365 }
366 return false;
367 }
368 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
369
370 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
371 QualType ResultTy,
372 ArrayRef<QualType> Args);
373
374public:
375 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
376 typedef OpaquePtr<TemplateName> TemplateTy;
377 typedef OpaquePtr<QualType> TypeTy;
378
379 OpenCLOptions OpenCLFeatures;
380 FPOptions FPFeatures;
381
382 const LangOptions &LangOpts;
383 Preprocessor &PP;
384 ASTContext &Context;
385 ASTConsumer &Consumer;
386 DiagnosticsEngine &Diags;
387 SourceManager &SourceMgr;
388
389 /// Flag indicating whether or not to collect detailed statistics.
390 bool CollectStats;
391
392 /// Code-completion consumer.
393 CodeCompleteConsumer *CodeCompleter;
394
395 /// CurContext - This is the current declaration context of parsing.
396 DeclContext *CurContext;
397
398 /// Generally null except when we temporarily switch decl contexts,
399 /// like in \see ActOnObjCTemporaryExitContainerContext.
400 DeclContext *OriginalLexicalContext;
401
402 /// VAListTagName - The declaration name corresponding to __va_list_tag.
403 /// This is used as part of a hack to omit that class from ADL results.
404 DeclarationName VAListTagName;
405
406 bool MSStructPragmaOn; // True when \#pragma ms_struct on
407
408 /// Controls member pointer representation format under the MS ABI.
409 LangOptions::PragmaMSPointersToMembersKind
410 MSPointerToMemberRepresentationMethod;
411
412 /// Stack of active SEH __finally scopes. Can be empty.
413 SmallVector<Scope*, 2> CurrentSEHFinally;
414
415 /// Source location for newly created implicit MSInheritanceAttrs
416 SourceLocation ImplicitMSInheritanceAttrLoc;
417
418 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
419 /// `TransformTypos` in order to keep track of any TypoExprs that are created
420 /// recursively during typo correction and wipe them away if the correction
421 /// fails.
422 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
423
424 /// pragma clang section kind
425 enum PragmaClangSectionKind {
426 PCSK_Invalid = 0,
427 PCSK_BSS = 1,
428 PCSK_Data = 2,
429 PCSK_Rodata = 3,
430 PCSK_Text = 4,
431 PCSK_Relro = 5
432 };
433
434 enum PragmaClangSectionAction {
435 PCSA_Set = 0,
436 PCSA_Clear = 1
437 };
438
439 struct PragmaClangSection {
440 std::string SectionName;
441 bool Valid = false;
442 SourceLocation PragmaLocation;
443
444 void Act(SourceLocation PragmaLocation,
445 PragmaClangSectionAction Action,
446 StringLiteral* Name);
447 };
448
449 PragmaClangSection PragmaClangBSSSection;
450 PragmaClangSection PragmaClangDataSection;
451 PragmaClangSection PragmaClangRodataSection;
452 PragmaClangSection PragmaClangRelroSection;
453 PragmaClangSection PragmaClangTextSection;
454
455 enum PragmaMsStackAction {
456 PSK_Reset = 0x0, // #pragma ()
457 PSK_Set = 0x1, // #pragma (value)
458 PSK_Push = 0x2, // #pragma (push[, id])
459 PSK_Pop = 0x4, // #pragma (pop[, id])
460 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
461 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
462 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
463 };
464
465 template<typename ValueType>
466 struct PragmaStack {
467 struct Slot {
468 llvm::StringRef StackSlotLabel;
469 ValueType Value;
470 SourceLocation PragmaLocation;
471 SourceLocation PragmaPushLocation;
472 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
473 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
474 : StackSlotLabel(StackSlotLabel), Value(Value),
475 PragmaLocation(PragmaLocation),
476 PragmaPushLocation(PragmaPushLocation) {}
477 };
478 void Act(SourceLocation PragmaLocation,
479 PragmaMsStackAction Action,
480 llvm::StringRef StackSlotLabel,
481 ValueType Value);
482
483 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
484 // method body to restore the stacks on exit, so it works like this:
485 //
486 // struct S {
487 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
488 // void Method {}
489 // #pragma <name>(pop, InternalPragmaSlot)
490 // };
491 //
492 // It works even with #pragma vtordisp, although MSVC doesn't support
493 // #pragma vtordisp(push [, id], n)
494 // syntax.
495 //
496 // Push / pop a named sentinel slot.
497 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
498 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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 499, __PRETTY_FUNCTION__))
499 "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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 499, __PRETTY_FUNCTION__))
;
500 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
501 }
502
503 // Constructors.
504 explicit PragmaStack(const ValueType &Default)
505 : DefaultValue(Default), CurrentValue(Default) {}
506
507 bool hasValue() const { return CurrentValue != DefaultValue; }
508
509 SmallVector<Slot, 2> Stack;
510 ValueType DefaultValue; // Value used for PSK_Reset action.
511 ValueType CurrentValue;
512 SourceLocation CurrentPragmaLocation;
513 };
514 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
515 // we shouldn't do so if they're in a module).
516
517 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
518 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
519 ///
520 /// 0: Suppress all vtordisps
521 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
522 /// structors
523 /// 2: Always insert vtordisps to support RTTI on partially constructed
524 /// objects
525 PragmaStack<MSVtorDispMode> VtorDispStack;
526 // #pragma pack.
527 // Sentinel to represent when the stack is set to mac68k alignment.
528 static const unsigned kMac68kAlignmentSentinel = ~0U;
529 PragmaStack<unsigned> PackStack;
530 // The current #pragma pack values and locations at each #include.
531 struct PackIncludeState {
532 unsigned CurrentValue;
533 SourceLocation CurrentPragmaLocation;
534 bool HasNonDefaultValue, ShouldWarnOnInclude;
535 };
536 SmallVector<PackIncludeState, 8> PackIncludeStack;
537 // Segment #pragmas.
538 PragmaStack<StringLiteral *> DataSegStack;
539 PragmaStack<StringLiteral *> BSSSegStack;
540 PragmaStack<StringLiteral *> ConstSegStack;
541 PragmaStack<StringLiteral *> CodeSegStack;
542
543 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
544 // Actions should be performed only if we enter / exit a C++ method body.
545 class PragmaStackSentinelRAII {
546 public:
547 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
548 ~PragmaStackSentinelRAII();
549
550 private:
551 Sema &S;
552 StringRef SlotLabel;
553 bool ShouldAct;
554 };
555
556 /// A mapping that describes the nullability we've seen in each header file.
557 FileNullabilityMap NullabilityMap;
558
559 /// Last section used with #pragma init_seg.
560 StringLiteral *CurInitSeg;
561 SourceLocation CurInitSegLoc;
562
563 /// VisContext - Manages the stack for \#pragma GCC visibility.
564 void *VisContext; // Really a "PragmaVisStack*"
565
566 /// This an attribute introduced by \#pragma clang attribute.
567 struct PragmaAttributeEntry {
568 SourceLocation Loc;
569 ParsedAttr *Attribute;
570 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
571 bool IsUsed;
572 };
573
574 /// A push'd group of PragmaAttributeEntries.
575 struct PragmaAttributeGroup {
576 /// The location of the push attribute.
577 SourceLocation Loc;
578 /// The namespace of this push group.
579 const IdentifierInfo *Namespace;
580 SmallVector<PragmaAttributeEntry, 2> Entries;
581 };
582
583 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
584
585 /// The declaration that is currently receiving an attribute from the
586 /// #pragma attribute stack.
587 const Decl *PragmaAttributeCurrentTargetDecl;
588
589 /// This represents the last location of a "#pragma clang optimize off"
590 /// directive if such a directive has not been closed by an "on" yet. If
591 /// optimizations are currently "on", this is set to an invalid location.
592 SourceLocation OptimizeOffPragmaLocation;
593
594 /// Flag indicating if Sema is building a recovery call expression.
595 ///
596 /// This flag is used to avoid building recovery call expressions
597 /// if Sema is already doing so, which would cause infinite recursions.
598 bool IsBuildingRecoveryCallExpr;
599
600 /// Used to control the generation of ExprWithCleanups.
601 CleanupInfo Cleanup;
602
603 /// ExprCleanupObjects - This is the stack of objects requiring
604 /// cleanup that are created by the current full expression. The
605 /// element type here is ExprWithCleanups::Object.
606 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
607
608 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
609 /// to a variable (constant) that may or may not be odr-used in this Expr, and
610 /// we won't know until all lvalue-to-rvalue and discarded value conversions
611 /// have been applied to all subexpressions of the enclosing full expression.
612 /// This is cleared at the end of each full expression.
613 using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
614 MaybeODRUseExprSet MaybeODRUseExprs;
615
616 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
617
618 /// Stack containing information about each of the nested
619 /// function, block, and method scopes that are currently active.
620 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
621
622 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
623 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
624 ExtVectorDeclsType;
625
626 /// ExtVectorDecls - This is a list all the extended vector types. This allows
627 /// us to associate a raw vector type with one of the ext_vector type names.
628 /// This is only necessary for issuing pretty diagnostics.
629 ExtVectorDeclsType ExtVectorDecls;
630
631 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
632 std::unique_ptr<CXXFieldCollector> FieldCollector;
633
634 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
635
636 /// Set containing all declared private fields that are not used.
637 NamedDeclSetType UnusedPrivateFields;
638
639 /// Set containing all typedefs that are likely unused.
640 llvm::SmallSetVector<const TypedefNameDecl *, 4>
641 UnusedLocalTypedefNameCandidates;
642
643 /// Delete-expressions to be analyzed at the end of translation unit
644 ///
645 /// This list contains class members, and locations of delete-expressions
646 /// that could not be proven as to whether they mismatch with new-expression
647 /// used in initializer of the field.
648 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
649 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
650 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
651
652 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
653
654 /// PureVirtualClassDiagSet - a set of class declarations which we have
655 /// emitted a list of pure virtual functions. Used to prevent emitting the
656 /// same list more than once.
657 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
658
659 /// ParsingInitForAutoVars - a set of declarations with auto types for which
660 /// we are currently parsing the initializer.
661 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
662
663 /// Look for a locally scoped extern "C" declaration by the given name.
664 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
665
666 typedef LazyVector<VarDecl *, ExternalSemaSource,
667 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
668 TentativeDefinitionsType;
669
670 /// All the tentative definitions encountered in the TU.
671 TentativeDefinitionsType TentativeDefinitions;
672
673 /// All the external declarations encoutered and used in the TU.
674 SmallVector<VarDecl *, 4> ExternalDeclarations;
675
676 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
677 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
678 UnusedFileScopedDeclsType;
679
680 /// The set of file scoped decls seen so far that have not been used
681 /// and must warn if not used. Only contains the first declaration.
682 UnusedFileScopedDeclsType UnusedFileScopedDecls;
683
684 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
685 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
686 DelegatingCtorDeclsType;
687
688 /// All the delegating constructors seen so far in the file, used for
689 /// cycle detection at the end of the TU.
690 DelegatingCtorDeclsType DelegatingCtorDecls;
691
692 /// All the overriding functions seen during a class definition
693 /// that had their exception spec checks delayed, plus the overridden
694 /// function.
695 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
696 DelayedOverridingExceptionSpecChecks;
697
698 /// All the function redeclarations seen during a class definition that had
699 /// their exception spec checks delayed, plus the prior declaration they
700 /// should be checked against. Except during error recovery, the new decl
701 /// should always be a friend declaration, as that's the only valid way to
702 /// redeclare a special member before its class is complete.
703 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
704 DelayedEquivalentExceptionSpecChecks;
705
706 typedef llvm::MapVector<const FunctionDecl *,
707 std::unique_ptr<LateParsedTemplate>>
708 LateParsedTemplateMapT;
709 LateParsedTemplateMapT LateParsedTemplateMap;
710
711 /// Callback to the parser to parse templated functions when needed.
712 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
713 typedef void LateTemplateParserCleanupCB(void *P);
714 LateTemplateParserCB *LateTemplateParser;
715 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
716 void *OpaqueParser;
717
718 void SetLateTemplateParser(LateTemplateParserCB *LTP,
719 LateTemplateParserCleanupCB *LTPCleanup,
720 void *P) {
721 LateTemplateParser = LTP;
722 LateTemplateParserCleanup = LTPCleanup;
723 OpaqueParser = P;
724 }
725
726 class DelayedDiagnostics;
727
728 class DelayedDiagnosticsState {
729 sema::DelayedDiagnosticPool *SavedPool;
730 friend class Sema::DelayedDiagnostics;
731 };
732 typedef DelayedDiagnosticsState ParsingDeclState;
733 typedef DelayedDiagnosticsState ProcessingContextState;
734
735 /// A class which encapsulates the logic for delaying diagnostics
736 /// during parsing and other processing.
737 class DelayedDiagnostics {
738 /// The current pool of diagnostics into which delayed
739 /// diagnostics should go.
740 sema::DelayedDiagnosticPool *CurPool;
741
742 public:
743 DelayedDiagnostics() : CurPool(nullptr) {}
744
745 /// Adds a delayed diagnostic.
746 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
747
748 /// Determines whether diagnostics should be delayed.
749 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
750
751 /// Returns the current delayed-diagnostics pool.
752 sema::DelayedDiagnosticPool *getCurrentPool() const {
753 return CurPool;
754 }
755
756 /// Enter a new scope. Access and deprecation diagnostics will be
757 /// collected in this pool.
758 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
759 DelayedDiagnosticsState state;
760 state.SavedPool = CurPool;
761 CurPool = &pool;
762 return state;
763 }
764
765 /// Leave a delayed-diagnostic state that was previously pushed.
766 /// Do not emit any of the diagnostics. This is performed as part
767 /// of the bookkeeping of popping a pool "properly".
768 void popWithoutEmitting(DelayedDiagnosticsState state) {
769 CurPool = state.SavedPool;
770 }
771
772 /// Enter a new scope where access and deprecation diagnostics are
773 /// not delayed.
774 DelayedDiagnosticsState pushUndelayed() {
775 DelayedDiagnosticsState state;
776 state.SavedPool = CurPool;
777 CurPool = nullptr;
778 return state;
779 }
780
781 /// Undo a previous pushUndelayed().
782 void popUndelayed(DelayedDiagnosticsState state) {
783 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 783, __PRETTY_FUNCTION__))
;
784 CurPool = state.SavedPool;
785 }
786 } DelayedDiagnostics;
787
788 /// A RAII object to temporarily push a declaration context.
789 class ContextRAII {
790 private:
791 Sema &S;
792 DeclContext *SavedContext;
793 ProcessingContextState SavedContextState;
794 QualType SavedCXXThisTypeOverride;
795
796 public:
797 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
798 : S(S), SavedContext(S.CurContext),
799 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
800 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
801 {
802 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 802, __PRETTY_FUNCTION__))
;
803 S.CurContext = ContextToPush;
804 if (NewThisContext)
805 S.CXXThisTypeOverride = QualType();
806 }
807
808 void pop() {
809 if (!SavedContext) return;
810 S.CurContext = SavedContext;
811 S.DelayedDiagnostics.popUndelayed(SavedContextState);
812 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
813 SavedContext = nullptr;
814 }
815
816 ~ContextRAII() {
817 pop();
818 }
819 };
820
821 /// Used to change context to isConstantEvaluated without pushing a heavy
822 /// ExpressionEvaluationContextRecord object.
823 bool isConstantEvaluatedOverride;
824
825 bool isConstantEvaluated() {
826 return ExprEvalContexts.back().isConstantEvaluated() ||
827 isConstantEvaluatedOverride;
828 }
829
830 /// RAII object to handle the state changes required to synthesize
831 /// a function body.
832 class SynthesizedFunctionScope {
833 Sema &S;
834 Sema::ContextRAII SavedContext;
835 bool PushedCodeSynthesisContext = false;
836
837 public:
838 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
839 : S(S), SavedContext(S, DC) {
840 S.PushFunctionScope();
841 S.PushExpressionEvaluationContext(
842 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
843 if (auto *FD = dyn_cast<FunctionDecl>(DC))
844 FD->setWillHaveBody(true);
845 else
846 assert(isa<ObjCMethodDecl>(DC))((isa<ObjCMethodDecl>(DC)) ? static_cast<void> (0
) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 846, __PRETTY_FUNCTION__))
;
847 }
848
849 void addContextNote(SourceLocation UseLoc) {
850 assert(!PushedCodeSynthesisContext)((!PushedCodeSynthesisContext) ? static_cast<void> (0) :
__assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 850, __PRETTY_FUNCTION__))
;
851
852 Sema::CodeSynthesisContext Ctx;
853 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
854 Ctx.PointOfInstantiation = UseLoc;
855 Ctx.Entity = cast<Decl>(S.CurContext);
856 S.pushCodeSynthesisContext(Ctx);
857
858 PushedCodeSynthesisContext = true;
859 }
860
861 ~SynthesizedFunctionScope() {
862 if (PushedCodeSynthesisContext)
863 S.popCodeSynthesisContext();
864 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
865 FD->setWillHaveBody(false);
866 S.PopExpressionEvaluationContext();
867 S.PopFunctionScopeInfo();
868 }
869 };
870
871 /// WeakUndeclaredIdentifiers - Identifiers contained in
872 /// \#pragma weak before declared. rare. may alias another
873 /// identifier, declared or undeclared
874 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
875
876 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
877 /// \#pragma redefine_extname before declared. Used in Solaris system headers
878 /// to define functions that occur in multiple standards to call the version
879 /// in the currently selected standard.
880 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
881
882
883 /// Load weak undeclared identifiers from the external source.
884 void LoadExternalWeakUndeclaredIdentifiers();
885
886 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
887 /// \#pragma weak during processing of other Decls.
888 /// I couldn't figure out a clean way to generate these in-line, so
889 /// we store them here and handle separately -- which is a hack.
890 /// It would be best to refactor this.
891 SmallVector<Decl*,2> WeakTopLevelDecl;
892
893 IdentifierResolver IdResolver;
894
895 /// Translation Unit Scope - useful to Objective-C actions that need
896 /// to lookup file scope declarations in the "ordinary" C decl namespace.
897 /// For example, user-defined classes, built-in "id" type, etc.
898 Scope *TUScope;
899
900 /// The C++ "std" namespace, where the standard library resides.
901 LazyDeclPtr StdNamespace;
902
903 /// The C++ "std::bad_alloc" class, which is defined by the C++
904 /// standard library.
905 LazyDeclPtr StdBadAlloc;
906
907 /// The C++ "std::align_val_t" enum class, which is defined by the C++
908 /// standard library.
909 LazyDeclPtr StdAlignValT;
910
911 /// The C++ "std::experimental" namespace, where the experimental parts
912 /// of the standard library resides.
913 NamespaceDecl *StdExperimentalNamespaceCache;
914
915 /// The C++ "std::initializer_list" template, which is defined in
916 /// \<initializer_list>.
917 ClassTemplateDecl *StdInitializerList;
918
919 /// The C++ "std::coroutine_traits" template, which is defined in
920 /// \<coroutine_traits>
921 ClassTemplateDecl *StdCoroutineTraitsCache;
922
923 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
924 RecordDecl *CXXTypeInfoDecl;
925
926 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
927 RecordDecl *MSVCGuidDecl;
928
929 /// Caches identifiers/selectors for NSFoundation APIs.
930 std::unique_ptr<NSAPI> NSAPIObj;
931
932 /// The declaration of the Objective-C NSNumber class.
933 ObjCInterfaceDecl *NSNumberDecl;
934
935 /// The declaration of the Objective-C NSValue class.
936 ObjCInterfaceDecl *NSValueDecl;
937
938 /// Pointer to NSNumber type (NSNumber *).
939 QualType NSNumberPointer;
940
941 /// Pointer to NSValue type (NSValue *).
942 QualType NSValuePointer;
943
944 /// The Objective-C NSNumber methods used to create NSNumber literals.
945 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
946
947 /// The declaration of the Objective-C NSString class.
948 ObjCInterfaceDecl *NSStringDecl;
949
950 /// Pointer to NSString type (NSString *).
951 QualType NSStringPointer;
952
953 /// The declaration of the stringWithUTF8String: method.
954 ObjCMethodDecl *StringWithUTF8StringMethod;
955
956 /// The declaration of the valueWithBytes:objCType: method.
957 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
958
959 /// The declaration of the Objective-C NSArray class.
960 ObjCInterfaceDecl *NSArrayDecl;
961
962 /// The declaration of the arrayWithObjects:count: method.
963 ObjCMethodDecl *ArrayWithObjectsMethod;
964
965 /// The declaration of the Objective-C NSDictionary class.
966 ObjCInterfaceDecl *NSDictionaryDecl;
967
968 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
969 ObjCMethodDecl *DictionaryWithObjectsMethod;
970
971 /// id<NSCopying> type.
972 QualType QIDNSCopying;
973
974 /// will hold 'respondsToSelector:'
975 Selector RespondsToSelectorSel;
976
977 /// A flag to remember whether the implicit forms of operator new and delete
978 /// have been declared.
979 bool GlobalNewDeleteDeclared;
980
981 /// A flag to indicate that we're in a context that permits abstract
982 /// references to fields. This is really a
983 bool AllowAbstractFieldReference;
984
985 /// Describes how the expressions currently being parsed are
986 /// evaluated at run-time, if at all.
987 enum class ExpressionEvaluationContext {
988 /// The current expression and its subexpressions occur within an
989 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
990 /// \c sizeof, where the type of the expression may be significant but
991 /// no code will be generated to evaluate the value of the expression at
992 /// run time.
993 Unevaluated,
994
995 /// The current expression occurs within a braced-init-list within
996 /// an unevaluated operand. This is mostly like a regular unevaluated
997 /// context, except that we still instantiate constexpr functions that are
998 /// referenced here so that we can perform narrowing checks correctly.
999 UnevaluatedList,
1000
1001 /// The current expression occurs within a discarded statement.
1002 /// This behaves largely similarly to an unevaluated operand in preventing
1003 /// definitions from being required, but not in other ways.
1004 DiscardedStatement,
1005
1006 /// The current expression occurs within an unevaluated
1007 /// operand that unconditionally permits abstract references to
1008 /// fields, such as a SIZE operator in MS-style inline assembly.
1009 UnevaluatedAbstract,
1010
1011 /// The current context is "potentially evaluated" in C++11 terms,
1012 /// but the expression is evaluated at compile-time (like the values of
1013 /// cases in a switch statement).
1014 ConstantEvaluated,
1015
1016 /// The current expression is potentially evaluated at run time,
1017 /// which means that code may be generated to evaluate the value of the
1018 /// expression at run time.
1019 PotentiallyEvaluated,
1020
1021 /// The current expression is potentially evaluated, but any
1022 /// declarations referenced inside that expression are only used if
1023 /// in fact the current expression is used.
1024 ///
1025 /// This value is used when parsing default function arguments, for which
1026 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1027 /// through varargs) but do not want to mark declarations as "referenced"
1028 /// until the default argument is used.
1029 PotentiallyEvaluatedIfUsed
1030 };
1031
1032 /// Data structure used to record current or nested
1033 /// expression evaluation contexts.
1034 struct ExpressionEvaluationContextRecord {
1035 /// The expression evaluation context.
1036 ExpressionEvaluationContext Context;
1037
1038 /// Whether the enclosing context needed a cleanup.
1039 CleanupInfo ParentCleanup;
1040
1041 /// Whether we are in a decltype expression.
1042 bool IsDecltype;
1043
1044 /// The number of active cleanup objects when we entered
1045 /// this expression evaluation context.
1046 unsigned NumCleanupObjects;
1047
1048 /// The number of typos encountered during this expression evaluation
1049 /// context (i.e. the number of TypoExprs created).
1050 unsigned NumTypos;
1051
1052 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1053
1054 /// The lambdas that are present within this context, if it
1055 /// is indeed an unevaluated context.
1056 SmallVector<LambdaExpr *, 2> Lambdas;
1057
1058 /// The declaration that provides context for lambda expressions
1059 /// and block literals if the normal declaration context does not
1060 /// suffice, e.g., in a default function argument.
1061 Decl *ManglingContextDecl;
1062
1063 /// If we are processing a decltype type, a set of call expressions
1064 /// for which we have deferred checking the completeness of the return type.
1065 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1066
1067 /// If we are processing a decltype type, a set of temporary binding
1068 /// expressions for which we have deferred checking the destructor.
1069 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1070
1071 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1072
1073 /// Expressions appearing as the LHS of a volatile assignment in this
1074 /// context. We produce a warning for these when popping the context if
1075 /// they are not discarded-value expressions nor unevaluated operands.
1076 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1077
1078 /// \brief Describes whether we are in an expression constext which we have
1079 /// to handle differently.
1080 enum ExpressionKind {
1081 EK_Decltype, EK_TemplateArgument, EK_Other
1082 } ExprContext;
1083
1084 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1085 unsigned NumCleanupObjects,
1086 CleanupInfo ParentCleanup,
1087 Decl *ManglingContextDecl,
1088 ExpressionKind ExprContext)
1089 : Context(Context), ParentCleanup(ParentCleanup),
1090 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1091 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1092
1093 bool isUnevaluated() const {
1094 return Context == ExpressionEvaluationContext::Unevaluated ||
1095 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1096 Context == ExpressionEvaluationContext::UnevaluatedList;
1097 }
1098 bool isConstantEvaluated() const {
1099 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1100 }
1101 };
1102
1103 /// A stack of expression evaluation contexts.
1104 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1105
1106 /// Emit a warning for all pending noderef expressions that we recorded.
1107 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1108
1109 /// Compute the mangling number context for a lambda expression or
1110 /// block literal. Also return the extra mangling decl if any.
1111 ///
1112 /// \param DC - The DeclContext containing the lambda expression or
1113 /// block literal.
1114 std::tuple<MangleNumberingContext *, Decl *>
1115 getCurrentMangleNumberContext(const DeclContext *DC);
1116
1117
1118 /// SpecialMemberOverloadResult - The overloading result for a special member
1119 /// function.
1120 ///
1121 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1122 /// integer are used to determine whether overload resolution succeeded.
1123 class SpecialMemberOverloadResult {
1124 public:
1125 enum Kind {
1126 NoMemberOrDeleted,
1127 Ambiguous,
1128 Success
1129 };
1130
1131 private:
1132 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1133
1134 public:
1135 SpecialMemberOverloadResult() : Pair() {}
1136 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1137 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1138
1139 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1140 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1141
1142 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1143 void setKind(Kind K) { Pair.setInt(K); }
1144 };
1145
1146 class SpecialMemberOverloadResultEntry
1147 : public llvm::FastFoldingSetNode,
1148 public SpecialMemberOverloadResult {
1149 public:
1150 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1151 : FastFoldingSetNode(ID)
1152 {}
1153 };
1154
1155 /// A cache of special member function overload resolution results
1156 /// for C++ records.
1157 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1158
1159 /// A cache of the flags available in enumerations with the flag_bits
1160 /// attribute.
1161 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1162
1163 /// The kind of translation unit we are processing.
1164 ///
1165 /// When we're processing a complete translation unit, Sema will perform
1166 /// end-of-translation-unit semantic tasks (such as creating
1167 /// initializers for tentative definitions in C) once parsing has
1168 /// completed. Modules and precompiled headers perform different kinds of
1169 /// checks.
1170 TranslationUnitKind TUKind;
1171
1172 llvm::BumpPtrAllocator BumpAlloc;
1173
1174 /// The number of SFINAE diagnostics that have been trapped.
1175 unsigned NumSFINAEErrors;
1176
1177 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1178 UnparsedDefaultArgInstantiationsMap;
1179
1180 /// A mapping from parameters with unparsed default arguments to the
1181 /// set of instantiations of each parameter.
1182 ///
1183 /// This mapping is a temporary data structure used when parsing
1184 /// nested class templates or nested classes of class templates,
1185 /// where we might end up instantiating an inner class before the
1186 /// default arguments of its methods have been parsed.
1187 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1188
1189 // Contains the locations of the beginning of unparsed default
1190 // argument locations.
1191 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1192
1193 /// UndefinedInternals - all the used, undefined objects which require a
1194 /// definition in this translation unit.
1195 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1196
1197 /// Determine if VD, which must be a variable or function, is an external
1198 /// symbol that nonetheless can't be referenced from outside this translation
1199 /// unit because its type has no linkage and it's not extern "C".
1200 bool isExternalWithNoLinkageType(ValueDecl *VD);
1201
1202 /// Obtain a sorted list of functions that are undefined but ODR-used.
1203 void getUndefinedButUsed(
1204 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1205
1206 /// Retrieves list of suspicious delete-expressions that will be checked at
1207 /// the end of translation unit.
1208 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1209 getMismatchingDeleteExpressions() const;
1210
1211 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1212 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1213
1214 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1215 /// We need to maintain a list, since selectors can have differing signatures
1216 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1217 /// of selectors are "overloaded").
1218 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1219 /// methods inside categories with a particular selector.
1220 GlobalMethodPool MethodPool;
1221
1222 /// Method selectors used in a \@selector expression. Used for implementation
1223 /// of -Wselector.
1224 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1225
1226 /// List of SourceLocations where 'self' is implicitly retained inside a
1227 /// block.
1228 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1229 ImplicitlyRetainedSelfLocs;
1230
1231 /// Kinds of C++ special members.
1232 enum CXXSpecialMember {
1233 CXXDefaultConstructor,
1234 CXXCopyConstructor,
1235 CXXMoveConstructor,
1236 CXXCopyAssignment,
1237 CXXMoveAssignment,
1238 CXXDestructor,
1239 CXXInvalid
1240 };
1241
1242 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1243 SpecialMemberDecl;
1244
1245 /// The C++ special members which we are currently in the process of
1246 /// declaring. If this process recursively triggers the declaration of the
1247 /// same special member, we should act as if it is not yet declared.
1248 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1249
1250 /// Kinds of defaulted comparison operator functions.
1251 enum class DefaultedComparisonKind : unsigned char {
1252 /// This is not a defaultable comparison operator.
1253 None,
1254 /// This is an operator== that should be implemented as a series of
1255 /// subobject comparisons.
1256 Equal,
1257 /// This is an operator<=> that should be implemented as a series of
1258 /// subobject comparisons.
1259 ThreeWay,
1260 /// This is an operator!= that should be implemented as a rewrite in terms
1261 /// of a == comparison.
1262 NotEqual,
1263 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1264 /// terms of a <=> comparison.
1265 Relational,
1266 };
1267
1268 /// The function definitions which were renamed as part of typo-correction
1269 /// to match their respective declarations. We want to keep track of them
1270 /// to ensure that we don't emit a "redefinition" error if we encounter a
1271 /// correctly named definition after the renamed definition.
1272 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1273
1274 /// Stack of types that correspond to the parameter entities that are
1275 /// currently being copy-initialized. Can be empty.
1276 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1277
1278 void ReadMethodPool(Selector Sel);
1279 void updateOutOfDateSelector(Selector Sel);
1280
1281 /// Private Helper predicate to check for 'self'.
1282 bool isSelfExpr(Expr *RExpr);
1283 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1284
1285 /// Cause the active diagnostic on the DiagosticsEngine to be
1286 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1287 /// should not be used elsewhere.
1288 void EmitCurrentDiagnostic(unsigned DiagID);
1289
1290 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1291 /// statements.
1292 class FPContractStateRAII {
1293 public:
1294 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1295 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1296
1297 private:
1298 Sema& S;
1299 FPOptions OldFPFeaturesState;
1300 };
1301
1302 void addImplicitTypedef(StringRef Name, QualType T);
1303
1304 bool WarnedStackExhausted = false;
1305
1306public:
1307 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1308 TranslationUnitKind TUKind = TU_Complete,
1309 CodeCompleteConsumer *CompletionConsumer = nullptr);
1310 ~Sema();
1311
1312 /// Perform initialization that occurs after the parser has been
1313 /// initialized but before it parses anything.
1314 void Initialize();
1315
1316 const LangOptions &getLangOpts() const { return LangOpts; }
1317 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1318 FPOptions &getFPOptions() { return FPFeatures; }
1319
1320 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1321 SourceManager &getSourceManager() const { return SourceMgr; }
1322 Preprocessor &getPreprocessor() const { return PP; }
1323 ASTContext &getASTContext() const { return Context; }
1324 ASTConsumer &getASTConsumer() const { return Consumer; }
1325 ASTMutationListener *getASTMutationListener() const;
1326 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1327
1328 ///Registers an external source. If an external source already exists,
1329 /// creates a multiplex external source and appends to it.
1330 ///
1331 ///\param[in] E - A non-null external sema source.
1332 ///
1333 void addExternalSource(ExternalSemaSource *E);
1334
1335 void PrintStats() const;
1336
1337 /// Warn that the stack is nearly exhausted.
1338 void warnStackExhausted(SourceLocation Loc);
1339
1340 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1341 /// guaranteed). Produces a warning if we're low on stack space and allocates
1342 /// more in that case. Use this in code that may recurse deeply (for example,
1343 /// in template instantiation) to avoid stack overflow.
1344 void runWithSufficientStackSpace(SourceLocation Loc,
1345 llvm::function_ref<void()> Fn);
1346
1347 /// Helper class that creates diagnostics with optional
1348 /// template instantiation stacks.
1349 ///
1350 /// This class provides a wrapper around the basic DiagnosticBuilder
1351 /// class that emits diagnostics. SemaDiagnosticBuilder is
1352 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1353 /// does) and, if the diagnostic comes from inside a template
1354 /// instantiation, printing the template instantiation stack as
1355 /// well.
1356 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1357 Sema &SemaRef;
1358 unsigned DiagID;
1359
1360 public:
1361 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1362 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1363
1364 // This is a cunning lie. DiagnosticBuilder actually performs move
1365 // construction in its copy constructor (but due to varied uses, it's not
1366 // possible to conveniently express this as actual move construction). So
1367 // the default copy ctor here is fine, because the base class disables the
1368 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1369 // in that case anwyay.
1370 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1371
1372 ~SemaDiagnosticBuilder() {
1373 // If we aren't active, there is nothing to do.
1374 if (!isActive()) return;
1375
1376 // Otherwise, we need to emit the diagnostic. First flush the underlying
1377 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1378 // won't emit the diagnostic in its own destructor.
1379 //
1380 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1381 // do its own needless checks to see if the diagnostic needs to be
1382 // emitted. However, because we take care to ensure that the builder
1383 // objects never escape, a sufficiently smart compiler will be able to
1384 // eliminate that code.
1385 FlushCounts();
1386 Clear();
1387
1388 // Dispatch to Sema to emit the diagnostic.
1389 SemaRef.EmitCurrentDiagnostic(DiagID);
1390 }
1391
1392 /// Teach operator<< to produce an object of the correct type.
1393 template<typename T>
1394 friend const SemaDiagnosticBuilder &operator<<(
1395 const SemaDiagnosticBuilder &Diag, const T &Value) {
1396 const DiagnosticBuilder &BaseDiag = Diag;
1397 BaseDiag << Value;
1398 return Diag;
1399 }
1400 };
1401
1402 /// Emit a diagnostic.
1403 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1404 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1405 return SemaDiagnosticBuilder(DB, *this, DiagID);
1406 }
1407
1408 /// Emit a partial diagnostic.
1409 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1410
1411 /// Build a partial diagnostic.
1412 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1413
1414 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1415
1416 /// Get a string to suggest for zero-initialization of a type.
1417 std::string
1418 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1419 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1420
1421 /// Calls \c Lexer::getLocForEndOfToken()
1422 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1423
1424 /// Retrieve the module loader associated with the preprocessor.
1425 ModuleLoader &getModuleLoader() const;
1426
1427 void emitAndClearUnusedLocalTypedefWarnings();
1428
1429 enum TUFragmentKind {
1430 /// The global module fragment, between 'module;' and a module-declaration.
1431 Global,
1432 /// A normal translation unit fragment. For a non-module unit, this is the
1433 /// entire translation unit. Otherwise, it runs from the module-declaration
1434 /// to the private-module-fragment (if any) or the end of the TU (if not).
1435 Normal,
1436 /// The private module fragment, between 'module :private;' and the end of
1437 /// the translation unit.
1438 Private
1439 };
1440
1441 void ActOnStartOfTranslationUnit();
1442 void ActOnEndOfTranslationUnit();
1443 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1444
1445 void CheckDelegatingCtorCycles();
1446
1447 Scope *getScopeForContext(DeclContext *Ctx);
1448
1449 void PushFunctionScope();
1450 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1451 sema::LambdaScopeInfo *PushLambdaScope();
1452
1453 /// This is used to inform Sema what the current TemplateParameterDepth
1454 /// is during Parsing. Currently it is used to pass on the depth
1455 /// when parsing generic lambda 'auto' parameters.
1456 void RecordParsingTemplateParameterDepth(unsigned Depth);
1457
1458 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1459 RecordDecl *RD, CapturedRegionKind K,
1460 unsigned OpenMPCaptureLevel = 0);
1461
1462 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1463 /// time after they've been popped.
1464 class PoppedFunctionScopeDeleter {
1465 Sema *Self;
1466
1467 public:
1468 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1469 void operator()(sema::FunctionScopeInfo *Scope) const;
1470 };
1471
1472 using PoppedFunctionScopePtr =
1473 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1474
1475 PoppedFunctionScopePtr
1476 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1477 const Decl *D = nullptr,
1478 QualType BlockType = QualType());
1479
1480 sema::FunctionScopeInfo *getCurFunction() const {
1481 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1482 }
1483
1484 sema::FunctionScopeInfo *getEnclosingFunction() const;
1485
1486 void setFunctionHasBranchIntoScope();
1487 void setFunctionHasBranchProtectedScope();
1488 void setFunctionHasIndirectGoto();
1489
1490 void PushCompoundScope(bool IsStmtExpr);
1491 void PopCompoundScope();
1492
1493 sema::CompoundScopeInfo &getCurCompoundScope() const;
1494
1495 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1496
1497 /// Retrieve the current block, if any.
1498 sema::BlockScopeInfo *getCurBlock();
1499
1500 /// Get the innermost lambda enclosing the current location, if any. This
1501 /// looks through intervening non-lambda scopes such as local functions and
1502 /// blocks.
1503 sema::LambdaScopeInfo *getEnclosingLambda() const;
1504
1505 /// Retrieve the current lambda scope info, if any.
1506 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1507 /// lambda scope info ignoring all inner capturing scopes that are not
1508 /// lambda scopes.
1509 sema::LambdaScopeInfo *
1510 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1511
1512 /// Retrieve the current generic lambda info, if any.
1513 sema::LambdaScopeInfo *getCurGenericLambda();
1514
1515 /// Retrieve the current captured region, if any.
1516 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1517
1518 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1519 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1520
1521 void ActOnComment(SourceRange Comment);
1522
1523 //===--------------------------------------------------------------------===//
1524 // Type Analysis / Processing: SemaType.cpp.
1525 //
1526
1527 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1528 const DeclSpec *DS = nullptr);
1529 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1530 const DeclSpec *DS = nullptr);
1531 QualType BuildPointerType(QualType T,
1532 SourceLocation Loc, DeclarationName Entity);
1533 QualType BuildReferenceType(QualType T, bool LValueRef,
1534 SourceLocation Loc, DeclarationName Entity);
1535 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1536 Expr *ArraySize, unsigned Quals,
1537 SourceRange Brackets, DeclarationName Entity);
1538 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1539 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1540 SourceLocation AttrLoc);
1541 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1542 SourceLocation AttrLoc);
1543
1544 /// Same as above, but constructs the AddressSpace index if not provided.
1545 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1546 SourceLocation AttrLoc);
1547
1548 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1549
1550 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1551
1552 /// Build a function type.
1553 ///
1554 /// This routine checks the function type according to C++ rules and
1555 /// under the assumption that the result type and parameter types have
1556 /// just been instantiated from a template. It therefore duplicates
1557 /// some of the behavior of GetTypeForDeclarator, but in a much
1558 /// simpler form that is only suitable for this narrow use case.
1559 ///
1560 /// \param T The return type of the function.
1561 ///
1562 /// \param ParamTypes The parameter types of the function. This array
1563 /// will be modified to account for adjustments to the types of the
1564 /// function parameters.
1565 ///
1566 /// \param Loc The location of the entity whose type involves this
1567 /// function type or, if there is no such entity, the location of the
1568 /// type that will have function type.
1569 ///
1570 /// \param Entity The name of the entity that involves the function
1571 /// type, if known.
1572 ///
1573 /// \param EPI Extra information about the function type. Usually this will
1574 /// be taken from an existing function with the same prototype.
1575 ///
1576 /// \returns A suitable function type, if there are no errors. The
1577 /// unqualified type will always be a FunctionProtoType.
1578 /// Otherwise, returns a NULL type.
1579 QualType BuildFunctionType(QualType T,
1580 MutableArrayRef<QualType> ParamTypes,
1581 SourceLocation Loc, DeclarationName Entity,
1582 const FunctionProtoType::ExtProtoInfo &EPI);
1583
1584 QualType BuildMemberPointerType(QualType T, QualType Class,
1585 SourceLocation Loc,
1586 DeclarationName Entity);
1587 QualType BuildBlockPointerType(QualType T,
1588 SourceLocation Loc, DeclarationName Entity);
1589 QualType BuildParenType(QualType T);
1590 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1591 QualType BuildReadPipeType(QualType T,
1592 SourceLocation Loc);
1593 QualType BuildWritePipeType(QualType T,
1594 SourceLocation Loc);
1595
1596 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1597 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1598
1599 /// Package the given type and TSI into a ParsedType.
1600 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1601 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1602 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1603 static QualType GetTypeFromParser(ParsedType Ty,
1604 TypeSourceInfo **TInfo = nullptr);
1605 CanThrowResult canThrow(const Stmt *E);
1606 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1607 const FunctionProtoType *FPT);
1608 void UpdateExceptionSpec(FunctionDecl *FD,
1609 const FunctionProtoType::ExceptionSpecInfo &ESI);
1610 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1611 bool CheckDistantExceptionSpec(QualType T);
1612 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1613 bool CheckEquivalentExceptionSpec(
1614 const FunctionProtoType *Old, SourceLocation OldLoc,
1615 const FunctionProtoType *New, SourceLocation NewLoc);
1616 bool CheckEquivalentExceptionSpec(
1617 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1618 const FunctionProtoType *Old, SourceLocation OldLoc,
1619 const FunctionProtoType *New, SourceLocation NewLoc);
1620 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1621 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1622 const PartialDiagnostic &NestedDiagID,
1623 const PartialDiagnostic &NoteID,
1624 const PartialDiagnostic &NoThrowDiagID,
1625 const FunctionProtoType *Superset,
1626 SourceLocation SuperLoc,
1627 const FunctionProtoType *Subset,
1628 SourceLocation SubLoc);
1629 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1630 const PartialDiagnostic &NoteID,
1631 const FunctionProtoType *Target,
1632 SourceLocation TargetLoc,
1633 const FunctionProtoType *Source,
1634 SourceLocation SourceLoc);
1635
1636 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1637
1638 /// The parser has parsed the context-sensitive type 'instancetype'
1639 /// in an Objective-C message declaration. Return the appropriate type.
1640 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1641
1642 /// Abstract class used to diagnose incomplete types.
1643 struct TypeDiagnoser {
1644 TypeDiagnoser() {}
1645
1646 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1647 virtual ~TypeDiagnoser() {}
1648 };
1649
1650 static int getPrintable(int I) { return I; }
1651 static unsigned getPrintable(unsigned I) { return I; }
1652 static bool getPrintable(bool B) { return B; }
1653 static const char * getPrintable(const char *S) { return S; }
1654 static StringRef getPrintable(StringRef S) { return S; }
1655 static const std::string &getPrintable(const std::string &S) { return S; }
1656 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1657 return II;
1658 }
1659 static DeclarationName getPrintable(DeclarationName N) { return N; }
1660 static QualType getPrintable(QualType T) { return T; }
1661 static SourceRange getPrintable(SourceRange R) { return R; }
1662 static SourceRange getPrintable(SourceLocation L) { return L; }
1663 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1664 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1665
1666 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1667 unsigned DiagID;
1668 std::tuple<const Ts &...> Args;
1669
1670 template <std::size_t... Is>
1671 void emit(const SemaDiagnosticBuilder &DB,
1672 std::index_sequence<Is...>) const {
1673 // Apply all tuple elements to the builder in order.
1674 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1675 (void)Dummy;
1676 }
1677
1678 public:
1679 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1680 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1681 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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 1681, __PRETTY_FUNCTION__))
;
1682 }
1683
1684 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1685 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1686 emit(DB, std::index_sequence_for<Ts...>());
1687 DB << T;
1688 }
1689 };
1690
1691private:
1692 /// Methods for marking which expressions involve dereferencing a pointer
1693 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1694 /// they are parsed, meaning that a noderef pointer may not be accessed. For
1695 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1696 /// `*p`, but need to check that `address of` is called on it. This requires
1697 /// keeping a container of all pending expressions and checking if the address
1698 /// of them are eventually taken.
1699 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1700 void CheckAddressOfNoDeref(const Expr *E);
1701 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1702
1703 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1704 TypeDiagnoser *Diagnoser);
1705
1706 struct ModuleScope {
1707 SourceLocation BeginLoc;
1708 clang::Module *Module = nullptr;
1709 bool ModuleInterface = false;
1710 bool ImplicitGlobalModuleFragment = false;
1711 VisibleModuleSet OuterVisibleModules;
1712 };
1713 /// The modules we're currently parsing.
1714 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1715
1716 /// Namespace definitions that we will export when they finish.
1717 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1718
1719 /// Get the module whose scope we are currently within.
1720 Module *getCurrentModule() const {
1721 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1722 }
1723
1724 VisibleModuleSet VisibleModules;
1725
1726public:
1727 /// Get the module owning an entity.
1728 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
22
Called C++ object pointer is null
1729
1730 /// Make a merged definition of an existing hidden definition \p ND
1731 /// visible at the specified location.
1732 void makeMergedDefinitionVisible(NamedDecl *ND);
1733
1734 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1735
1736 /// Determine whether a declaration is visible to name lookup.
1737 bool isVisible(const NamedDecl *D) {
1738 return !D->isHidden() || isVisibleSlow(D);
1739 }
1740
1741 /// Determine whether any declaration of an entity is visible.
1742 bool
1743 hasVisibleDeclaration(const NamedDecl *D,
1744 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1745 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1746 }
1747 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1748 llvm::SmallVectorImpl<Module *> *Modules);
1749
1750 bool hasVisibleMergedDefinition(NamedDecl *Def);
1751 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1752
1753 /// Determine if \p D and \p Suggested have a structurally compatible
1754 /// layout as described in C11 6.2.7/1.
1755 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1756
1757 /// Determine if \p D has a visible definition. If not, suggest a declaration
1758 /// that should be made visible to expose the definition.
1759 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1760 bool OnlyNeedComplete = false);
1761 bool hasVisibleDefinition(const NamedDecl *D) {
1762 NamedDecl *Hidden;
1763 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1764 }
1765
1766 /// Determine if the template parameter \p D has a visible default argument.
1767 bool
1768 hasVisibleDefaultArgument(const NamedDecl *D,
1769 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1770
1771 /// Determine if there is a visible declaration of \p D that is an explicit
1772 /// specialization declaration for a specialization of a template. (For a
1773 /// member specialization, use hasVisibleMemberSpecialization.)
1774 bool hasVisibleExplicitSpecialization(
1775 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1776
1777 /// Determine if there is a visible declaration of \p D that is a member
1778 /// specialization declaration (as opposed to an instantiated declaration).
1779 bool hasVisibleMemberSpecialization(
1780 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1781
1782 /// Determine if \p A and \p B are equivalent internal linkage declarations
1783 /// from different modules, and thus an ambiguity error can be downgraded to
1784 /// an extension warning.
1785 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1786 const NamedDecl *B);
1787 void diagnoseEquivalentInternalLinkageDeclarations(
1788 SourceLocation Loc, const NamedDecl *D,
1789 ArrayRef<const NamedDecl *> Equiv);
1790
1791 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1792
1793 bool isCompleteType(SourceLocation Loc, QualType T) {
1794 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1795 }
1796 bool RequireCompleteType(SourceLocation Loc, QualType T,
1797 TypeDiagnoser &Diagnoser);
1798 bool RequireCompleteType(SourceLocation Loc, QualType T,
1799 unsigned DiagID);
1800
1801 template <typename... Ts>
1802 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1803 const Ts &...Args) {
1804 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1805 return RequireCompleteType(Loc, T, Diagnoser);
1806 }
1807
1808 void completeExprArrayBound(Expr *E);
1809 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1810 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1811
1812 template <typename... Ts>
1813 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1814 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1815 return RequireCompleteExprType(E, Diagnoser);
1816 }
1817
1818 bool RequireLiteralType(SourceLocation Loc, QualType T,
1819 TypeDiagnoser &Diagnoser);
1820 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1821
1822 template <typename... Ts>
1823 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1824 const Ts &...Args) {
1825 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1826 return RequireLiteralType(Loc, T, Diagnoser);
1827 }
1828
1829 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1830 const CXXScopeSpec &SS, QualType T,
1831 TagDecl *OwnedTagDecl = nullptr);
1832
1833 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1834 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1835 /// context, such as when building a type for decltype(auto).
1836 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1837 bool AsUnevaluated = true);
1838 QualType BuildUnaryTransformType(QualType BaseType,
1839 UnaryTransformType::UTTKind UKind,
1840 SourceLocation Loc);
1841
1842 //===--------------------------------------------------------------------===//
1843 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1844 //
1845
1846 struct SkipBodyInfo {
1847 SkipBodyInfo()
1848 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1849 New(nullptr) {}
1850 bool ShouldSkip;
1851 bool CheckSameAsPrevious;
1852 NamedDecl *Previous;
1853 NamedDecl *New;
1854 };
1855
1856 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1857
1858 void DiagnoseUseOfUnimplementedSelectors();
1859
1860 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1861
1862 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1863 Scope *S, CXXScopeSpec *SS = nullptr,
1864 bool isClassName = false, bool HasTrailingDot = false,
1865 ParsedType ObjectType = nullptr,
1866 bool IsCtorOrDtorName = false,
1867 bool WantNontrivialTypeSourceInfo = false,
1868 bool IsClassTemplateDeductionContext = true,
1869 IdentifierInfo **CorrectedII = nullptr);
1870 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1871 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1872 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1873 SourceLocation IILoc,
1874 Scope *S,
1875 CXXScopeSpec *SS,
1876 ParsedType &SuggestedType,
1877 bool IsTemplateName = false);
1878
1879 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1880 /// type name has failed in a dependent context. In these situations, we
1881 /// automatically form a DependentTypeName that will retry lookup in a related
1882 /// scope during instantiation.
1883 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1884 SourceLocation NameLoc,
1885 bool IsTemplateTypeArg);
1886
1887 /// Describes the result of the name lookup and resolution performed
1888 /// by \c ClassifyName().
1889 enum NameClassificationKind {
1890 /// This name is not a type or template in this context, but might be
1891 /// something else.
1892 NC_Unknown,
1893 /// Classification failed; an error has been produced.
1894 NC_Error,
1895 /// The name has been typo-corrected to a keyword.
1896 NC_Keyword,
1897 /// The name was classified as a type.
1898 NC_Type,
1899 /// The name was classified as a specific non-type, non-template
1900 /// declaration. ActOnNameClassifiedAsNonType should be called to
1901 /// convert the declaration to an expression.
1902 NC_NonType,
1903 /// The name was classified as an ADL-only function name.
1904 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1905 /// result to an expression.
1906 NC_UndeclaredNonType,
1907 /// The name denotes a member of a dependent type that could not be
1908 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1909 /// convert the result to an expression.
1910 NC_DependentNonType,
1911 /// The name was classified as a non-type, and an expression representing
1912 /// that name has been formed.
1913 NC_ContextIndependentExpr,
1914 /// The name was classified as a template whose specializations are types.
1915 NC_TypeTemplate,
1916 /// The name was classified as a variable template name.
1917 NC_VarTemplate,
1918 /// The name was classified as a function template name.
1919 NC_FunctionTemplate,
1920 /// The name was classified as an ADL-only function template name.
1921 NC_UndeclaredTemplate,
1922 };
1923
1924 class NameClassification {
1925 NameClassificationKind Kind;
1926 union {
1927 ExprResult Expr;
1928 NamedDecl *NonTypeDecl;
1929 TemplateName Template;
1930 ParsedType Type;
1931 };
1932
1933 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1934
1935 public:
1936 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1937
1938 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1939
1940 static NameClassification Error() {
1941 return NameClassification(NC_Error);
1942 }
1943
1944 static NameClassification Unknown() {
1945 return NameClassification(NC_Unknown);
1946 }
1947
1948 static NameClassification ContextIndependentExpr(ExprResult E) {
1949 NameClassification Result(NC_ContextIndependentExpr);
1950 Result.Expr = E;
1951 return Result;
1952 }
1953
1954 static NameClassification NonType(NamedDecl *D) {
1955 NameClassification Result(NC_NonType);
1956 Result.NonTypeDecl = D;
1957 return Result;
1958 }
1959
1960 static NameClassification UndeclaredNonType() {
1961 return NameClassification(NC_UndeclaredNonType);
1962 }
1963
1964 static NameClassification DependentNonType() {
1965 return NameClassification(NC_DependentNonType);
1966 }
1967
1968 static NameClassification TypeTemplate(TemplateName Name) {
1969 NameClassification Result(NC_TypeTemplate);
1970 Result.Template = Name;
1971 return Result;
1972 }
1973
1974 static NameClassification VarTemplate(TemplateName Name) {
1975 NameClassification Result(NC_VarTemplate);
1976 Result.Template = Name;
1977 return Result;
1978 }
1979
1980 static NameClassification FunctionTemplate(TemplateName Name) {
1981 NameClassification Result(NC_FunctionTemplate);
1982 Result.Template = Name;
1983 return Result;
1984 }
1985
1986 static NameClassification UndeclaredTemplate(TemplateName Name) {
1987 NameClassification Result(NC_UndeclaredTemplate);
1988 Result.Template = Name;
1989 return Result;
1990 }
1991
1992 NameClassificationKind getKind() const { return Kind; }
1993
1994 ExprResult getExpression() const {
1995 assert(Kind == NC_ContextIndependentExpr)((Kind == NC_ContextIndependentExpr) ? static_cast<void>
(0) : __assert_fail ("Kind == NC_ContextIndependentExpr", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 1995, __PRETTY_FUNCTION__))
;
1996 return Expr;
1997 }
1998
1999 ParsedType getType() const {
2000 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 2000, __PRETTY_FUNCTION__))
;
2001 return Type;
2002 }
2003
2004 NamedDecl *getNonTypeDecl() const {
2005 assert(Kind == NC_NonType)((Kind == NC_NonType) ? static_cast<void> (0) : __assert_fail
("Kind == NC_NonType", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 2005, __PRETTY_FUNCTION__))
;
2006 return NonTypeDecl;
2007 }
2008
2009 TemplateName getTemplateName() const {
2010 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 2011, __PRETTY_FUNCTION__))
2011 Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate || Kind == NC_UndeclaredTemplate) ? static_cast
<void> (0) : __assert_fail ("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 2011, __PRETTY_FUNCTION__))
;
2012 return Template;
2013 }
2014
2015 TemplateNameKind getTemplateNameKind() const {
2016 switch (Kind) {
2017 case NC_TypeTemplate:
2018 return TNK_Type_template;
2019 case NC_FunctionTemplate:
2020 return TNK_Function_template;
2021 case NC_VarTemplate:
2022 return TNK_Var_template;
2023 case NC_UndeclaredTemplate:
2024 return TNK_Undeclared_template;
2025 default:
2026 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 2026)
;
2027 }
2028 }
2029 };
2030
2031 /// Perform name lookup on the given name, classifying it based on
2032 /// the results of name lookup and the following token.
2033 ///
2034 /// This routine is used by the parser to resolve identifiers and help direct
2035 /// parsing. When the identifier cannot be found, this routine will attempt
2036 /// to correct the typo and classify based on the resulting name.
2037 ///
2038 /// \param S The scope in which we're performing name lookup.
2039 ///
2040 /// \param SS The nested-name-specifier that precedes the name.
2041 ///
2042 /// \param Name The identifier. If typo correction finds an alternative name,
2043 /// this pointer parameter will be updated accordingly.
2044 ///
2045 /// \param NameLoc The location of the identifier.
2046 ///
2047 /// \param NextToken The token following the identifier. Used to help
2048 /// disambiguate the name.
2049 ///
2050 /// \param CCC The correction callback, if typo correction is desired.
2051 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2052 IdentifierInfo *&Name, SourceLocation NameLoc,
2053 const Token &NextToken,
2054 CorrectionCandidateCallback *CCC = nullptr);
2055
2056 /// Act on the result of classifying a name as an undeclared (ADL-only)
2057 /// non-type declaration.
2058 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2059 SourceLocation NameLoc);
2060 /// Act on the result of classifying a name as an undeclared member of a
2061 /// dependent base class.
2062 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2063 IdentifierInfo *Name,
2064 SourceLocation NameLoc,
2065 bool IsAddressOfOperand);
2066 /// Act on the result of classifying a name as a specific non-type
2067 /// declaration.
2068 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2069 NamedDecl *Found,
2070 SourceLocation NameLoc,
2071 const Token &NextToken);
2072
2073 /// Describes the detailed kind of a template name. Used in diagnostics.
2074 enum class TemplateNameKindForDiagnostics {
2075 ClassTemplate,
2076 FunctionTemplate,
2077 VarTemplate,
2078 AliasTemplate,
2079 TemplateTemplateParam,
2080 Concept,
2081 DependentTemplate
2082 };
2083 TemplateNameKindForDiagnostics
2084 getTemplateNameKindForDiagnostics(TemplateName Name);
2085
2086 /// Determine whether it's plausible that E was intended to be a
2087 /// template-name.
2088 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2089 if (!getLangOpts().CPlusPlus || E.isInvalid())
2090 return false;
2091 Dependent = false;
2092 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2093 return !DRE->hasExplicitTemplateArgs();
2094 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2095 return !ME->hasExplicitTemplateArgs();
2096 Dependent = true;
2097 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2098 return !DSDRE->hasExplicitTemplateArgs();
2099 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2100 return !DSME->hasExplicitTemplateArgs();
2101 // Any additional cases recognized here should also be handled by
2102 // diagnoseExprIntendedAsTemplateName.
2103 return false;
2104 }
2105 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2106 SourceLocation Less,
2107 SourceLocation Greater);
2108
2109 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2110
2111 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2112 MultiTemplateParamsArg TemplateParameterLists);
2113 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2114 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2115 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2116 DeclarationName Name, SourceLocation Loc,
2117 bool IsTemplateId);
2118 void
2119 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2120 SourceLocation FallbackLoc,
2121 SourceLocation ConstQualLoc = SourceLocation(),
2122 SourceLocation VolatileQualLoc = SourceLocation(),
2123 SourceLocation RestrictQualLoc = SourceLocation(),
2124 SourceLocation AtomicQualLoc = SourceLocation(),
2125 SourceLocation UnalignedQualLoc = SourceLocation());
2126
2127 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2128 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2129 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2130 const LookupResult &R);
2131 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2132 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2133 const LookupResult &R);
2134 void CheckShadow(Scope *S, VarDecl *D);
2135
2136 /// Warn if 'E', which is an expression that is about to be modified, refers
2137 /// to a shadowing declaration.
2138 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2139
2140 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2141
2142private:
2143 /// Map of current shadowing declarations to shadowed declarations. Warn if
2144 /// it looks like the user is trying to modify the shadowing declaration.
2145 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2146
2147public:
2148 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2149 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2150 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2151 TypedefNameDecl *NewTD);
2152 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2153 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2154 TypeSourceInfo *TInfo,
2155 LookupResult &Previous);
2156 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2157 LookupResult &Previous, bool &Redeclaration);
2158 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2159 TypeSourceInfo *TInfo,
2160 LookupResult &Previous,
2161 MultiTemplateParamsArg TemplateParamLists,
2162 bool &AddToScope,
2163 ArrayRef<BindingDecl *> Bindings = None);
2164 NamedDecl *
2165 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2166 MultiTemplateParamsArg TemplateParamLists);
2167 // Returns true if the variable declaration is a redeclaration
2168 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2169 void CheckVariableDeclarationType(VarDecl *NewVD);
2170 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2171 Expr *Init);
2172 void CheckCompleteVariableDeclaration(VarDecl *VD);
2173 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2174 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2175
2176 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2177 TypeSourceInfo *TInfo,
2178 LookupResult &Previous,
2179 MultiTemplateParamsArg TemplateParamLists,
2180 bool &AddToScope);
2181 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2182
2183 enum class CheckConstexprKind {
2184 /// Diagnose issues that are non-constant or that are extensions.
2185 Diagnose,
2186 /// Identify whether this function satisfies the formal rules for constexpr
2187 /// functions in the current lanugage mode (with no extensions).
2188 CheckValid
2189 };
2190
2191 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2192 CheckConstexprKind Kind);
2193
2194 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2195 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2196 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2197 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2198 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2199 // Returns true if the function declaration is a redeclaration
2200 bool CheckFunctionDeclaration(Scope *S,
2201 FunctionDecl *NewFD, LookupResult &Previous,
2202 bool IsMemberSpecialization);
2203 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2204 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2205 QualType NewT, QualType OldT);
2206 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2207 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2208 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2209 bool IsDefinition);
2210 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2211 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2212 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2213 SourceLocation Loc,
2214 QualType T);
2215 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2216 SourceLocation NameLoc, IdentifierInfo *Name,
2217 QualType T, TypeSourceInfo *TSInfo,
2218 StorageClass SC);
2219 void ActOnParamDefaultArgument(Decl *param,
2220 SourceLocation EqualLoc,
2221 Expr *defarg);
2222 void ActOnParamUnparsedDefaultArgument(Decl *param,
2223 SourceLocation EqualLoc,
2224 SourceLocation ArgLoc);
2225 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2226 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2227 SourceLocation EqualLoc);
2228
2229 // Contexts where using non-trivial C union types can be disallowed. This is
2230 // passed to err_non_trivial_c_union_in_invalid_context.
2231 enum NonTrivialCUnionContext {
2232 // Function parameter.
2233 NTCUC_FunctionParam,
2234 // Function return.
2235 NTCUC_FunctionReturn,
2236 // Default-initialized object.
2237 NTCUC_DefaultInitializedObject,
2238 // Variable with automatic storage duration.
2239 NTCUC_AutoVar,
2240 // Initializer expression that might copy from another object.
2241 NTCUC_CopyInit,
2242 // Assignment.
2243 NTCUC_Assignment,
2244 // Compound literal.
2245 NTCUC_CompoundLiteral,
2246 // Block capture.
2247 NTCUC_BlockCapture,
2248 // lvalue-to-rvalue conversion of volatile type.
2249 NTCUC_LValueToRValueVolatile,
2250 };
2251
2252 /// Emit diagnostics if the initializer or any of its explicit or
2253 /// implicitly-generated subexpressions require copying or
2254 /// default-initializing a type that is or contains a C union type that is
2255 /// non-trivial to copy or default-initialize.
2256 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2257
2258 // These flags are passed to checkNonTrivialCUnion.
2259 enum NonTrivialCUnionKind {
2260 NTCUK_Init = 0x1,
2261 NTCUK_Destruct = 0x2,
2262 NTCUK_Copy = 0x4,
2263 };
2264
2265 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2266 /// a non-trivial C union is used in an invalid context.
2267 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2268 NonTrivialCUnionContext UseContext,
2269 unsigned NonTrivialKind);
2270
2271 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2272 void ActOnUninitializedDecl(Decl *dcl);
2273 void ActOnInitializerError(Decl *Dcl);
2274
2275 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2276 void ActOnCXXForRangeDecl(Decl *D);
2277 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2278 IdentifierInfo *Ident,
2279 ParsedAttributes &Attrs,
2280 SourceLocation AttrEnd);
2281 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2282 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2283 void CheckStaticLocalForDllExport(VarDecl *VD);
2284 void FinalizeDeclaration(Decl *D);
2285 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2286 ArrayRef<Decl *> Group);
2287 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2288
2289 /// Should be called on all declarations that might have attached
2290 /// documentation comments.
2291 void ActOnDocumentableDecl(Decl *D);
2292 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2293
2294 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2295 SourceLocation LocAfterDecls);
2296 void CheckForFunctionRedefinition(
2297 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2298 SkipBodyInfo *SkipBody = nullptr);
2299 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2300 MultiTemplateParamsArg TemplateParamLists,
2301 SkipBodyInfo *SkipBody = nullptr);
2302 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2303 SkipBodyInfo *SkipBody = nullptr);
2304 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2305 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2306 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2307 bool isObjCMethodDecl(Decl *D) {
2308 return D && isa<ObjCMethodDecl>(D);
2309 }
2310
2311 /// Determine whether we can delay parsing the body of a function or
2312 /// function template until it is used, assuming we don't care about emitting
2313 /// code for that function.
2314 ///
2315 /// This will be \c false if we may need the body of the function in the
2316 /// middle of parsing an expression (where it's impractical to switch to
2317 /// parsing a different function), for instance, if it's constexpr in C++11
2318 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2319 bool canDelayFunctionBody(const Declarator &D);
2320
2321 /// Determine whether we can skip parsing the body of a function
2322 /// definition, assuming we don't care about analyzing its body or emitting
2323 /// code for that function.
2324 ///
2325 /// This will be \c false only if we may need the body of the function in
2326 /// order to parse the rest of the program (for instance, if it is
2327 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2328 bool canSkipFunctionBody(Decl *D);
2329
2330 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2331 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2332 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2333 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2334 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2335
2336 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2337 /// attribute for which parsing is delayed.
2338 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2339
2340 /// Diagnose any unused parameters in the given sequence of
2341 /// ParmVarDecl pointers.
2342 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2343
2344 /// Diagnose whether the size of parameters or return value of a
2345 /// function or obj-c method definition is pass-by-value and larger than a
2346 /// specified threshold.
2347 void
2348 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2349 QualType ReturnTy, NamedDecl *D);
2350
2351 void DiagnoseInvalidJumps(Stmt *Body);
2352 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2353 SourceLocation AsmLoc,
2354 SourceLocation RParenLoc);
2355
2356 /// Handle a C++11 empty-declaration and attribute-declaration.
2357 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2358 SourceLocation SemiLoc);
2359
2360 enum class ModuleDeclKind {
2361 Interface, ///< 'export module X;'
2362 Implementation, ///< 'module X;'
2363 };
2364
2365 /// The parser has processed a module-declaration that begins the definition
2366 /// of a module interface or implementation.
2367 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2368 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2369 ModuleIdPath Path, bool IsFirstDecl);
2370
2371 /// The parser has processed a global-module-fragment declaration that begins
2372 /// the definition of the global module fragment of the current module unit.
2373 /// \param ModuleLoc The location of the 'module' keyword.
2374 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2375
2376 /// The parser has processed a private-module-fragment declaration that begins
2377 /// the definition of the private module fragment of the current module unit.
2378 /// \param ModuleLoc The location of the 'module' keyword.
2379 /// \param PrivateLoc The location of the 'private' keyword.
2380 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2381 SourceLocation PrivateLoc);
2382
2383 /// The parser has processed a module import declaration.
2384 ///
2385 /// \param StartLoc The location of the first token in the declaration. This
2386 /// could be the location of an '@', 'export', or 'import'.
2387 /// \param ExportLoc The location of the 'export' keyword, if any.
2388 /// \param ImportLoc The location of the 'import' keyword.
2389 /// \param Path The module access path.
2390 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2391 SourceLocation ExportLoc,
2392 SourceLocation ImportLoc, ModuleIdPath Path);
2393 DeclResult ActOnModuleImport(SourceLocation StartLoc,
2394 SourceLocation ExportLoc,
2395 SourceLocation ImportLoc, Module *M,
2396 ModuleIdPath Path = {});
2397
2398 /// The parser has processed a module import translated from a
2399 /// #include or similar preprocessing directive.
2400 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2401 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2402
2403 /// The parsed has entered a submodule.
2404 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2405 /// The parser has left a submodule.
2406 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2407
2408 /// Create an implicit import of the given module at the given
2409 /// source location, for error recovery, if possible.
2410 ///
2411 /// This routine is typically used when an entity found by name lookup
2412 /// is actually hidden within a module that we know about but the user
2413 /// has forgotten to import.
2414 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2415 Module *Mod);
2416
2417 /// Kinds of missing import. Note, the values of these enumerators correspond
2418 /// to %select values in diagnostics.
2419 enum class MissingImportKind {
2420 Declaration,
2421 Definition,
2422 DefaultArgument,
2423 ExplicitSpecialization,
2424 PartialSpecialization
2425 };
2426
2427 /// Diagnose that the specified declaration needs to be visible but
2428 /// isn't, and suggest a module import that would resolve the problem.
2429 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2430 MissingImportKind MIK, bool Recover = true);
2431 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2432 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2433 MissingImportKind MIK, bool Recover);
2434
2435 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2436 SourceLocation LBraceLoc);
2437 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2438 SourceLocation RBraceLoc);
2439
2440 /// We've found a use of a templated declaration that would trigger an
2441 /// implicit instantiation. Check that any relevant explicit specializations
2442 /// and partial specializations are visible, and diagnose if not.
2443 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2444
2445 /// We've found a use of a template specialization that would select a
2446 /// partial specialization. Check that the partial specialization is visible,
2447 /// and diagnose if not.
2448 void checkPartialSpecializationVisibility(SourceLocation Loc,
2449 NamedDecl *Spec);
2450
2451 /// Retrieve a suitable printing policy for diagnostics.
2452 PrintingPolicy getPrintingPolicy() const {
2453 return getPrintingPolicy(Context, PP);
2454 }
2455
2456 /// Retrieve a suitable printing policy for diagnostics.
2457 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2458 const Preprocessor &PP);
2459
2460 /// Scope actions.
2461 void ActOnPopScope(SourceLocation Loc, Scope *S);
2462 void ActOnTranslationUnitScope(Scope *S);
2463
2464 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2465 RecordDecl *&AnonRecord);
2466 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2467 MultiTemplateParamsArg TemplateParams,
2468 bool IsExplicitInstantiation,
2469 RecordDecl *&AnonRecord);
2470
2471 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2472 AccessSpecifier AS,
2473 RecordDecl *Record,
2474 const PrintingPolicy &Policy);
2475
2476 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2477 RecordDecl *Record);
2478
2479 /// Common ways to introduce type names without a tag for use in diagnostics.
2480 /// Keep in sync with err_tag_reference_non_tag.
2481 enum NonTagKind {
2482 NTK_NonStruct,
2483 NTK_NonClass,
2484 NTK_NonUnion,
2485 NTK_NonEnum,
2486 NTK_Typedef,
2487 NTK_TypeAlias,
2488 NTK_Template,
2489 NTK_TypeAliasTemplate,
2490 NTK_TemplateTemplateArgument,
2491 };
2492
2493 /// Given a non-tag type declaration, returns an enum useful for indicating
2494 /// what kind of non-tag type this is.
2495 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2496
2497 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2498 TagTypeKind NewTag, bool isDefinition,
2499 SourceLocation NewTagLoc,
2500 const IdentifierInfo *Name);
2501
2502 enum TagUseKind {
2503 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2504 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2505 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2506 TUK_Friend // Friend declaration: 'friend struct foo;'
2507 };
2508
2509 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2510 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2511 SourceLocation NameLoc, const ParsedAttributesView &Attr,
2512 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2513 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2514 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2515 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2516 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2517 SkipBodyInfo *SkipBody = nullptr);
2518
2519 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2520 unsigned TagSpec, SourceLocation TagLoc,
2521 CXXScopeSpec &SS, IdentifierInfo *Name,
2522 SourceLocation NameLoc,
2523 const ParsedAttributesView &Attr,
2524 MultiTemplateParamsArg TempParamLists);
2525
2526 TypeResult ActOnDependentTag(Scope *S,
2527 unsigned TagSpec,
2528 TagUseKind TUK,
2529 const CXXScopeSpec &SS,
2530 IdentifierInfo *Name,
2531 SourceLocation TagLoc,
2532 SourceLocation NameLoc);
2533
2534 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2535 IdentifierInfo *ClassName,
2536 SmallVectorImpl<Decl *> &Decls);
2537 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2538 Declarator &D, Expr *BitfieldWidth);
2539
2540 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2541 Declarator &D, Expr *BitfieldWidth,
2542 InClassInitStyle InitStyle,
2543 AccessSpecifier AS);
2544 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2545 SourceLocation DeclStart, Declarator &D,
2546 Expr *BitfieldWidth,
2547 InClassInitStyle InitStyle,
2548 AccessSpecifier AS,
2549 const ParsedAttr &MSPropertyAttr);
2550
2551 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2552 TypeSourceInfo *TInfo,
2553 RecordDecl *Record, SourceLocation Loc,
2554 bool Mutable, Expr *BitfieldWidth,
2555 InClassInitStyle InitStyle,
2556 SourceLocation TSSL,
2557 AccessSpecifier AS, NamedDecl *PrevDecl,
2558 Declarator *D = nullptr);
2559
2560 bool CheckNontrivialField(FieldDecl *FD);
2561 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2562
2563 enum TrivialABIHandling {
2564 /// The triviality of a method unaffected by "trivial_abi".
2565 TAH_IgnoreTrivialABI,
2566
2567 /// The triviality of a method affected by "trivial_abi".
2568 TAH_ConsiderTrivialABI
2569 };
2570
2571 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2572 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2573 bool Diagnose = false);
2574
2575 /// For a defaulted function, the kind of defaulted function that it is.
2576 class DefaultedFunctionKind {
2577 CXXSpecialMember SpecialMember : 8;
2578 DefaultedComparisonKind Comparison : 8;
2579
2580 public:
2581 DefaultedFunctionKind()
2582 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2583 }
2584 DefaultedFunctionKind(CXXSpecialMember CSM)
2585 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
2586 DefaultedFunctionKind(DefaultedComparisonKind Comp)
2587 : SpecialMember(CXXInvalid), Comparison(Comp) {}
2588
2589 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
2590 bool isComparison() const {
2591 return Comparison != DefaultedComparisonKind::None;
2592 }
2593
2594 explicit operator bool() const {
2595 return isSpecialMember() || isComparison();
2596 }
2597
2598 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
2599 DefaultedComparisonKind asComparison() const { return Comparison; }
2600
2601 /// Get the index of this function kind for use in diagnostics.
2602 unsigned getDiagnosticIndex() const {
2603 static_assert(CXXInvalid > CXXDestructor,
2604 "invalid should have highest index");
2605 static_assert((unsigned)DefaultedComparisonKind::None == 0,
2606 "none should be equal to zero");
2607 return SpecialMember + (unsigned)Comparison;
2608 }
2609 };
2610
2611 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2612
2613 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2614 return getDefaultedFunctionKind(MD).asSpecialMember();
2615 }
2616 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2617 return getDefaultedFunctionKind(FD).asComparison();
2618 }
2619
2620 void ActOnLastBitfield(SourceLocation DeclStart,
2621 SmallVectorImpl<Decl *> &AllIvarDecls);
2622 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2623 Declarator &D, Expr *BitfieldWidth,
2624 tok::ObjCKeywordKind visibility);
2625
2626 // This is used for both record definitions and ObjC interface declarations.
2627 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2628 ArrayRef<Decl *> Fields, SourceLocation LBrac,
2629 SourceLocation RBrac, const ParsedAttributesView &AttrList);
2630
2631 /// ActOnTagStartDefinition - Invoked when we have entered the
2632 /// scope of a tag's definition (e.g., for an enumeration, class,
2633 /// struct, or union).
2634 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2635
2636 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2637 /// Differently from C++, actually parse the body and reject / error out
2638 /// in case of a structural mismatch.
2639 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2640 SkipBodyInfo &SkipBody);
2641
2642 typedef void *SkippedDefinitionContext;
2643
2644 /// Invoked when we enter a tag definition that we're skipping.
2645 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2646
2647 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2648
2649 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2650 /// C++ record definition's base-specifiers clause and are starting its
2651 /// member declarations.
2652 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2653 SourceLocation FinalLoc,
2654 bool IsFinalSpelledSealed,
2655 SourceLocation LBraceLoc);
2656
2657 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2658 /// the definition of a tag (enumeration, class, struct, or union).
2659 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2660 SourceRange BraceRange);
2661
2662 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2663
2664 void ActOnObjCContainerFinishDefinition();
2665
2666 /// Invoked when we must temporarily exit the objective-c container
2667 /// scope for parsing/looking-up C constructs.
2668 ///
2669 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2670 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2671 void ActOnObjCReenterContainerContext(DeclContext *DC);
2672
2673 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2674 /// error parsing the definition of a tag.
2675 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2676
2677 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2678 EnumConstantDecl *LastEnumConst,
2679 SourceLocation IdLoc,
2680 IdentifierInfo *Id,
2681 Expr *val);
2682 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2683 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2684 QualType EnumUnderlyingTy, bool IsFixed,
2685 const EnumDecl *Prev);
2686
2687 /// Determine whether the body of an anonymous enumeration should be skipped.
2688 /// \param II The name of the first enumerator.
2689 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2690 SourceLocation IILoc);
2691
2692 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2693 SourceLocation IdLoc, IdentifierInfo *Id,
2694 const ParsedAttributesView &Attrs,
2695 SourceLocation EqualLoc, Expr *Val);
2696 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2697 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2698 const ParsedAttributesView &Attr);
2699
2700 DeclContext *getContainingDC(DeclContext *DC);
2701
2702 /// Set the current declaration context until it gets popped.
2703 void PushDeclContext(Scope *S, DeclContext *DC);
2704 void PopDeclContext();
2705
2706 /// EnterDeclaratorContext - Used when we must lookup names in the context
2707 /// of a declarator's nested name specifier.
2708 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2709 void ExitDeclaratorContext(Scope *S);
2710
2711 /// Push the parameters of D, which must be a function, into scope.
2712 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2713 void ActOnExitFunctionContext();
2714
2715 DeclContext *getFunctionLevelDeclContext();
2716
2717 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2718 /// to the function decl for the function being parsed. If we're currently
2719 /// in a 'block', this returns the containing context.
2720 FunctionDecl *getCurFunctionDecl();
2721
2722 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2723 /// the method decl for the method being parsed. If we're currently
2724 /// in a 'block', this returns the containing context.
2725 ObjCMethodDecl *getCurMethodDecl();
2726
2727 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2728 /// or C function we're in, otherwise return null. If we're currently
2729 /// in a 'block', this returns the containing context.
2730 NamedDecl *getCurFunctionOrMethodDecl();
2731
2732 /// Add this decl to the scope shadowed decl chains.
2733 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2734
2735 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2736 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2737 /// true if 'D' belongs to the given declaration context.
2738 ///
2739 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2740 /// enclosing namespace set of the context, rather than contained
2741 /// directly within it.
2742 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2743 bool AllowInlineNamespace = false);
2744
2745 /// Finds the scope corresponding to the given decl context, if it
2746 /// happens to be an enclosing scope. Otherwise return NULL.
2747 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2748
2749 /// Subroutines of ActOnDeclarator().
2750 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2751 TypeSourceInfo *TInfo);
2752 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2753
2754 /// Describes the kind of merge to perform for availability
2755 /// attributes (including "deprecated", "unavailable", and "availability").
2756 enum AvailabilityMergeKind {
2757 /// Don't merge availability attributes at all.
2758 AMK_None,
2759 /// Merge availability attributes for a redeclaration, which requires
2760 /// an exact match.
2761 AMK_Redeclaration,
2762 /// Merge availability attributes for an override, which requires
2763 /// an exact match or a weakening of constraints.
2764 AMK_Override,
2765 /// Merge availability attributes for an implementation of
2766 /// a protocol requirement.
2767 AMK_ProtocolImplementation,
2768 };
2769
2770 /// Describes the kind of priority given to an availability attribute.
2771 ///
2772 /// The sum of priorities deteremines the final priority of the attribute.
2773 /// The final priority determines how the attribute will be merged.
2774 /// An attribute with a lower priority will always remove higher priority
2775 /// attributes for the specified platform when it is being applied. An
2776 /// attribute with a higher priority will not be applied if the declaration
2777 /// already has an availability attribute with a lower priority for the
2778 /// specified platform. The final prirority values are not expected to match
2779 /// the values in this enumeration, but instead should be treated as a plain
2780 /// integer value. This enumeration just names the priority weights that are
2781 /// used to calculate that final vaue.
2782 enum AvailabilityPriority : int {
2783 /// The availability attribute was specified explicitly next to the
2784 /// declaration.
2785 AP_Explicit = 0,
2786
2787 /// The availability attribute was applied using '#pragma clang attribute'.
2788 AP_PragmaClangAttribute = 1,
2789
2790 /// The availability attribute for a specific platform was inferred from
2791 /// an availability attribute for another platform.
2792 AP_InferredFromOtherPlatform = 2
2793 };
2794
2795 /// Attribute merging methods. Return true if a new attribute was added.
2796 AvailabilityAttr *
2797 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
2798 IdentifierInfo *Platform, bool Implicit,
2799 VersionTuple Introduced, VersionTuple Deprecated,
2800 VersionTuple Obsoleted, bool IsUnavailable,
2801 StringRef Message, bool IsStrict, StringRef Replacement,
2802 AvailabilityMergeKind AMK, int Priority);
2803 TypeVisibilityAttr *
2804 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2805 TypeVisibilityAttr::VisibilityType Vis);
2806 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2807 VisibilityAttr::VisibilityType Vis);
2808 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
2809 StringRef Uuid);
2810 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
2811 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
2812 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
2813 const AttributeCommonInfo &CI,
2814 bool BestCase,
2815 MSInheritanceModel Model);
2816 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
2817 IdentifierInfo *Format, int FormatIdx,
2818 int FirstArg);
2819 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2820 StringRef Name);
2821 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
2822 StringRef Name);
2823 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
2824 const AttributeCommonInfo &CI,
2825 const IdentifierInfo *Ident);
2826 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
2827 NoSpeculativeLoadHardeningAttr *
2828 mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2829 const NoSpeculativeLoadHardeningAttr &AL);
2830 SpeculativeLoadHardeningAttr *
2831 mergeSpeculativeLoadHardeningAttr(Decl *D,
2832 const SpeculativeLoadHardeningAttr &AL);
2833 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
2834 const AttributeCommonInfo &CI);
2835 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2836 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2837 const InternalLinkageAttr &AL);
2838 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2839 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2840
2841 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2842 AvailabilityMergeKind AMK = AMK_Redeclaration);
2843 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2844 LookupResult &OldDecls);
2845 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2846 bool MergeTypeWithOld);
2847 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2848 Scope *S, bool MergeTypeWithOld);
2849 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2850 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2851 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2852 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2853 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2854 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2855 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2856
2857 // AssignmentAction - This is used by all the assignment diagnostic functions
2858 // to represent what is actually causing the operation
2859 enum AssignmentAction {
2860 AA_Assigning,
2861 AA_Passing,
2862 AA_Returning,
2863 AA_Converting,
2864 AA_Initializing,
2865 AA_Sending,
2866 AA_Casting,
2867 AA_Passing_CFAudited
2868 };
2869
2870 /// C++ Overloading.
2871 enum OverloadKind {
2872 /// This is a legitimate overload: the existing declarations are
2873 /// functions or function templates with different signatures.
2874 Ovl_Overload,
2875
2876 /// This is not an overload because the signature exactly matches
2877 /// an existing declaration.
2878 Ovl_Match,
2879
2880 /// This is not an overload because the lookup results contain a
2881 /// non-function.
2882 Ovl_NonFunction
2883 };
2884 OverloadKind CheckOverload(Scope *S,
2885 FunctionDecl *New,
2886 const LookupResult &OldDecls,
2887 NamedDecl *&OldDecl,
2888 bool IsForUsingDecl);
2889 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2890 bool ConsiderCudaAttrs = true,
2891 bool ConsiderRequiresClauses = true);
2892
2893 ImplicitConversionSequence
2894 TryImplicitConversion(Expr *From, QualType ToType,
2895 bool SuppressUserConversions,
2896 bool AllowExplicit,
2897 bool InOverloadResolution,
2898 bool CStyle,
2899 bool AllowObjCWritebackConversion);
2900
2901 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2902 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2903 bool IsComplexPromotion(QualType FromType, QualType ToType);
2904 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2905 bool InOverloadResolution,
2906 QualType& ConvertedType, bool &IncompatibleObjC);
2907 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2908 QualType& ConvertedType, bool &IncompatibleObjC);
2909 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2910 QualType &ConvertedType);
2911 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2912 QualType& ConvertedType);
2913 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2914 const FunctionProtoType *NewType,
2915 unsigned *ArgPos = nullptr);
2916 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2917 QualType FromType, QualType ToType);
2918
2919 void maybeExtendBlockObject(ExprResult &E);
2920 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2921 bool CheckPointerConversion(Expr *From, QualType ToType,
2922 CastKind &Kind,
2923 CXXCastPath& BasePath,
2924 bool IgnoreBaseAccess,
2925 bool Diagnose = true);
2926 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2927 bool InOverloadResolution,
2928 QualType &ConvertedType);
2929 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2930 CastKind &Kind,
2931 CXXCastPath &BasePath,
2932 bool IgnoreBaseAccess);
2933 bool IsQualificationConversion(QualType FromType, QualType ToType,
2934 bool CStyle, bool &ObjCLifetimeConversion);
2935 bool IsFunctionConversion(QualType FromType, QualType ToType,
2936 QualType &ResultTy);
2937 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2938 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2939
2940 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2941 const VarDecl *NRVOCandidate,
2942 QualType ResultType,
2943 Expr *Value,
2944 bool AllowNRVO = true);
2945
2946 bool CanPerformAggregateInitializationForOverloadResolution(
2947 const InitializedEntity &Entity, InitListExpr *From);
2948
2949 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2950 ExprResult Init);
2951 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2952 SourceLocation EqualLoc,
2953 ExprResult Init,
2954 bool TopLevelOfInitList = false,
2955 bool AllowExplicit = false);
2956 ExprResult PerformObjectArgumentInitialization(Expr *From,
2957 NestedNameSpecifier *Qualifier,
2958 NamedDecl *FoundDecl,
2959 CXXMethodDecl *Method);
2960
2961 /// Check that the lifetime of the initializer (and its subobjects) is
2962 /// sufficient for initializing the entity, and perform lifetime extension
2963 /// (when permitted) if not.
2964 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
2965
2966 ExprResult PerformContextuallyConvertToBool(Expr *From);
2967 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2968
2969 /// Contexts in which a converted constant expression is required.
2970 enum CCEKind {
2971 CCEK_CaseValue, ///< Expression in a case label.
2972 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2973 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2974 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2975 CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
2976 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
2977 };
2978 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2979 llvm::APSInt &Value, CCEKind CCE);
2980 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2981 APValue &Value, CCEKind CCE);
2982
2983 /// Abstract base class used to perform a contextual implicit
2984 /// conversion from an expression to any type passing a filter.
2985 class ContextualImplicitConverter {
2986 public:
2987 bool Suppress;
2988 bool SuppressConversion;
2989
2990 ContextualImplicitConverter(bool Suppress = false,
2991 bool SuppressConversion = false)
2992 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2993
2994 /// Determine whether the specified type is a valid destination type
2995 /// for this conversion.
2996 virtual bool match(QualType T) = 0;
2997
2998 /// Emits a diagnostic complaining that the expression does not have
2999 /// integral or enumeration type.
3000 virtual SemaDiagnosticBuilder
3001 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3002
3003 /// Emits a diagnostic when the expression has incomplete class type.
3004 virtual SemaDiagnosticBuilder
3005 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3006
3007 /// Emits a diagnostic when the only matching conversion function
3008 /// is explicit.
3009 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3010 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3011
3012 /// Emits a note for the explicit conversion function.
3013 virtual SemaDiagnosticBuilder
3014 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3015
3016 /// Emits a diagnostic when there are multiple possible conversion
3017 /// functions.
3018 virtual SemaDiagnosticBuilder
3019 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3020
3021 /// Emits a note for one of the candidate conversions.
3022 virtual SemaDiagnosticBuilder
3023 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3024
3025 /// Emits a diagnostic when we picked a conversion function
3026 /// (for cases when we are not allowed to pick a conversion function).
3027 virtual SemaDiagnosticBuilder diagnoseConversion(
3028 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3029
3030 virtual ~ContextualImplicitConverter() {}
3031 };
3032
3033 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3034 bool AllowScopedEnumerations;
3035
3036 public:
3037 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3038 bool Suppress, bool SuppressConversion)
3039 : ContextualImplicitConverter(Suppress, SuppressConversion),
3040 AllowScopedEnumerations(AllowScopedEnumerations) {}
3041
3042 /// Match an integral or (possibly scoped) enumeration type.
3043 bool match(QualType T) override;
3044
3045 SemaDiagnosticBuilder
3046 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3047 return diagnoseNotInt(S, Loc, T);
3048 }
3049
3050 /// Emits a diagnostic complaining that the expression does not have
3051 /// integral or enumeration type.
3052 virtual SemaDiagnosticBuilder
3053 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3054 };
3055
3056 /// Perform a contextual implicit conversion.
3057 ExprResult PerformContextualImplicitConversion(
3058 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3059
3060
3061 enum ObjCSubscriptKind {
3062 OS_Array,
3063 OS_Dictionary,
3064 OS_Error
3065 };
3066 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3067
3068 // Note that LK_String is intentionally after the other literals, as
3069 // this is used for diagnostics logic.
3070 enum ObjCLiteralKind {
3071 LK_Array,
3072 LK_Dictionary,
3073 LK_Numeric,
3074 LK_Boxed,
3075 LK_String,
3076 LK_Block,
3077 LK_None
3078 };
3079 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3080
3081 ExprResult PerformObjectMemberConversion(Expr *From,
3082 NestedNameSpecifier *Qualifier,
3083 NamedDecl *FoundDecl,
3084 NamedDecl *Member);
3085
3086 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3087 // TODO: make this is a typesafe union.
3088 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3089 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3090
3091 using ADLCallKind = CallExpr::ADLCallKind;
3092
3093 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3094 ArrayRef<Expr *> Args,
3095 OverloadCandidateSet &CandidateSet,
3096 bool SuppressUserConversions = false,
3097 bool PartialOverloading = false,
3098 bool AllowExplicit = true,
3099 bool AllowExplicitConversion = false,
3100 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3101 ConversionSequenceList EarlyConversions = None,
3102 OverloadCandidateParamOrder PO = {});
3103 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3104 ArrayRef<Expr *> Args,
3105 OverloadCandidateSet &CandidateSet,
3106 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3107 bool SuppressUserConversions = false,
3108 bool PartialOverloading = false,
3109 bool FirstArgumentIsBase = false);
3110 void AddMethodCandidate(DeclAccessPair FoundDecl,
3111 QualType ObjectType,
3112 Expr::Classification ObjectClassification,
3113 ArrayRef<Expr *> Args,
3114 OverloadCandidateSet& CandidateSet,
3115 bool SuppressUserConversion = false,
3116 OverloadCandidateParamOrder PO = {});
3117 void AddMethodCandidate(CXXMethodDecl *Method,
3118 DeclAccessPair FoundDecl,
3119 CXXRecordDecl *ActingContext, QualType ObjectType,
3120 Expr::Classification ObjectClassification,
3121 ArrayRef<Expr *> Args,
3122 OverloadCandidateSet& CandidateSet,
3123 bool SuppressUserConversions = false,
3124 bool PartialOverloading = false,
3125 ConversionSequenceList EarlyConversions = None,
3126 OverloadCandidateParamOrder PO = {});
3127 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3128 DeclAccessPair FoundDecl,
3129 CXXRecordDecl *ActingContext,
3130 TemplateArgumentListInfo *ExplicitTemplateArgs,
3131 QualType ObjectType,
3132 Expr::Classification ObjectClassification,
3133 ArrayRef<Expr *> Args,
3134 OverloadCandidateSet& CandidateSet,
3135 bool SuppressUserConversions = false,
3136 bool PartialOverloading = false,
3137 OverloadCandidateParamOrder PO = {});
3138 void AddTemplateOverloadCandidate(
3139 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3140 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3141 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3142 bool PartialOverloading = false, bool AllowExplicit = true,
3143 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3144 OverloadCandidateParamOrder PO = {});
3145 bool CheckNonDependentConversions(
3146 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3147 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3148 ConversionSequenceList &Conversions, bool SuppressUserConversions,
3149 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3150 Expr::Classification ObjectClassification = {},
3151 OverloadCandidateParamOrder PO = {});
3152 void AddConversionCandidate(
3153 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3154 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3155 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3156 bool AllowExplicit, bool AllowResultConversion = true);
3157 void AddTemplateConversionCandidate(
3158 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3159 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3160 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3161 bool AllowExplicit, bool AllowResultConversion = true);
3162 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3163 DeclAccessPair FoundDecl,
3164 CXXRecordDecl *ActingContext,
3165 const FunctionProtoType *Proto,
3166 Expr *Object, ArrayRef<Expr *> Args,
3167 OverloadCandidateSet& CandidateSet);
3168 void AddNonMemberOperatorCandidates(
3169 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3170 OverloadCandidateSet &CandidateSet,
3171 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3172 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3173 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3174 OverloadCandidateSet &CandidateSet,
3175 OverloadCandidateParamOrder PO = {});
3176 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3177 OverloadCandidateSet& CandidateSet,
3178 bool IsAssignmentOperator = false,
3179 unsigned NumContextualBoolArguments = 0);
3180 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3181 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3182 OverloadCandidateSet& CandidateSet);
3183 void AddArgumentDependentLookupCandidates(DeclarationName Name,
3184 SourceLocation Loc,
3185 ArrayRef<Expr *> Args,
3186 TemplateArgumentListInfo *ExplicitTemplateArgs,
3187 OverloadCandidateSet& CandidateSet,
3188 bool PartialOverloading = false);
3189
3190 // Emit as a 'note' the specific overload candidate
3191 void NoteOverloadCandidate(
3192 NamedDecl *Found, FunctionDecl *Fn,
3193 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3194 QualType DestType = QualType(), bool TakingAddress = false);
3195
3196 // Emit as a series of 'note's all template and non-templates identified by
3197 // the expression Expr
3198 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3199 bool TakingAddress = false);
3200
3201 /// Check the enable_if expressions on the given function. Returns the first
3202 /// failing attribute, or NULL if they were all successful.
3203 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
3204 bool MissingImplicitThis = false);
3205
3206 /// Find the failed Boolean condition within a given Boolean
3207 /// constant expression, and describe it with a string.
3208 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3209
3210 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3211 /// non-ArgDependent DiagnoseIfAttrs.
3212 ///
3213 /// Argument-dependent diagnose_if attributes should be checked each time a
3214 /// function is used as a direct callee of a function call.
3215 ///
3216 /// Returns true if any errors were emitted.
3217 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3218 const Expr *ThisArg,
3219 ArrayRef<const Expr *> Args,
3220 SourceLocation Loc);
3221
3222 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3223 /// ArgDependent DiagnoseIfAttrs.
3224 ///
3225 /// Argument-independent diagnose_if attributes should be checked on every use
3226 /// of a function.
3227 ///
3228 /// Returns true if any errors were emitted.
3229 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3230 SourceLocation Loc);
3231
3232 /// Returns whether the given function's address can be taken or not,
3233 /// optionally emitting a diagnostic if the address can't be taken.
3234 ///
3235 /// Returns false if taking the address of the function is illegal.
3236 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3237 bool Complain = false,
3238 SourceLocation Loc = SourceLocation());
3239
3240 // [PossiblyAFunctionType] --> [Return]
3241 // NonFunctionType --> NonFunctionType
3242 // R (A) --> R(A)
3243 // R (*)(A) --> R (A)
3244 // R (&)(A) --> R (A)
3245 // R (S::*)(A) --> R (A)
3246 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3247
3248 FunctionDecl *
3249 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3250 QualType TargetType,
3251 bool Complain,
3252 DeclAccessPair &Found,
3253 bool *pHadMultipleCandidates = nullptr);
3254
3255 FunctionDecl *
3256 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3257
3258 bool resolveAndFixAddressOfSingleOverloadCandidate(
3259 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3260
3261 FunctionDecl *
3262 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3263 bool Complain = false,
3264 DeclAccessPair *Found = nullptr);
3265
3266 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3267 ExprResult &SrcExpr,
3268 bool DoFunctionPointerConverion = false,
3269 bool Complain = false,
3270 SourceRange OpRangeForComplaining = SourceRange(),
3271 QualType DestTypeForComplaining = QualType(),
3272 unsigned DiagIDForComplaining = 0);
3273
3274
3275 Expr *FixOverloadedFunctionReference(Expr *E,
3276 DeclAccessPair FoundDecl,
3277 FunctionDecl *Fn);
3278 ExprResult FixOverloadedFunctionReference(ExprResult,
3279 DeclAccessPair FoundDecl,
3280 FunctionDecl *Fn);
3281
3282 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3283 ArrayRef<Expr *> Args,
3284 OverloadCandidateSet &CandidateSet,
3285 bool PartialOverloading = false);
3286
3287 // An enum used to represent the different possible results of building a
3288 // range-based for loop.
3289 enum ForRangeStatus {
3290 FRS_Success,
3291 FRS_NoViableFunction,
3292 FRS_DiagnosticIssued
3293 };
3294
3295 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3296 SourceLocation RangeLoc,
3297 const DeclarationNameInfo &NameInfo,
3298 LookupResult &MemberLookup,
3299 OverloadCandidateSet *CandidateSet,
3300 Expr *Range, ExprResult *CallExpr);
3301
3302 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3303 UnresolvedLookupExpr *ULE,
3304 SourceLocation LParenLoc,
3305 MultiExprArg Args,
3306 SourceLocation RParenLoc,
3307 Expr *ExecConfig,
3308 bool AllowTypoCorrection=true,
3309 bool CalleesAddressIsTaken=false);
3310
3311 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3312 MultiExprArg Args, SourceLocation RParenLoc,
3313 OverloadCandidateSet *CandidateSet,
3314 ExprResult *Result);
3315
3316 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3317 UnaryOperatorKind Opc,
3318 const UnresolvedSetImpl &Fns,
3319 Expr *input, bool RequiresADL = true);
3320
3321 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3322 OverloadedOperatorKind Op,
3323 const UnresolvedSetImpl &Fns,
3324 ArrayRef<Expr *> Args, bool RequiresADL = true);
3325 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3326 BinaryOperatorKind Opc,
3327 const UnresolvedSetImpl &Fns,
3328 Expr *LHS, Expr *RHS,
3329 bool RequiresADL = true,
3330 bool AllowRewrittenCandidates = true,
3331 FunctionDecl *DefaultedFn = nullptr);
3332 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
3333 const UnresolvedSetImpl &Fns,
3334 Expr *LHS, Expr *RHS,
3335 FunctionDecl *DefaultedFn);
3336
3337 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3338 SourceLocation RLoc,
3339 Expr *Base,Expr *Idx);
3340
3341 ExprResult
3342 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3343 SourceLocation LParenLoc,
3344 MultiExprArg Args,
3345 SourceLocation RParenLoc);
3346 ExprResult
3347 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3348 MultiExprArg Args,
3349 SourceLocation RParenLoc);
3350
3351 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3352 SourceLocation OpLoc,
3353 bool *NoArrowOperatorFound = nullptr);
3354
3355 /// CheckCallReturnType - Checks that a call expression's return type is
3356 /// complete. Returns true on failure. The location passed in is the location
3357 /// that best represents the call.
3358 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3359 CallExpr *CE, FunctionDecl *FD);
3360
3361 /// Helpers for dealing with blocks and functions.
3362 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3363 bool CheckParameterNames);
3364 void CheckCXXDefaultArguments(FunctionDecl *FD);
3365 void CheckExtraCXXDefaultArguments(Declarator &D);
3366 Scope *getNonFieldDeclScope(Scope *S);
3367
3368 /// \name Name lookup
3369 ///
3370 /// These routines provide name lookup that is used during semantic
3371 /// analysis to resolve the various kinds of names (identifiers,
3372 /// overloaded operator names, constructor names, etc.) into zero or
3373 /// more declarations within a particular scope. The major entry
3374 /// points are LookupName, which performs unqualified name lookup,
3375 /// and LookupQualifiedName, which performs qualified name lookup.
3376 ///
3377 /// All name lookup is performed based on some specific criteria,
3378 /// which specify what names will be visible to name lookup and how
3379 /// far name lookup should work. These criteria are important both
3380 /// for capturing language semantics (certain lookups will ignore
3381 /// certain names, for example) and for performance, since name
3382 /// lookup is often a bottleneck in the compilation of C++. Name
3383 /// lookup criteria is specified via the LookupCriteria enumeration.
3384 ///
3385 /// The results of name lookup can vary based on the kind of name
3386 /// lookup performed, the current language, and the translation
3387 /// unit. In C, for example, name lookup will either return nothing
3388 /// (no entity found) or a single declaration. In C++, name lookup
3389 /// can additionally refer to a set of overloaded functions or
3390 /// result in an ambiguity. All of the possible results of name
3391 /// lookup are captured by the LookupResult class, which provides
3392 /// the ability to distinguish among them.
3393 //@{
3394
3395 /// Describes the kind of name lookup to perform.
3396 enum LookupNameKind {
3397 /// Ordinary name lookup, which finds ordinary names (functions,
3398 /// variables, typedefs, etc.) in C and most kinds of names
3399 /// (functions, variables, members, types, etc.) in C++.
3400 LookupOrdinaryName = 0,
3401 /// Tag name lookup, which finds the names of enums, classes,
3402 /// structs, and unions.
3403 LookupTagName,
3404 /// Label name lookup.
3405 LookupLabel,
3406 /// Member name lookup, which finds the names of
3407 /// class/struct/union members.
3408 LookupMemberName,
3409 /// Look up of an operator name (e.g., operator+) for use with
3410 /// operator overloading. This lookup is similar to ordinary name
3411 /// lookup, but will ignore any declarations that are class members.
3412 LookupOperatorName,
3413 /// Look up of a name that precedes the '::' scope resolution
3414 /// operator in C++. This lookup completely ignores operator, object,
3415 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3416 LookupNestedNameSpecifierName,
3417 /// Look up a namespace name within a C++ using directive or
3418 /// namespace alias definition, ignoring non-namespace names (C++
3419 /// [basic.lookup.udir]p1).
3420 LookupNamespaceName,
3421 /// Look up all declarations in a scope with the given name,
3422 /// including resolved using declarations. This is appropriate
3423 /// for checking redeclarations for a using declaration.
3424 LookupUsingDeclName,
3425 /// Look up an ordinary name that is going to be redeclared as a
3426 /// name with linkage. This lookup ignores any declarations that
3427 /// are outside of the current scope unless they have linkage. See
3428 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3429 LookupRedeclarationWithLinkage,
3430 /// Look up a friend of a local class. This lookup does not look
3431 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3432 LookupLocalFriendName,
3433 /// Look up the name of an Objective-C protocol.
3434 LookupObjCProtocolName,
3435 /// Look up implicit 'self' parameter of an objective-c method.
3436 LookupObjCImplicitSelfParam,
3437 /// Look up the name of an OpenMP user-defined reduction operation.
3438 LookupOMPReductionName,
3439 /// Look up the name of an OpenMP user-defined mapper.
3440 LookupOMPMapperName,
3441 /// Look up any declaration with any name.
3442 LookupAnyName
3443 };
3444
3445 /// Specifies whether (or how) name lookup is being performed for a
3446 /// redeclaration (vs. a reference).
3447 enum RedeclarationKind {
3448 /// The lookup is a reference to this name that is not for the
3449 /// purpose of redeclaring the name.
3450 NotForRedeclaration = 0,
3451 /// The lookup results will be used for redeclaration of a name,
3452 /// if an entity by that name already exists and is visible.
3453 ForVisibleRedeclaration,
3454 /// The lookup results will be used for redeclaration of a name
3455 /// with external linkage; non-visible lookup results with external linkage
3456 /// may also be found.
3457 ForExternalRedeclaration
3458 };
3459
3460 RedeclarationKind forRedeclarationInCurContext() {
3461 // A declaration with an owning module for linkage can never link against
3462 // anything that is not visible. We don't need to check linkage here; if
3463 // the context has internal linkage, redeclaration lookup won't find things
3464 // from other TUs, and we can't safely compute linkage yet in general.
3465 if (cast<Decl>(CurContext)
3466 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3467 return ForVisibleRedeclaration;
3468 return ForExternalRedeclaration;
3469 }
3470
3471 /// The possible outcomes of name lookup for a literal operator.
3472 enum LiteralOperatorLookupResult {
3473 /// The lookup resulted in an error.
3474 LOLR_Error,
3475 /// The lookup found no match but no diagnostic was issued.
3476 LOLR_ErrorNoDiagnostic,
3477 /// The lookup found a single 'cooked' literal operator, which
3478 /// expects a normal literal to be built and passed to it.
3479 LOLR_Cooked,
3480 /// The lookup found a single 'raw' literal operator, which expects
3481 /// a string literal containing the spelling of the literal token.
3482 LOLR_Raw,
3483 /// The lookup found an overload set of literal operator templates,
3484 /// which expect the characters of the spelling of the literal token to be
3485 /// passed as a non-type template argument pack.
3486 LOLR_Template,
3487 /// The lookup found an overload set of literal operator templates,
3488 /// which expect the character type and characters of the spelling of the
3489 /// string literal token to be passed as template arguments.
3490 LOLR_StringTemplate
3491 };
3492
3493 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3494 CXXSpecialMember SM,
3495 bool ConstArg,
3496 bool VolatileArg,
3497 bool RValueThis,
3498 bool ConstThis,
3499 bool VolatileThis);
3500
3501 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3502 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3503 TypoRecoveryCallback;
3504
3505private:
3506 bool CppLookupName(LookupResult &R, Scope *S);
3507
3508 struct TypoExprState {
3509 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3510 TypoDiagnosticGenerator DiagHandler;
3511 TypoRecoveryCallback RecoveryHandler;
3512 TypoExprState();
3513 TypoExprState(TypoExprState &&other) noexcept;
3514 TypoExprState &operator=(TypoExprState &&other) noexcept;
3515 };
3516
3517 /// The set of unhandled TypoExprs and their associated state.
3518 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3519
3520 /// Creates a new TypoExpr AST node.
3521 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3522 TypoDiagnosticGenerator TDG,
3523 TypoRecoveryCallback TRC);
3524
3525 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3526 //
3527 // The boolean value will be true to indicate that the namespace was loaded
3528 // from an AST/PCH file, or false otherwise.
3529 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3530
3531 /// Whether we have already loaded known namespaces from an extenal
3532 /// source.
3533 bool LoadedExternalKnownNamespaces;
3534
3535 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3536 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3537 /// should be skipped entirely.
3538 std::unique_ptr<TypoCorrectionConsumer>
3539 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3540 Sema::LookupNameKind LookupKind, Scope *S,
3541 CXXScopeSpec *SS,
3542 CorrectionCandidateCallback &CCC,
3543 DeclContext *MemberContext, bool EnteringContext,
3544 const ObjCObjectPointerType *OPT,
3545 bool ErrorRecovery);
3546
3547public:
3548 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3549
3550 /// Clears the state of the given TypoExpr.
3551 void clearDelayedTypo(TypoExpr *TE);
3552
3553 /// Look up a name, looking for a single declaration. Return
3554 /// null if the results were absent, ambiguous, or overloaded.
3555 ///
3556 /// It is preferable to use the elaborated form and explicitly handle
3557 /// ambiguity and overloaded.
3558 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3559 SourceLocation Loc,
3560 LookupNameKind NameKind,
3561 RedeclarationKind Redecl
3562 = NotForRedeclaration);
3563 bool LookupBuiltin(LookupResult &R);
3564 bool LookupName(LookupResult &R, Scope *S,
3565 bool AllowBuiltinCreation = false);
3566 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3567 bool InUnqualifiedLookup = false);
3568 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3569 CXXScopeSpec &SS);
3570 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3571 bool AllowBuiltinCreation = false,
3572 bool EnteringContext = false);
3573 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3574 RedeclarationKind Redecl
3575 = NotForRedeclaration);
3576 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3577
3578 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3579 QualType T1, QualType T2,
3580 UnresolvedSetImpl &Functions);
3581
3582 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3583 SourceLocation GnuLabelLoc = SourceLocation());
3584
3585 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3586 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3587 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3588 unsigned Quals);
3589 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3590 bool RValueThis, unsigned ThisQuals);
3591 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3592 unsigned Quals);
3593 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3594 bool RValueThis, unsigned ThisQuals);
3595 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3596
3597 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3598 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3599 ArrayRef<QualType> ArgTys,
3600 bool AllowRaw,
3601 bool AllowTemplate,
3602 bool AllowStringTemplate,
3603 bool DiagnoseMissing);
3604 bool isKnownName(StringRef name);
3605
3606 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3607 enum class FunctionEmissionStatus {
3608 Emitted,
3609 CUDADiscarded, // Discarded due to CUDA/HIP hostness
3610 OMPDiscarded, // Discarded due to OpenMP hostness
3611 TemplateDiscarded, // Discarded due to uninstantiated templates
3612 Unknown,
3613 };
3614 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
3615
3616 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3617 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
3618
3619 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3620 ArrayRef<Expr *> Args, ADLResult &Functions);
3621
3622 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3623 VisibleDeclConsumer &Consumer,
3624 bool IncludeGlobalScope = true,
3625 bool LoadExternal = true);
3626 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3627 VisibleDeclConsumer &Consumer,
3628 bool IncludeGlobalScope = true,
3629 bool IncludeDependentBases = false,
3630 bool LoadExternal = true);
3631
3632 enum CorrectTypoKind {
3633 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3634 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3635 };
3636
3637 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3638 Sema::LookupNameKind LookupKind,
3639 Scope *S, CXXScopeSpec *SS,
3640 CorrectionCandidateCallback &CCC,
3641 CorrectTypoKind Mode,
3642 DeclContext *MemberContext = nullptr,
3643 bool EnteringContext = false,
3644 const ObjCObjectPointerType *OPT = nullptr,
3645 bool RecordFailure = true);
3646
3647 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3648 Sema::LookupNameKind LookupKind, Scope *S,
3649 CXXScopeSpec *SS,
3650 CorrectionCandidateCallback &CCC,
3651 TypoDiagnosticGenerator TDG,
3652 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3653 DeclContext *MemberContext = nullptr,
3654 bool EnteringContext = false,
3655 const ObjCObjectPointerType *OPT = nullptr);
3656
3657 /// Process any TypoExprs in the given Expr and its children,
3658 /// generating diagnostics as appropriate and returning a new Expr if there
3659 /// were typos that were all successfully corrected and ExprError if one or
3660 /// more typos could not be corrected.
3661 ///
3662 /// \param E The Expr to check for TypoExprs.
3663 ///
3664 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3665 /// initializer.
3666 ///
3667 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3668 /// it is an acceptable/usable result from a single combination of typo
3669 /// corrections. As long as the filter returns ExprError, different
3670 /// combinations of corrections will be tried until all are exhausted.
3671 ExprResult
3672 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3673 llvm::function_ref<ExprResult(Expr *)> Filter =
3674 [](Expr *E) -> ExprResult { return E; });
3675
3676 ExprResult
3677 CorrectDelayedTyposInExpr(Expr *E,
3678 llvm::function_ref<ExprResult(Expr *)> Filter) {
3679 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3680 }
3681
3682 ExprResult
3683 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3684 llvm::function_ref<ExprResult(Expr *)> Filter =
3685 [](Expr *E) -> ExprResult { return E; }) {
3686 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3687 }
3688
3689 ExprResult
3690 CorrectDelayedTyposInExpr(ExprResult ER,
3691 llvm::function_ref<ExprResult(Expr *)> Filter) {
3692 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3693 }
3694
3695 void diagnoseTypo(const TypoCorrection &Correction,
3696 const PartialDiagnostic &TypoDiag,
3697 bool ErrorRecovery = true);
3698
3699 void diagnoseTypo(const TypoCorrection &Correction,
3700 const PartialDiagnostic &TypoDiag,
3701 const PartialDiagnostic &PrevNote,
3702 bool ErrorRecovery = true);
3703
3704 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3705
3706 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3707 ArrayRef<Expr *> Args,
3708 AssociatedNamespaceSet &AssociatedNamespaces,
3709 AssociatedClassSet &AssociatedClasses);
3710
3711 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3712 bool ConsiderLinkage, bool AllowInlineNamespace);
3713
3714 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3715
3716 void DiagnoseAmbiguousLookup(LookupResult &Result);
3717 //@}
3718
3719 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3720 SourceLocation IdLoc,
3721 bool TypoCorrection = false);
3722 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3723 Scope *S, bool ForRedeclaration,
3724 SourceLocation Loc);
3725 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3726 Scope *S);
3727 void AddKnownFunctionAttributes(FunctionDecl *FD);
3728
3729 // More parsing and symbol table subroutines.
3730
3731 void ProcessPragmaWeak(Scope *S, Decl *D);
3732 // Decl attributes - this routine is the top level dispatcher.
3733 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3734 // Helper for delayed processing of attributes.
3735 void ProcessDeclAttributeDelayed(Decl *D,
3736 const ParsedAttributesView &AttrList);
3737 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3738 bool IncludeCXX11Attributes = true);
3739 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3740 const ParsedAttributesView &AttrList);
3741
3742 void checkUnusedDeclAttributes(Declarator &D);
3743
3744 /// Determine if type T is a valid subject for a nonnull and similar
3745 /// attributes. By default, we look through references (the behavior used by
3746 /// nonnull), but if the second parameter is true, then we treat a reference
3747 /// type as valid.
3748 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3749
3750 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3751 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3752 const FunctionDecl *FD = nullptr);
3753 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3754 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3755 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3756 StringRef &Str,
3757 SourceLocation *ArgLocation = nullptr);
3758 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3759 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3760 bool checkMSInheritanceAttrOnDefinition(
3761 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3762 MSInheritanceModel SemanticSpelling);
3763
3764 void CheckAlignasUnderalignment(Decl *D);
3765
3766 /// Adjust the calling convention of a method to be the ABI default if it
3767 /// wasn't specified explicitly. This handles method types formed from
3768 /// function type typedefs and typename template arguments.
3769 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3770 SourceLocation Loc);
3771
3772 // Check if there is an explicit attribute, but only look through parens.
3773 // The intent is to look for an attribute on the current declarator, but not
3774 // one that came from a typedef.
3775 bool hasExplicitCallingConv(QualType T);
3776
3777 /// Get the outermost AttributedType node that sets a calling convention.
3778 /// Valid types should not have multiple attributes with different CCs.
3779 const AttributedType *getCallingConvAttributedType(QualType T) const;
3780
3781 /// Stmt attributes - this routine is the top level dispatcher.
3782 StmtResult ProcessStmtAttributes(Stmt *Stmt,
3783 const ParsedAttributesView &Attrs,
3784 SourceRange Range);
3785
3786 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3787 ObjCMethodDecl *MethodDecl,
3788 bool IsProtocolMethodDecl);
3789
3790 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3791 ObjCMethodDecl *Overridden,
3792 bool IsProtocolMethodDecl);
3793
3794 /// WarnExactTypedMethods - This routine issues a warning if method
3795 /// implementation declaration matches exactly that of its declaration.
3796 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3797 ObjCMethodDecl *MethodDecl,
3798 bool IsProtocolMethodDecl);
3799
3800 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3801
3802 /// CheckImplementationIvars - This routine checks if the instance variables
3803 /// listed in the implelementation match those listed in the interface.
3804 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3805 ObjCIvarDecl **Fields, unsigned nIvars,
3806 SourceLocation Loc);
3807
3808 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3809 /// remains unimplemented in the class or category \@implementation.
3810 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3811 ObjCContainerDecl* IDecl,
3812 bool IncompleteImpl = false);
3813
3814 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3815 /// which must be implemented by this implementation.
3816 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3817 ObjCContainerDecl *CDecl,
3818 bool SynthesizeProperties);
3819
3820 /// Diagnose any null-resettable synthesized setters.
3821 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3822
3823 /// DefaultSynthesizeProperties - This routine default synthesizes all
3824 /// properties which must be synthesized in the class's \@implementation.
3825 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3826 ObjCInterfaceDecl *IDecl,
3827 SourceLocation AtEnd);
3828 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3829
3830 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3831 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3832 /// declared in class 'IFace'.
3833 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3834 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3835
3836 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3837 /// backs the property is not used in the property's accessor.
3838 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3839 const ObjCImplementationDecl *ImplD);
3840
3841 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3842 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3843 /// It also returns ivar's property on success.
3844 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3845 const ObjCPropertyDecl *&PDecl) const;
3846
3847 /// Called by ActOnProperty to handle \@property declarations in
3848 /// class extensions.
3849 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3850 SourceLocation AtLoc,
3851 SourceLocation LParenLoc,
3852 FieldDeclarator &FD,
3853 Selector GetterSel,
3854 SourceLocation GetterNameLoc,
3855 Selector SetterSel,
3856 SourceLocation SetterNameLoc,
3857 const bool isReadWrite,
3858 unsigned &Attributes,
3859 const unsigned AttributesAsWritten,
3860 QualType T,
3861 TypeSourceInfo *TSI,
3862 tok::ObjCKeywordKind MethodImplKind);
3863
3864 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3865 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3866 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3867 ObjCContainerDecl *CDecl,
3868 SourceLocation AtLoc,
3869 SourceLocation LParenLoc,
3870 FieldDeclarator &FD,
3871 Selector GetterSel,
3872 SourceLocation GetterNameLoc,
3873 Selector SetterSel,
3874 SourceLocation SetterNameLoc,
3875 const bool isReadWrite,
3876 const unsigned Attributes,
3877 const unsigned AttributesAsWritten,
3878 QualType T,
3879 TypeSourceInfo *TSI,
3880 tok::ObjCKeywordKind MethodImplKind,
3881 DeclContext *lexicalDC = nullptr);
3882
3883 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3884 /// warning) when atomic property has one but not the other user-declared
3885 /// setter or getter.
3886 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3887 ObjCInterfaceDecl* IDecl);
3888
3889 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3890
3891 void DiagnoseMissingDesignatedInitOverrides(
3892 const ObjCImplementationDecl *ImplD,
3893 const ObjCInterfaceDecl *IFD);
3894
3895 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3896
3897 enum MethodMatchStrategy {
3898 MMS_loose,
3899 MMS_strict
3900 };
3901
3902 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3903 /// true, or false, accordingly.
3904 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3905 const ObjCMethodDecl *PrevMethod,
3906 MethodMatchStrategy strategy = MMS_strict);
3907
3908 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3909 /// or protocol against those declared in their implementations.
3910 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3911 const SelectorSet &ClsMap,
3912 SelectorSet &InsMapSeen,
3913 SelectorSet &ClsMapSeen,
3914 ObjCImplDecl* IMPDecl,
3915 ObjCContainerDecl* IDecl,
3916 bool &IncompleteImpl,
3917 bool ImmediateClass,
3918 bool WarnCategoryMethodImpl=false);
3919
3920 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3921 /// category matches with those implemented in its primary class and
3922 /// warns each time an exact match is found.
3923 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3924
3925 /// Add the given method to the list of globally-known methods.
3926 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3927
3928 /// Returns default addr space for method qualifiers.
3929 LangAS getDefaultCXXMethodAddrSpace() const;
3930
3931private:
3932 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3933 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3934 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3935
3936 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3937 /// optionally warns if there are multiple signatures.
3938 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3939 bool receiverIdOrClass,
3940 bool instance);
3941
3942public:
3943 /// - Returns instance or factory methods in global method pool for
3944 /// given selector. It checks the desired kind first, if none is found, and
3945 /// parameter checkTheOther is set, it then checks the other kind. If no such
3946 /// method or only one method is found, function returns false; otherwise, it
3947 /// returns true.
3948 bool
3949 CollectMultipleMethodsInGlobalPool(Selector Sel,
3950 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3951 bool InstanceFirst, bool CheckTheOther,
3952 const ObjCObjectType *TypeBound = nullptr);
3953
3954 bool
3955 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3956 SourceRange R, bool receiverIdOrClass,
3957 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3958
3959 void
3960 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3961 Selector Sel, SourceRange R,
3962 bool receiverIdOrClass);
3963
3964private:
3965 /// - Returns a selector which best matches given argument list or
3966 /// nullptr if none could be found
3967 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3968 bool IsInstance,
3969 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3970
3971
3972 /// Record the typo correction failure and return an empty correction.
3973 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3974 bool RecordFailure = true) {
3975 if (RecordFailure)
3976 TypoCorrectionFailures[Typo].insert(TypoLoc);
3977 return TypoCorrection();
3978 }
3979
3980public:
3981 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3982 /// unit are added to a global pool. This allows us to efficiently associate
3983 /// a selector with a method declaraation for purposes of typechecking
3984 /// messages sent to "id" (where the class of the object is unknown).
3985 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3986 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3987 }
3988
3989 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3990 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3991 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3992 }
3993
3994 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3995 /// pool.
3996 void AddAnyMethodToGlobalPool(Decl *D);
3997
3998 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3999 /// there are multiple signatures.
4000 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4001 bool receiverIdOrClass=false) {
4002 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4003 /*instance*/true);
4004 }
4005
4006 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4007 /// there are multiple signatures.
4008 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4009 bool receiverIdOrClass=false) {
4010 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4011 /*instance*/false);
4012 }
4013
4014 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4015 QualType ObjectType=QualType());
4016 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4017 /// implementation.
4018 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4019
4020 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4021 /// initialization.
4022 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4023 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4024
4025 //===--------------------------------------------------------------------===//
4026 // Statement Parsing Callbacks: SemaStmt.cpp.
4027public:
4028 class FullExprArg {
4029 public:
4030 FullExprArg() : E(nullptr) { }
4031 FullExprArg(Sema &actions) : E(nullptr) { }
4032
4033 ExprResult release() {
4034 return E;
4035 }
4036
4037 Expr *get() const { return E; }
4038
4039 Expr *operator->() {
4040 return E;
4041 }
4042
4043 private:
4044 // FIXME: No need to make the entire Sema class a friend when it's just
4045 // Sema::MakeFullExpr that needs access to the constructor below.
4046 friend class Sema;
4047
4048 explicit FullExprArg(Expr *expr) : E(expr) {}
4049
4050 Expr *E;
4051 };
4052
4053 FullExprArg MakeFullExpr(Expr *Arg) {
4054 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4055 }
4056 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4057 return FullExprArg(
4058 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4059 }
4060 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4061 ExprResult FE =
4062 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4063 /*DiscardedValue*/ true);
4064 return FullExprArg(FE.get());
4065 }
4066
4067 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4068 StmtResult ActOnExprStmtError();
4069
4070 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4071 bool HasLeadingEmptyMacro = false);
4072
4073 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4074 void ActOnFinishOfCompoundStmt();
4075 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4076 ArrayRef<Stmt *> Elts, bool isStmtExpr);
4077
4078 /// A RAII object to enter scope of a compound statement.
4079 class CompoundScopeRAII {
4080 public:
4081 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4082 S.ActOnStartOfCompoundStmt(IsStmtExpr);
4083 }
4084
4085 ~CompoundScopeRAII() {
4086 S.ActOnFinishOfCompoundStmt();
4087 }
4088
4089 private:
4090 Sema &S;
4091 };
4092
4093 /// An RAII helper that pops function a function scope on exit.
4094 struct FunctionScopeRAII {
4095 Sema &S;
4096 bool Active;
4097 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4098 ~FunctionScopeRAII() {
4099 if (Active)
4100 S.PopFunctionScopeInfo();
4101 }
4102 void disable() { Active = false; }
4103 };
4104
4105 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4106 SourceLocation StartLoc,
4107 SourceLocation EndLoc);
4108 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4109 StmtResult ActOnForEachLValueExpr(Expr *E);
4110 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4111 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4112 SourceLocation DotDotDotLoc, ExprResult RHS,
4113 SourceLocation ColonLoc);
4114 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4115
4116 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4117 SourceLocation ColonLoc,
4118 Stmt *SubStmt, Scope *CurScope);
4119 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4120 SourceLocation ColonLoc, Stmt *SubStmt);
4121
4122 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4123 ArrayRef<const Attr*> Attrs,
4124 Stmt *SubStmt);
4125
4126 class ConditionResult;
4127 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4128 Stmt *InitStmt,
4129 ConditionResult Cond, Stmt *ThenVal,
4130 SourceLocation ElseLoc, Stmt *ElseVal);
4131 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4132 Stmt *InitStmt,
4133 ConditionResult Cond, Stmt *ThenVal,
4134 SourceLocation ElseLoc, Stmt *ElseVal);
4135 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4136 Stmt *InitStmt,
4137 ConditionResult Cond);
4138 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4139 Stmt *Switch, Stmt *Body);
4140 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
4141 Stmt *Body);
4142 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4143 SourceLocation WhileLoc, SourceLocation CondLParen,
4144 Expr *Cond, SourceLocation CondRParen);
4145
4146 StmtResult ActOnForStmt(SourceLocation ForLoc,
4147 SourceLocation LParenLoc,
4148 Stmt *First,
4149 ConditionResult Second,
4150 FullExprArg Third,
4151 SourceLocation RParenLoc,
4152 Stmt *Body);
4153 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4154 Expr *collection);
4155 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4156 Stmt *First, Expr *collection,
4157 SourceLocation RParenLoc);
4158 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4159
4160 enum BuildForRangeKind {
4161 /// Initial building of a for-range statement.
4162 BFRK_Build,
4163 /// Instantiation or recovery rebuild of a for-range statement. Don't
4164 /// attempt any typo-correction.
4165 BFRK_Rebuild,
4166 /// Determining whether a for-range statement could be built. Avoid any
4167 /// unnecessary or irreversible actions.
4168 BFRK_Check
4169 };
4170
4171 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4172 SourceLocation CoawaitLoc,
4173 Stmt *InitStmt,
4174 Stmt *LoopVar,
4175 SourceLocation ColonLoc, Expr *Collection,
4176 SourceLocation RParenLoc,
4177 BuildForRangeKind Kind);
4178 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4179 SourceLocation CoawaitLoc,
4180 Stmt *InitStmt,
4181 SourceLocation ColonLoc,
4182 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4183 Expr *Cond, Expr *Inc,
4184 Stmt *LoopVarDecl,
4185 SourceLocation RParenLoc,
4186 BuildForRangeKind Kind);
4187 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4188
4189 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4190 SourceLocation LabelLoc,
4191 LabelDecl *TheDecl);
4192 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4193 SourceLocation StarLoc,
4194 Expr *DestExp);
4195 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4196 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4197
4198 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4199 CapturedRegionKind Kind, unsigned NumParams);
4200 typedef std::pair<StringRef, QualType> CapturedParamNameType;
4201 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4202 CapturedRegionKind Kind,
4203 ArrayRef<CapturedParamNameType> Params,
4204 unsigned OpenMPCaptureLevel = 0);
4205 StmtResult ActOnCapturedRegionEnd(Stmt *S);
4206 void ActOnCapturedRegionError();
4207 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4208 SourceLocation Loc,
4209 unsigned NumParams);
4210
4211 enum CopyElisionSemanticsKind {
4212 CES_Strict = 0,
4213 CES_AllowParameters = 1,
4214 CES_AllowDifferentTypes = 2,
4215 CES_AllowExceptionVariables = 4,
4216 CES_FormerDefault = (CES_AllowParameters),
4217 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4218 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4219 CES_AllowExceptionVariables),
4220 };
4221
4222 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4223 CopyElisionSemanticsKind CESK);
4224 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4225 CopyElisionSemanticsKind CESK);
4226
4227 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4228 Scope *CurScope);
4229 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4230 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4231
4232 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4233 bool IsVolatile, unsigned NumOutputs,
4234 unsigned NumInputs, IdentifierInfo **Names,
4235 MultiExprArg Constraints, MultiExprArg Exprs,
4236 Expr *AsmString, MultiExprArg Clobbers,
4237 unsigned NumLabels,
4238 SourceLocation RParenLoc);
4239
4240 void FillInlineAsmIdentifierInfo(Expr *Res,
4241 llvm::InlineAsmIdentifierInfo &Info);
4242 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4243 SourceLocation TemplateKWLoc,
4244 UnqualifiedId &Id,
4245 bool IsUnevaluatedContext);
4246 bool LookupInlineAsmField(StringRef Base, StringRef Member,
4247 unsigned &Offset, SourceLocation AsmLoc);
4248 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4249 SourceLocation AsmLoc);
4250 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4251 ArrayRef<Token> AsmToks,
4252 StringRef AsmString,
4253 unsigned NumOutputs, unsigned NumInputs,
4254 ArrayRef<StringRef> Constraints,
4255 ArrayRef<StringRef> Clobbers,
4256 ArrayRef<Expr*> Exprs,
4257 SourceLocation EndLoc);
4258 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4259 SourceLocation Location,
4260 bool AlwaysCreate);
4261
4262 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4263 SourceLocation StartLoc,
4264 SourceLocation IdLoc, IdentifierInfo *Id,
4265 bool Invalid = false);
4266
4267 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4268
4269 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4270 Decl *Parm, Stmt *Body);
4271
4272 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4273
4274 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4275 MultiStmtArg Catch, Stmt *Finally);
4276
4277 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4278 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4279 Scope *CurScope);
4280 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4281 Expr *operand);
4282 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4283 Expr *SynchExpr,
4284 Stmt *SynchBody);
4285
4286 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4287
4288 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4289 SourceLocation StartLoc,
4290 SourceLocation IdLoc,
4291 IdentifierInfo *Id);
4292
4293 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4294
4295 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4296 Decl *ExDecl, Stmt *HandlerBlock);
4297 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4298 ArrayRef<Stmt *> Handlers);
4299
4300 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4301 SourceLocation TryLoc, Stmt *TryBlock,
4302 Stmt *Handler);
4303 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4304 Expr *FilterExpr,
4305 Stmt *Block);
4306 void ActOnStartSEHFinallyBlock();
4307 void ActOnAbortSEHFinallyBlock();
4308 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4309 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4310
4311 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4312
4313 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4314
4315 /// If it's a file scoped decl that must warn if not used, keep track
4316 /// of it.
4317 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4318
4319 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4320 /// whose result is unused, warn.
4321 void DiagnoseUnusedExprResult(const Stmt *S);
4322 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4323 void DiagnoseUnusedDecl(const NamedDecl *ND);
4324
4325 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4326 /// statement as a \p Body, and it is located on the same line.
4327 ///
4328 /// This helps prevent bugs due to typos, such as:
4329 /// if (condition);
4330 /// do_stuff();
4331 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4332 const Stmt *Body,
4333 unsigned DiagID);
4334
4335 /// Warn if a for/while loop statement \p S, which is followed by
4336 /// \p PossibleBody, has a suspicious null statement as a body.
4337 void DiagnoseEmptyLoopBody(const Stmt *S,
4338 const Stmt *PossibleBody);
4339
4340 /// Warn if a value is moved to itself.
4341 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4342 SourceLocation OpLoc);
4343
4344 /// Warn if we're implicitly casting from a _Nullable pointer type to a
4345 /// _Nonnull one.
4346 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4347 SourceLocation Loc);
4348
4349 /// Warn when implicitly casting 0 to nullptr.
4350 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4351
4352 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4353 return DelayedDiagnostics.push(pool);
4354 }
4355 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4356
4357 typedef ProcessingContextState ParsingClassState;
4358 ParsingClassState PushParsingClass() {
4359 ParsingClassDepth++;
4360 return DelayedDiagnostics.pushUndelayed();
4361 }
4362 void PopParsingClass(ParsingClassState state) {
4363 ParsingClassDepth--;
4364 DelayedDiagnostics.popUndelayed(state);
4365 }
4366
4367 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4368
4369 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4370 const ObjCInterfaceDecl *UnknownObjCClass,
4371 bool ObjCPropertyAccess,
4372 bool AvoidPartialAvailabilityChecks = false,
4373 ObjCInterfaceDecl *ClassReceiver = nullptr);
4374
4375 bool makeUnavailableInSystemHeader(SourceLocation loc,
4376 UnavailableAttr::ImplicitReason reason);
4377
4378 /// Issue any -Wunguarded-availability warnings in \c FD
4379 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4380
4381 //===--------------------------------------------------------------------===//
4382 // Expression Parsing Callbacks: SemaExpr.cpp.
4383
4384 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4385 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4386 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4387 bool ObjCPropertyAccess = false,
4388 bool AvoidPartialAvailabilityChecks = false,
4389 ObjCInterfaceDecl *ClassReciever = nullptr);
4390 void NoteDeletedFunction(FunctionDecl *FD);
4391 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4392 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4393 ObjCMethodDecl *Getter,
4394 SourceLocation Loc);
4395 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4396 ArrayRef<Expr *> Args);
4397
4398 void PushExpressionEvaluationContext(
4399 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4400 ExpressionEvaluationContextRecord::ExpressionKind Type =
4401 ExpressionEvaluationContextRecord::EK_Other);
4402 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4403 void PushExpressionEvaluationContext(
4404 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4405 ExpressionEvaluationContextRecord::ExpressionKind Type =
4406 ExpressionEvaluationContextRecord::EK_Other);
4407 void PopExpressionEvaluationContext();
4408
4409 void DiscardCleanupsInEvaluationContext();
4410
4411 ExprResult TransformToPotentiallyEvaluated(Expr *E);
4412 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4413
4414 ExprResult CheckUnevaluatedOperand(Expr *E);
4415 void CheckUnusedVolatileAssignment(Expr *E);
4416
4417 ExprResult ActOnConstantExpression(ExprResult Res);
4418
4419 // Functions for marking a declaration referenced. These functions also
4420 // contain the relevant logic for marking if a reference to a function or
4421 // variable is an odr-use (in the C++11 sense). There are separate variants
4422 // for expressions referring to a decl; these exist because odr-use marking
4423 // needs to be delayed for some constant variables when we build one of the
4424 // named expressions.
4425 //
4426 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4427 // should usually be true. This only needs to be set to false if the lack of
4428 // odr-use cannot be determined from the current context (for instance,
4429 // because the name denotes a virtual function and was written without an
4430 // explicit nested-name-specifier).
4431 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4432 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4433 bool MightBeOdrUse = true);
4434 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4435 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4436 void MarkMemberReferenced(MemberExpr *E);
4437 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4438 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4439 unsigned CapturingScopeIndex);
4440
4441 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4442 void CleanupVarDeclMarking();
4443
4444 enum TryCaptureKind {
4445 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4446 };
4447
4448 /// Try to capture the given variable.
4449 ///
4450 /// \param Var The variable to capture.
4451 ///
4452 /// \param Loc The location at which the capture occurs.
4453 ///
4454 /// \param Kind The kind of capture, which may be implicit (for either a
4455 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4456 ///
4457 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4458 /// an explicit lambda capture.
4459 ///
4460 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4461 /// captures or diagnose errors. If false, this routine merely check whether
4462 /// the capture can occur without performing the capture itself or complaining
4463 /// if the variable cannot be captured.
4464 ///
4465 /// \param CaptureType Will be set to the type of the field used to capture
4466 /// this variable in the innermost block or lambda. Only valid when the
4467 /// variable can be captured.
4468 ///
4469 /// \param DeclRefType Will be set to the type of a reference to the capture
4470 /// from within the current scope. Only valid when the variable can be
4471 /// captured.
4472 ///
4473 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4474 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4475 /// This is useful when enclosing lambdas must speculatively capture
4476 /// variables that may or may not be used in certain specializations of
4477 /// a nested generic lambda.
4478 ///
4479 /// \returns true if an error occurred (i.e., the variable cannot be
4480 /// captured) and false if the capture succeeded.
4481 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4482 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4483 QualType &CaptureType,
4484 QualType &DeclRefType,
4485 const unsigned *const FunctionScopeIndexToStopAt);
4486
4487 /// Try to capture the given variable.
4488 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4489 TryCaptureKind Kind = TryCapture_Implicit,
4490 SourceLocation EllipsisLoc = SourceLocation());
4491
4492 /// Checks if the variable must be captured.
4493 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4494
4495 /// Given a variable, determine the type that a reference to that
4496 /// variable will have in the given scope.
4497 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4498
4499 /// Mark all of the declarations referenced within a particular AST node as
4500 /// referenced. Used when template instantiation instantiates a non-dependent
4501 /// type -- entities referenced by the type are now referenced.
4502 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4503 void MarkDeclarationsReferencedInExpr(Expr *E,
4504 bool SkipLocalVariables = false);
4505
4506 /// Try to recover by turning the given expression into a
4507 /// call. Returns true if recovery was attempted or an error was
4508 /// emitted; this may also leave the ExprResult invalid.
4509 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4510 bool ForceComplain = false,
4511 bool (*IsPlausibleResult)(QualType) = nullptr);
4512
4513 /// Figure out if an expression could be turned into a call.
4514 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4515 UnresolvedSetImpl &NonTemplateOverloads);
4516
4517 /// Conditionally issue a diagnostic based on the current
4518 /// evaluation context.
4519 ///
4520 /// \param Statement If Statement is non-null, delay reporting the
4521 /// diagnostic until the function body is parsed, and then do a basic
4522 /// reachability analysis to determine if the statement is reachable.
4523 /// If it is unreachable, the diagnostic will not be emitted.
4524 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4525 const PartialDiagnostic &PD);
4526 /// Similar, but diagnostic is only produced if all the specified statements
4527 /// are reachable.
4528 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4529 const PartialDiagnostic &PD);
4530
4531 // Primary Expressions.
4532 SourceRange getExprRange(Expr *E) const;
4533
4534 ExprResult ActOnIdExpression(
4535 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4536 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4537 CorrectionCandidateCallback *CCC = nullptr,
4538 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4539
4540 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4541 TemplateArgumentListInfo &Buffer,
4542 DeclarationNameInfo &NameInfo,
4543 const TemplateArgumentListInfo *&TemplateArgs);
4544
4545 bool
4546 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4547 CorrectionCandidateCallback &CCC,
4548 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4549 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4550
4551 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4552 IdentifierInfo *II);
4553 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4554
4555 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4556 IdentifierInfo *II,
4557 bool AllowBuiltinCreation=false);
4558
4559 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4560 SourceLocation TemplateKWLoc,
4561 const DeclarationNameInfo &NameInfo,
4562 bool isAddressOfOperand,
4563 const TemplateArgumentListInfo *TemplateArgs);
4564
4565 /// If \p D cannot be odr-used in the current expression evaluation context,
4566 /// return a reason explaining why. Otherwise, return NOUR_None.
4567 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4568
4569 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4570 SourceLocation Loc,
4571 const CXXScopeSpec *SS = nullptr);
4572 DeclRefExpr *
4573 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4574 const DeclarationNameInfo &NameInfo,
4575 const CXXScopeSpec *SS = nullptr,
4576 NamedDecl *FoundD = nullptr,
4577 SourceLocation TemplateKWLoc = SourceLocation(),
4578 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4579 DeclRefExpr *
4580 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4581 const DeclarationNameInfo &NameInfo,
4582 NestedNameSpecifierLoc NNS,
4583 NamedDecl *FoundD = nullptr,
4584 SourceLocation TemplateKWLoc = SourceLocation(),
4585 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4586
4587 ExprResult
4588 BuildAnonymousStructUnionMemberReference(
4589 const CXXScopeSpec &SS,
4590 SourceLocation nameLoc,
4591 IndirectFieldDecl *indirectField,
4592 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4593 Expr *baseObjectExpr = nullptr,
4594 SourceLocation opLoc = SourceLocation());
4595
4596 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4597 SourceLocation TemplateKWLoc,
4598 LookupResult &R,
4599 const TemplateArgumentListInfo *TemplateArgs,
4600 const Scope *S);
4601 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4602 SourceLocation TemplateKWLoc,
4603 LookupResult &R,
4604 const TemplateArgumentListInfo *TemplateArgs,
4605 bool IsDefiniteInstance,
4606 const Scope *S);
4607 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4608 const LookupResult &R,
4609 bool HasTrailingLParen);
4610
4611 ExprResult
4612 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4613 const DeclarationNameInfo &NameInfo,
4614 bool IsAddressOfOperand, const Scope *S,
4615 TypeSourceInfo **RecoveryTSI = nullptr);
4616
4617 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4618 SourceLocation TemplateKWLoc,
4619 const DeclarationNameInfo &NameInfo,
4620 const TemplateArgumentListInfo *TemplateArgs);
4621
4622 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4623 LookupResult &R,
4624 bool NeedsADL,
4625 bool AcceptInvalidDecl = false);
4626 ExprResult BuildDeclarationNameExpr(
4627 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4628 NamedDecl *FoundD = nullptr,
4629 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4630 bool AcceptInvalidDecl = false);
4631
4632 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4633 DeclarationNameInfo &SuffixInfo,
4634 ArrayRef<Expr *> Args,
4635 SourceLocation LitEndLoc,
4636 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4637
4638 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4639 PredefinedExpr::IdentKind IK);
4640 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4641 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4642
4643 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4644
4645 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4646 ExprResult ActOnCharacterConstant(const Token &Tok,
4647 Scope *UDLScope = nullptr);
4648 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4649 ExprResult ActOnParenListExpr(SourceLocation L,
4650 SourceLocation R,
4651 MultiExprArg Val);
4652
4653 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4654 /// fragments (e.g. "foo" "bar" L"baz").
4655 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4656 Scope *UDLScope = nullptr);
4657
4658 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4659 SourceLocation DefaultLoc,
4660 SourceLocation RParenLoc,
4661 Expr *ControllingExpr,
4662 ArrayRef<ParsedType> ArgTypes,
4663 ArrayRef<Expr *> ArgExprs);
4664 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4665 SourceLocation DefaultLoc,
4666 SourceLocation RParenLoc,
4667 Expr *ControllingExpr,
4668 ArrayRef<TypeSourceInfo *> Types,
4669 ArrayRef<Expr *> Exprs);
4670
4671 // Binary/Unary Operators. 'Tok' is the token for the operator.
4672 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4673 Expr *InputExpr);
4674 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4675 UnaryOperatorKind Opc, Expr *Input);
4676 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4677 tok::TokenKind Op, Expr *Input);
4678
4679 bool isQualifiedMemberAccess(Expr *E);
4680 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4681
4682 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4683 SourceLocation OpLoc,
4684 UnaryExprOrTypeTrait ExprKind,
4685 SourceRange R);
4686 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4687 UnaryExprOrTypeTrait ExprKind);
4688 ExprResult
4689 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4690 UnaryExprOrTypeTrait ExprKind,
4691 bool IsType, void *TyOrEx,
4692 SourceRange ArgRange);
4693
4694 ExprResult CheckPlaceholderExpr(Expr *E);
4695 bool CheckVecStepExpr(Expr *E);
4696
4697 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4698 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4699 SourceRange ExprRange,
4700 UnaryExprOrTypeTrait ExprKind);
4701 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4702 SourceLocation OpLoc,
4703 IdentifierInfo &Name,
4704 SourceLocation NameLoc,
4705 SourceLocation RParenLoc);
4706 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4707 tok::TokenKind Kind, Expr *Input);
4708
4709 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4710 Expr *Idx, SourceLocation RLoc);
4711 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4712 Expr *Idx, SourceLocation RLoc);
4713 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4714 Expr *LowerBound, SourceLocation ColonLoc,
4715 Expr *Length, SourceLocation RBLoc);
4716
4717 // This struct is for use by ActOnMemberAccess to allow
4718 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4719 // changing the access operator from a '.' to a '->' (to see if that is the
4720 // change needed to fix an error about an unknown member, e.g. when the class
4721 // defines a custom operator->).
4722 struct ActOnMemberAccessExtraArgs {
4723 Scope *S;
4724 UnqualifiedId &Id;
4725 Decl *ObjCImpDecl;
4726 };
4727
4728 ExprResult BuildMemberReferenceExpr(
4729 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4730 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4731 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4732 const TemplateArgumentListInfo *TemplateArgs,
4733 const Scope *S,
4734 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4735
4736 ExprResult
4737 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4738 bool IsArrow, const CXXScopeSpec &SS,
4739 SourceLocation TemplateKWLoc,
4740 NamedDecl *FirstQualifierInScope, LookupResult &R,
4741 const TemplateArgumentListInfo *TemplateArgs,
4742 const Scope *S,
4743 bool SuppressQualifierCheck = false,
4744 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4745
4746 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4747 SourceLocation OpLoc,
4748 const CXXScopeSpec &SS, FieldDecl *Field,
4749 DeclAccessPair FoundDecl,
4750 const DeclarationNameInfo &MemberNameInfo);
4751
4752 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4753
4754 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4755 const CXXScopeSpec &SS,
4756 const LookupResult &R);
4757
4758 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4759 bool IsArrow, SourceLocation OpLoc,
4760 const CXXScopeSpec &SS,
4761 SourceLocation TemplateKWLoc,
4762 NamedDecl *FirstQualifierInScope,
4763 const DeclarationNameInfo &NameInfo,
4764 const TemplateArgumentListInfo *TemplateArgs);
4765
4766 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4767 SourceLocation OpLoc,
4768 tok::TokenKind OpKind,
4769 CXXScopeSpec &SS,
4770 SourceLocation TemplateKWLoc,
4771 UnqualifiedId &Member,
4772 Decl *ObjCImpDecl);
4773
4774 MemberExpr *
4775 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4776 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
4777 ValueDecl *Member, DeclAccessPair FoundDecl,
4778 bool HadMultipleCandidates,
4779 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4780 ExprValueKind VK, ExprObjectKind OK,
4781 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4782 MemberExpr *
4783 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4784 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
4785 ValueDecl *Member, DeclAccessPair FoundDecl,
4786 bool HadMultipleCandidates,
4787 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4788 ExprValueKind VK, ExprObjectKind OK,
4789 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4790
4791 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4792 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4793 FunctionDecl *FDecl,
4794 const FunctionProtoType *Proto,
4795 ArrayRef<Expr *> Args,
4796 SourceLocation RParenLoc,
4797 bool ExecConfig = false);
4798 void CheckStaticArrayArgument(SourceLocation CallLoc,
4799 ParmVarDecl *Param,
4800 const Expr *ArgExpr);
4801
4802 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4803 /// This provides the location of the left/right parens and a list of comma
4804 /// locations.
4805 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4806 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4807 Expr *ExecConfig = nullptr);
4808 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4809 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4810 Expr *ExecConfig = nullptr,
4811 bool IsExecConfig = false);
4812 enum class AtomicArgumentOrder { API, AST };
4813 ExprResult
4814 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4815 SourceLocation RParenLoc, MultiExprArg Args,
4816 AtomicExpr::AtomicOp Op,
4817 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
4818 ExprResult
4819 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
4820 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
4821 Expr *Config = nullptr, bool IsExecConfig = false,
4822 ADLCallKind UsesADL = ADLCallKind::NotADL);
4823
4824 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4825 MultiExprArg ExecConfig,
4826 SourceLocation GGGLoc);
4827
4828 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4829 Declarator &D, ParsedType &Ty,
4830 SourceLocation RParenLoc, Expr *CastExpr);
4831 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4832 TypeSourceInfo *Ty,
4833 SourceLocation RParenLoc,
4834 Expr *Op);
4835 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4836
4837 /// Build an altivec or OpenCL literal.
4838 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4839 SourceLocation RParenLoc, Expr *E,
4840 TypeSourceInfo *TInfo);
4841
4842 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4843
4844 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4845 ParsedType Ty,
4846 SourceLocation RParenLoc,
4847 Expr *InitExpr);
4848
4849 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4850 TypeSourceInfo *TInfo,
4851 SourceLocation RParenLoc,
4852 Expr *LiteralExpr);
4853
4854 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4855 MultiExprArg InitArgList,
4856 SourceLocation RBraceLoc);
4857
4858 ExprResult BuildInitList(SourceLocation LBraceLoc,
4859 MultiExprArg InitArgList,
4860 SourceLocation RBraceLoc);
4861
4862 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4863 SourceLocation EqualOrColonLoc,
4864 bool GNUSyntax,
4865 ExprResult Init);
4866
4867private:
4868 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4869
4870public:
4871 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4872 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4873 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4874 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4875 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4876 Expr *LHSExpr, Expr *RHSExpr);
4877
4878 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4879
4880 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4881 /// in the case of a the GNU conditional expr extension.
4882 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4883 SourceLocation ColonLoc,
4884 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4885
4886 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4887 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4888 LabelDecl *TheDecl);
4889
4890 void ActOnStartStmtExpr();
4891 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4892 SourceLocation RPLoc); // "({..})"
4893 // Handle the final expression in a statement expression.
4894 ExprResult ActOnStmtExprResult(ExprResult E);
4895 void ActOnStmtExprError();
4896
4897 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4898 struct OffsetOfComponent {
4899 SourceLocation LocStart, LocEnd;
4900 bool isBrackets; // true if [expr], false if .ident
4901 union {
4902 IdentifierInfo *IdentInfo;
4903 Expr *E;
4904 } U;
4905 };
4906
4907 /// __builtin_offsetof(type, a.b[123][456].c)
4908 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4909 TypeSourceInfo *TInfo,
4910 ArrayRef<OffsetOfComponent> Components,
4911 SourceLocation RParenLoc);
4912 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4913 SourceLocation BuiltinLoc,
4914 SourceLocation TypeLoc,
4915 ParsedType ParsedArgTy,
4916 ArrayRef<OffsetOfComponent> Components,
4917 SourceLocation RParenLoc);
4918
4919 // __builtin_choose_expr(constExpr, expr1, expr2)
4920 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4921 Expr *CondExpr, Expr *LHSExpr,
4922 Expr *RHSExpr, SourceLocation RPLoc);
4923
4924 // __builtin_va_arg(expr, type)
4925 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4926 SourceLocation RPLoc);
4927 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4928 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4929
4930 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
4931 // __builtin_COLUMN()
4932 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
4933 SourceLocation BuiltinLoc,
4934 SourceLocation RPLoc);
4935
4936 // Build a potentially resolved SourceLocExpr.
4937 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
4938 SourceLocation BuiltinLoc, SourceLocation RPLoc,
4939 DeclContext *ParentContext);
4940
4941 // __null
4942 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4943
4944 bool CheckCaseExpression(Expr *E);
4945
4946 /// Describes the result of an "if-exists" condition check.
4947 enum IfExistsResult {
4948 /// The symbol exists.
4949 IER_Exists,
4950
4951 /// The symbol does not exist.
4952 IER_DoesNotExist,
4953
4954 /// The name is a dependent name, so the results will differ
4955 /// from one instantiation to the next.
4956 IER_Dependent,
4957
4958 /// An error occurred.
4959 IER_Error
4960 };
4961
4962 IfExistsResult
4963 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4964 const DeclarationNameInfo &TargetNameInfo);
4965
4966 IfExistsResult
4967 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4968 bool IsIfExists, CXXScopeSpec &SS,
4969 UnqualifiedId &Name);
4970
4971 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4972 bool IsIfExists,
4973 NestedNameSpecifierLoc QualifierLoc,
4974 DeclarationNameInfo NameInfo,
4975 Stmt *Nested);
4976 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4977 bool IsIfExists,
4978 CXXScopeSpec &SS, UnqualifiedId &Name,
4979 Stmt *Nested);
4980
4981 //===------------------------- "Block" Extension ------------------------===//
4982
4983 /// ActOnBlockStart - This callback is invoked when a block literal is
4984 /// started.
4985 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4986
4987 /// ActOnBlockArguments - This callback allows processing of block arguments.
4988 /// If there are no arguments, this is still invoked.
4989 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4990 Scope *CurScope);
4991
4992 /// ActOnBlockError - If there is an error parsing a block, this callback
4993 /// is invoked to pop the information about the block from the action impl.
4994 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4995
4996 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4997 /// literal was successfully completed. ^(int x){...}
4998 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4999 Scope *CurScope);
5000
5001 //===---------------------------- Clang Extensions ----------------------===//
5002
5003 /// __builtin_convertvector(...)
5004 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5005 SourceLocation BuiltinLoc,
5006 SourceLocation RParenLoc);
5007
5008 //===---------------------------- OpenCL Features -----------------------===//
5009
5010 /// __builtin_astype(...)
5011 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5012 SourceLocation BuiltinLoc,
5013 SourceLocation RParenLoc);
5014
5015 //===---------------------------- C++ Features --------------------------===//
5016
5017 // Act on C++ namespaces
5018 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5019 SourceLocation NamespaceLoc,
5020 SourceLocation IdentLoc, IdentifierInfo *Ident,
5021 SourceLocation LBrace,
5022 const ParsedAttributesView &AttrList,
5023 UsingDirectiveDecl *&UsingDecl);
5024 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5025
5026 NamespaceDecl *getStdNamespace() const;
5027 NamespaceDecl *getOrCreateStdNamespace();
5028
5029 NamespaceDecl *lookupStdExperimentalNamespace();
5030
5031 CXXRecordDecl *getStdBadAlloc() const;
5032 EnumDecl *getStdAlignValT() const;
5033
5034private:
5035 // A cache representing if we've fully checked the various comparison category
5036 // types stored in ASTContext. The bit-index corresponds to the integer value
5037 // of a ComparisonCategoryType enumerator.
5038 llvm::SmallBitVector FullyCheckedComparisonCategories;
5039
5040 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5041 CXXScopeSpec &SS,
5042 ParsedType TemplateTypeTy,
5043 IdentifierInfo *MemberOrBase);
5044
5045public:
5046 enum class ComparisonCategoryUsage {
5047 /// The '<=>' operator was used in an expression and a builtin operator
5048 /// was selected.
5049 OperatorInExpression,
5050 /// A defaulted 'operator<=>' needed the comparison category. This
5051 /// typically only applies to 'std::strong_ordering', due to the implicit
5052 /// fallback return value.
5053 DefaultedOperator,
5054 };
5055
5056 /// Lookup the specified comparison category types in the standard
5057 /// library, an check the VarDecls possibly returned by the operator<=>
5058 /// builtins for that type.
5059 ///
5060 /// \return The type of the comparison category type corresponding to the
5061 /// specified Kind, or a null type if an error occurs
5062 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5063 SourceLocation Loc,
5064 ComparisonCategoryUsage Usage);
5065
5066 /// Tests whether Ty is an instance of std::initializer_list and, if
5067 /// it is and Element is not NULL, assigns the element type to Element.
5068 bool isStdInitializerList(QualType Ty, QualType *Element);
5069
5070 /// Looks for the std::initializer_list template and instantiates it
5071 /// with Element, or emits an error if it's not found.
5072 ///
5073 /// \returns The instantiated template, or null on error.
5074 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5075
5076 /// Determine whether Ctor is an initializer-list constructor, as
5077 /// defined in [dcl.init.list]p2.
5078 bool isInitListConstructor(const FunctionDecl *Ctor);
5079
5080 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5081 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5082 SourceLocation IdentLoc,
5083 IdentifierInfo *NamespcName,
5084 const ParsedAttributesView &AttrList);
5085
5086 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5087
5088 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5089 SourceLocation NamespaceLoc,
5090 SourceLocation AliasLoc,
5091 IdentifierInfo *Alias,
5092 CXXScopeSpec &SS,
5093 SourceLocation IdentLoc,
5094 IdentifierInfo *Ident);
5095
5096 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5097 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
5098 const LookupResult &PreviousDecls,
5099 UsingShadowDecl *&PrevShadow);
5100 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5101 NamedDecl *Target,
5102 UsingShadowDecl *PrevDecl);
5103
5104 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5105 bool HasTypenameKeyword,
5106 const CXXScopeSpec &SS,
5107 SourceLocation NameLoc,
5108 const LookupResult &Previous);
5109 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5110 bool HasTypename,
5111 const CXXScopeSpec &SS,
5112 const DeclarationNameInfo &NameInfo,
5113 SourceLocation NameLoc);
5114
5115 NamedDecl *BuildUsingDeclaration(
5116 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5117 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5118 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5119 const ParsedAttributesView &AttrList, bool IsInstantiation);
5120 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5121 ArrayRef<NamedDecl *> Expansions);
5122
5123 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5124
5125 /// Given a derived-class using shadow declaration for a constructor and the
5126 /// correspnding base class constructor, find or create the implicit
5127 /// synthesized derived class constructor to use for this initialization.
5128 CXXConstructorDecl *
5129 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5130 ConstructorUsingShadowDecl *DerivedShadow);
5131
5132 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5133 SourceLocation UsingLoc,
5134 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5135 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5136 const ParsedAttributesView &AttrList);
5137 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5138 MultiTemplateParamsArg TemplateParams,
5139 SourceLocation UsingLoc, UnqualifiedId &Name,
5140 const ParsedAttributesView &AttrList,
5141 TypeResult Type, Decl *DeclFromDeclSpec);
5142
5143 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5144 /// including handling of its default argument expressions.
5145 ///
5146 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5147 ExprResult
5148 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5149 NamedDecl *FoundDecl,
5150 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5151 bool HadMultipleCandidates, bool IsListInitialization,
5152 bool IsStdInitListInitialization,
5153 bool RequiresZeroInit, unsigned ConstructKind,
5154 SourceRange ParenRange);
5155
5156 /// Build a CXXConstructExpr whose constructor has already been resolved if
5157 /// it denotes an inherited constructor.
5158 ExprResult
5159 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5160 CXXConstructorDecl *Constructor, bool Elidable,
5161 MultiExprArg Exprs,
5162 bool HadMultipleCandidates, bool IsListInitialization,
5163 bool IsStdInitListInitialization,
5164 bool RequiresZeroInit, unsigned ConstructKind,
5165 SourceRange ParenRange);
5166
5167 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5168 // the constructor can be elidable?
5169 ExprResult
5170 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5171 NamedDecl *FoundDecl,
5172 CXXConstructorDecl *Constructor, bool Elidable,
5173 MultiExprArg Exprs, bool HadMultipleCandidates,
5174 bool IsListInitialization,
5175 bool IsStdInitListInitialization, bool RequiresZeroInit,
5176 unsigned ConstructKind, SourceRange ParenRange);
5177
5178 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5179
5180
5181 /// Instantiate or parse a C++ default argument expression as necessary.
5182 /// Return true on error.
5183 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5184 ParmVarDecl *Param);
5185
5186 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5187 /// the default expr if needed.
5188 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5189 FunctionDecl *FD,
5190 ParmVarDecl *Param);
5191
5192 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5193 /// constructed variable.
5194 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5195
5196 /// Helper class that collects exception specifications for
5197 /// implicitly-declared special member functions.
5198 class ImplicitExceptionSpecification {
5199 // Pointer to allow copying
5200 Sema *Self;
5201 // We order exception specifications thus:
5202 // noexcept is the most restrictive, but is only used in C++11.
5203 // throw() comes next.
5204 // Then a throw(collected exceptions)
5205 // Finally no specification, which is expressed as noexcept(false).
5206 // throw(...) is used instead if any called function uses it.
5207 ExceptionSpecificationType ComputedEST;
5208 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5209 SmallVector<QualType, 4> Exceptions;
5210
5211 void ClearExceptions() {
5212 ExceptionsSeen.clear();
5213 Exceptions.clear();
5214 }
5215
5216 public:
5217 explicit ImplicitExceptionSpecification(Sema &Self)
5218 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5219 if (!Self.getLangOpts().CPlusPlus11)
5220 ComputedEST = EST_DynamicNone;
5221 }
5222
5223 /// Get the computed exception specification type.
5224 ExceptionSpecificationType getExceptionSpecType() const {
5225 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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 5226, __PRETTY_FUNCTION__))
5226 "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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 5226, __PRETTY_FUNCTION__))
;
5227 return ComputedEST;
5228 }
5229
5230 /// The number of exceptions in the exception specification.
5231 unsigned size() const { return Exceptions.size(); }
5232
5233 /// The set of exceptions in the exception specification.
5234 const QualType *data() const { return Exceptions.data(); }
5235
5236 /// Integrate another called method into the collected data.
5237 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5238
5239 /// Integrate an invoked expression into the collected data.
5240 void CalledExpr(Expr *E) { CalledStmt(E); }
5241
5242 /// Integrate an invoked statement into the collected data.
5243 void CalledStmt(Stmt *S);
5244
5245 /// Overwrite an EPI's exception specification with this
5246 /// computed exception specification.
5247 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5248 FunctionProtoType::ExceptionSpecInfo ESI;
5249 ESI.Type = getExceptionSpecType();
5250 if (ESI.Type == EST_Dynamic) {
5251 ESI.Exceptions = Exceptions;
5252 } else if (ESI.Type == EST_None) {
5253 /// C++11 [except.spec]p14:
5254 /// The exception-specification is noexcept(false) if the set of
5255 /// potential exceptions of the special member function contains "any"
5256 ESI.Type = EST_NoexceptFalse;
5257 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5258 tok::kw_false).get();
5259 }
5260 return ESI;
5261 }
5262 };
5263
5264 /// Determine what sort of exception specification a defaulted
5265 /// copy constructor of a class will have.
5266 ImplicitExceptionSpecification
5267 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
5268 CXXMethodDecl *MD);
5269
5270 /// Determine what sort of exception specification a defaulted
5271 /// default constructor of a class will have, and whether the parameter
5272 /// will be const.
5273 ImplicitExceptionSpecification
5274 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
5275
5276 /// Determine what sort of exception specification a defaulted
5277 /// copy assignment operator of a class will have, and whether the
5278 /// parameter will be const.
5279 ImplicitExceptionSpecification
5280 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
5281
5282 /// Determine what sort of exception specification a defaulted move
5283 /// constructor of a class will have.
5284 ImplicitExceptionSpecification
5285 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
5286
5287 /// Determine what sort of exception specification a defaulted move
5288 /// assignment operator of a class will have.
5289 ImplicitExceptionSpecification
5290 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
5291
5292 /// Determine what sort of exception specification a defaulted
5293 /// destructor of a class will have.
5294 ImplicitExceptionSpecification
5295 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
5296
5297 /// Determine what sort of exception specification an inheriting
5298 /// constructor of a class will have.
5299 ImplicitExceptionSpecification
5300 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
5301 CXXConstructorDecl *CD);
5302
5303 /// Evaluate the implicit exception specification for a defaulted
5304 /// special member function.
5305 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5306
5307 /// Check the given noexcept-specifier, convert its expression, and compute
5308 /// the appropriate ExceptionSpecificationType.
5309 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5310 ExceptionSpecificationType &EST);
5311
5312 /// Check the given exception-specification and update the
5313 /// exception specification information with the results.
5314 void checkExceptionSpecification(bool IsTopLevel,
5315 ExceptionSpecificationType EST,
5316 ArrayRef<ParsedType> DynamicExceptions,
5317 ArrayRef<SourceRange> DynamicExceptionRanges,
5318 Expr *NoexceptExpr,
5319 SmallVectorImpl<QualType> &Exceptions,
5320 FunctionProtoType::ExceptionSpecInfo &ESI);
5321
5322 /// Determine if we're in a case where we need to (incorrectly) eagerly
5323 /// parse an exception specification to work around a libstdc++ bug.
5324 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5325
5326 /// Add an exception-specification to the given member function
5327 /// (or member function template). The exception-specification was parsed
5328 /// after the method itself was declared.
5329 void actOnDelayedExceptionSpecification(Decl *Method,
5330 ExceptionSpecificationType EST,
5331 SourceRange SpecificationRange,
5332 ArrayRef<ParsedType> DynamicExceptions,
5333 ArrayRef<SourceRange> DynamicExceptionRanges,
5334 Expr *NoexceptExpr);
5335
5336 class InheritedConstructorInfo;
5337
5338 /// Determine if a special member function should have a deleted
5339 /// definition when it is defaulted.
5340 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5341 InheritedConstructorInfo *ICI = nullptr,
5342 bool Diagnose = false);
5343
5344 /// Produce notes explaining why a defaulted function was defined as deleted.
5345 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5346
5347 /// Declare the implicit default constructor for the given class.
5348 ///
5349 /// \param ClassDecl The class declaration into which the implicit
5350 /// default constructor will be added.
5351 ///
5352 /// \returns The implicitly-declared default constructor.
5353 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5354 CXXRecordDecl *ClassDecl);
5355
5356 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5357 /// defining this constructor as the default constructor.
5358 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5359 CXXConstructorDecl *Constructor);
5360
5361 /// Declare the implicit destructor for the given class.
5362 ///
5363 /// \param ClassDecl The class declaration into which the implicit
5364 /// destructor will be added.
5365 ///
5366 /// \returns The implicitly-declared destructor.
5367 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5368
5369 /// DefineImplicitDestructor - Checks for feasibility of
5370 /// defining this destructor as the default destructor.
5371 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5372 CXXDestructorDecl *Destructor);
5373
5374 /// Build an exception spec for destructors that don't have one.
5375 ///
5376 /// C++11 says that user-defined destructors with no exception spec get one
5377 /// that looks as if the destructor was implicitly declared.
5378 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5379
5380 /// Define the specified inheriting constructor.
5381 void DefineInheritingConstructor(SourceLocation UseLoc,
5382 CXXConstructorDecl *Constructor);
5383
5384 /// Declare the implicit copy constructor for the given class.
5385 ///
5386 /// \param ClassDecl The class declaration into which the implicit
5387 /// copy constructor will be added.
5388 ///
5389 /// \returns The implicitly-declared copy constructor.
5390 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5391
5392 /// DefineImplicitCopyConstructor - Checks for feasibility of
5393 /// defining this constructor as the copy constructor.
5394 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5395 CXXConstructorDecl *Constructor);
5396
5397 /// Declare the implicit move constructor for the given class.
5398 ///
5399 /// \param ClassDecl The Class declaration into which the implicit
5400 /// move constructor will be added.
5401 ///
5402 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5403 /// declared.
5404 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5405
5406 /// DefineImplicitMoveConstructor - Checks for feasibility of
5407 /// defining this constructor as the move constructor.
5408 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5409 CXXConstructorDecl *Constructor);
5410
5411 /// Declare the implicit copy assignment operator for the given class.
5412 ///
5413 /// \param ClassDecl The class declaration into which the implicit
5414 /// copy assignment operator will be added.
5415 ///
5416 /// \returns The implicitly-declared copy assignment operator.
5417 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5418
5419 /// Defines an implicitly-declared copy assignment operator.
5420 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5421 CXXMethodDecl *MethodDecl);
5422
5423 /// Declare the implicit move assignment operator for the given class.
5424 ///
5425 /// \param ClassDecl The Class declaration into which the implicit
5426 /// move assignment operator will be added.
5427 ///
5428 /// \returns The implicitly-declared move assignment operator, or NULL if it
5429 /// wasn't declared.
5430 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5431
5432 /// Defines an implicitly-declared move assignment operator.
5433 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5434 CXXMethodDecl *MethodDecl);
5435
5436 /// Force the declaration of any implicitly-declared members of this
5437 /// class.
5438 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
5439
5440 /// Check a completed declaration of an implicit special member.
5441 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5442
5443 /// Determine whether the given function is an implicitly-deleted
5444 /// special member function.
5445 bool isImplicitlyDeleted(FunctionDecl *FD);
5446
5447 /// Check whether 'this' shows up in the type of a static member
5448 /// function after the (naturally empty) cv-qualifier-seq would be.
5449 ///
5450 /// \returns true if an error occurred.
5451 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5452
5453 /// Whether this' shows up in the exception specification of a static
5454 /// member function.
5455 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5456
5457 /// Check whether 'this' shows up in the attributes of the given
5458 /// static member function.
5459 ///
5460 /// \returns true if an error occurred.
5461 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5462
5463 /// MaybeBindToTemporary - If the passed in expression has a record type with
5464 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
5465 /// it simply returns the passed in expression.
5466 ExprResult MaybeBindToTemporary(Expr *E);
5467
5468 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5469 MultiExprArg ArgsPtr,
5470 SourceLocation Loc,
5471 SmallVectorImpl<Expr*> &ConvertedArgs,
5472 bool AllowExplicit = false,
5473 bool IsListInitialization = false);
5474
5475 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5476 SourceLocation NameLoc,
5477 IdentifierInfo &Name);
5478
5479 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5480 Scope *S, CXXScopeSpec &SS,
5481 bool EnteringContext);
5482 ParsedType getDestructorName(SourceLocation TildeLoc,
5483 IdentifierInfo &II, SourceLocation NameLoc,
5484 Scope *S, CXXScopeSpec &SS,
5485 ParsedType ObjectType,
5486 bool EnteringContext);
5487
5488 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
5489 ParsedType ObjectType);
5490
5491 // Checks that reinterpret casts don't have undefined behavior.
5492 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
5493 bool IsDereference, SourceRange Range);
5494
5495 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
5496 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
5497 tok::TokenKind Kind,
5498 SourceLocation LAngleBracketLoc,
5499 Declarator &D,
5500 SourceLocation RAngleBracketLoc,
5501 SourceLocation LParenLoc,
5502 Expr *E,
5503 SourceLocation RParenLoc);
5504
5505 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
5506 tok::TokenKind Kind,
5507 TypeSourceInfo *Ty,
5508 Expr *E,
5509 SourceRange AngleBrackets,
5510 SourceRange Parens);
5511
5512 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
5513 ExprResult Operand,
5514 SourceLocation RParenLoc);
5515
5516 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
5517 Expr *Operand, SourceLocation RParenLoc);
5518
5519 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5520 SourceLocation TypeidLoc,
5521 TypeSourceInfo *Operand,
5522 SourceLocation RParenLoc);
5523 ExprResult BuildCXXTypeId(QualType TypeInfoType,
5524 SourceLocation TypeidLoc,
5525 Expr *Operand,
5526 SourceLocation RParenLoc);
5527
5528 /// ActOnCXXTypeid - Parse typeid( something ).
5529 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5530 SourceLocation LParenLoc, bool isType,
5531 void *TyOrExpr,
5532 SourceLocation RParenLoc);
5533
5534 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5535 SourceLocation TypeidLoc,
5536 TypeSourceInfo *Operand,
5537 SourceLocation RParenLoc);
5538 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5539 SourceLocation TypeidLoc,
5540 Expr *Operand,
5541 SourceLocation RParenLoc);
5542
5543 /// ActOnCXXUuidof - Parse __uuidof( something ).
5544 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5545 SourceLocation LParenLoc, bool isType,
5546 void *TyOrExpr,
5547 SourceLocation RParenLoc);
5548
5549 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
5550 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5551 tok::TokenKind Operator,
5552 SourceLocation EllipsisLoc, Expr *RHS,
5553 SourceLocation RParenLoc);
5554 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5555 BinaryOperatorKind Operator,
5556 SourceLocation EllipsisLoc, Expr *RHS,
5557 SourceLocation RParenLoc,
5558 Optional<unsigned> NumExpansions);
5559 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5560 BinaryOperatorKind Operator);
5561
5562 //// ActOnCXXThis - Parse 'this' pointer.
5563 ExprResult ActOnCXXThis(SourceLocation loc);
5564
5565 /// Build a CXXThisExpr and mark it referenced in the current context.
5566 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
5567 void MarkThisReferenced(CXXThisExpr *This);
5568
5569 /// Try to retrieve the type of the 'this' pointer.
5570 ///
5571 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5572 QualType getCurrentThisType();
5573
5574 /// When non-NULL, the C++ 'this' expression is allowed despite the
5575 /// current context not being a non-static member function. In such cases,
5576 /// this provides the type used for 'this'.
5577 QualType CXXThisTypeOverride;
5578
5579 /// RAII object used to temporarily allow the C++ 'this' expression
5580 /// to be used, with the given qualifiers on the current class type.
5581 class CXXThisScopeRAII {
5582 Sema &S;
5583 QualType OldCXXThisTypeOverride;
5584 bool Enabled;
5585
5586 public:
5587 /// Introduce a new scope where 'this' may be allowed (when enabled),
5588 /// using the given declaration (which is either a class template or a
5589 /// class) along with the given qualifiers.
5590 /// along with the qualifiers placed on '*this'.
5591 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
5592 bool Enabled = true);
5593
5594 ~CXXThisScopeRAII();
5595 };
5596
5597 /// Make sure the value of 'this' is actually available in the current
5598 /// context, if it is a potentially evaluated context.
5599 ///
5600 /// \param Loc The location at which the capture of 'this' occurs.
5601 ///
5602 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5603 /// capture list.
5604 ///
5605 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5606 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5607 /// This is useful when enclosing lambdas must speculatively capture
5608 /// 'this' that may or may not be used in certain specializations of
5609 /// a nested generic lambda (depending on whether the name resolves to
5610 /// a non-static member function or a static function).
5611 /// \return returns 'true' if failed, 'false' if success.
5612 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5613 bool BuildAndDiagnose = true,
5614 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5615 bool ByCopy = false);
5616
5617 /// Determine whether the given type is the type of *this that is used
5618 /// outside of the body of a member function for a type that is currently
5619 /// being defined.
5620 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5621
5622 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5623 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5624
5625
5626 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5627 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5628
5629 ExprResult
5630 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5631 SourceLocation AtLoc, SourceLocation RParen);
5632
5633 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5634 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5635
5636 //// ActOnCXXThrow - Parse throw expressions.
5637 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5638 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5639 bool IsThrownVarInScope);
5640 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5641
5642 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5643 /// Can be interpreted either as function-style casting ("int(x)")
5644 /// or class type construction ("ClassType(x,y,z)")
5645 /// or creation of a value-initialized type ("int()").
5646 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5647 SourceLocation LParenOrBraceLoc,
5648 MultiExprArg Exprs,
5649 SourceLocation RParenOrBraceLoc,
5650 bool ListInitialization);
5651
5652 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5653 SourceLocation LParenLoc,
5654 MultiExprArg Exprs,
5655 SourceLocation RParenLoc,
5656 bool ListInitialization);
5657
5658 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5659 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5660 SourceLocation PlacementLParen,
5661 MultiExprArg PlacementArgs,
5662 SourceLocation PlacementRParen,
5663 SourceRange TypeIdParens, Declarator &D,
5664 Expr *Initializer);
5665 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5666 SourceLocation PlacementLParen,
5667 MultiExprArg PlacementArgs,
5668 SourceLocation PlacementRParen,
5669 SourceRange TypeIdParens,
5670 QualType AllocType,
5671 TypeSourceInfo *AllocTypeInfo,
5672 Optional<Expr *> ArraySize,
5673 SourceRange DirectInitRange,
5674 Expr *Initializer);
5675
5676 /// Determine whether \p FD is an aligned allocation or deallocation
5677 /// function that is unavailable.
5678 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
5679
5680 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
5681 /// function that is unavailable.
5682 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
5683 SourceLocation Loc);
5684
5685 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5686 SourceRange R);
5687
5688 /// The scope in which to find allocation functions.
5689 enum AllocationFunctionScope {
5690 /// Only look for allocation functions in the global scope.
5691 AFS_Global,
5692 /// Only look for allocation functions in the scope of the
5693 /// allocated class.
5694 AFS_Class,
5695 /// Look for allocation functions in both the global scope
5696 /// and in the scope of the allocated class.
5697 AFS_Both
5698 };
5699
5700 /// Finds the overloads of operator new and delete that are appropriate
5701 /// for the allocation.
5702 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5703 AllocationFunctionScope NewScope,
5704 AllocationFunctionScope DeleteScope,
5705 QualType AllocType, bool IsArray,
5706 bool &PassAlignment, MultiExprArg PlaceArgs,
5707 FunctionDecl *&OperatorNew,
5708 FunctionDecl *&OperatorDelete,
5709 bool Diagnose = true);
5710 void DeclareGlobalNewDelete();
5711 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5712 ArrayRef<QualType> Params);
5713
5714 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5715 DeclarationName Name, FunctionDecl* &Operator,
5716 bool Diagnose = true);
5717 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5718 bool CanProvideSize,
5719 bool Overaligned,
5720 DeclarationName Name);
5721 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5722 CXXRecordDecl *RD);
5723
5724 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5725 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5726 bool UseGlobal, bool ArrayForm,
5727 Expr *Operand);
5728 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5729 bool IsDelete, bool CallCanBeVirtual,
5730 bool WarnOnNonAbstractTypes,
5731 SourceLocation DtorLoc);
5732
5733 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5734 Expr *Operand, SourceLocation RParen);
5735 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5736 SourceLocation RParen);
5737
5738 /// Parsed one of the type trait support pseudo-functions.
5739 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5740 ArrayRef<ParsedType> Args,
5741 SourceLocation RParenLoc);
5742 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5743 ArrayRef<TypeSourceInfo *> Args,
5744 SourceLocation RParenLoc);
5745
5746 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5747 /// pseudo-functions.
5748 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5749 SourceLocation KWLoc,
5750 ParsedType LhsTy,
5751 Expr *DimExpr,
5752 SourceLocation RParen);
5753
5754 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5755 SourceLocation KWLoc,
5756 TypeSourceInfo *TSInfo,
5757 Expr *DimExpr,
5758 SourceLocation RParen);
5759
5760 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5761 /// pseudo-functions.
5762 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5763 SourceLocation KWLoc,
5764 Expr *Queried,
5765 SourceLocation RParen);
5766
5767 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5768 SourceLocation KWLoc,
5769 Expr *Queried,
5770 SourceLocation RParen);
5771
5772 ExprResult ActOnStartCXXMemberReference(Scope *S,
5773 Expr *Base,
5774 SourceLocation OpLoc,
5775 tok::TokenKind OpKind,
5776 ParsedType &ObjectType,
5777 bool &MayBePseudoDestructor);
5778
5779 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5780 SourceLocation OpLoc,
5781 tok::TokenKind OpKind,
5782 const CXXScopeSpec &SS,
5783 TypeSourceInfo *ScopeType,
5784 SourceLocation CCLoc,
5785 SourceLocation TildeLoc,
5786 PseudoDestructorTypeStorage DestroyedType);
5787
5788 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5789 SourceLocation OpLoc,
5790 tok::TokenKind OpKind,
5791 CXXScopeSpec &SS,
5792 UnqualifiedId &FirstTypeName,
5793 SourceLocation CCLoc,
5794 SourceLocation TildeLoc,
5795 UnqualifiedId &SecondTypeName);
5796
5797 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5798 SourceLocation OpLoc,
5799 tok::TokenKind OpKind,
5800 SourceLocation TildeLoc,
5801 const DeclSpec& DS);
5802
5803 /// MaybeCreateExprWithCleanups - If the current full-expression
5804 /// requires any cleanups, surround it with a ExprWithCleanups node.
5805 /// Otherwise, just returns the passed-in expression.
5806 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5807 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5808 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5809
5810 MaterializeTemporaryExpr *
5811 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5812 bool BoundToLvalueReference);
5813
5814 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
5815 return ActOnFinishFullExpr(
5816 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
5817 }
5818 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5819 bool DiscardedValue, bool IsConstexpr = false);
5820 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5821
5822 // Marks SS invalid if it represents an incomplete type.
5823 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5824
5825 DeclContext *computeDeclContext(QualType T);
5826 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5827 bool EnteringContext = false);
5828 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5829 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5830
5831 /// The parser has parsed a global nested-name-specifier '::'.
5832 ///
5833 /// \param CCLoc The location of the '::'.
5834 ///
5835 /// \param SS The nested-name-specifier, which will be updated in-place
5836 /// to reflect the parsed nested-name-specifier.
5837 ///
5838 /// \returns true if an error occurred, false otherwise.
5839 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5840
5841 /// The parser has parsed a '__super' nested-name-specifier.
5842 ///
5843 /// \param SuperLoc The location of the '__super' keyword.
5844 ///
5845 /// \param ColonColonLoc The location of the '::'.
5846 ///
5847 /// \param SS The nested-name-specifier, which will be updated in-place
5848 /// to reflect the parsed nested-name-specifier.
5849 ///
5850 /// \returns true if an error occurred, false otherwise.
5851 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5852 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5853
5854 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5855 bool *CanCorrect = nullptr);
5856 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5857
5858 /// Keeps information about an identifier in a nested-name-spec.
5859 ///
5860 struct NestedNameSpecInfo {
5861 /// The type of the object, if we're parsing nested-name-specifier in
5862 /// a member access expression.
5863 ParsedType ObjectType;
5864
5865 /// The identifier preceding the '::'.
5866 IdentifierInfo *Identifier;
5867
5868 /// The location of the identifier.
5869 SourceLocation IdentifierLoc;
5870
5871 /// The location of the '::'.
5872 SourceLocation CCLoc;
5873
5874 /// Creates info object for the most typical case.
5875 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5876 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5877 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5878 CCLoc(ColonColonLoc) {
5879 }
5880
5881 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5882 SourceLocation ColonColonLoc, QualType ObjectType)
5883 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5884 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5885 }
5886 };
5887
5888 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5889 NestedNameSpecInfo &IdInfo);
5890
5891 bool BuildCXXNestedNameSpecifier(Scope *S,
5892 NestedNameSpecInfo &IdInfo,
5893 bool EnteringContext,
5894 CXXScopeSpec &SS,
5895 NamedDecl *ScopeLookupResult,
5896 bool ErrorRecoveryLookup,
5897 bool *IsCorrectedToColon = nullptr,
5898 bool OnlyNamespace = false);
5899
5900 /// The parser has parsed a nested-name-specifier 'identifier::'.
5901 ///
5902 /// \param S The scope in which this nested-name-specifier occurs.
5903 ///
5904 /// \param IdInfo Parser information about an identifier in the
5905 /// nested-name-spec.
5906 ///
5907 /// \param EnteringContext Whether we're entering the context nominated by
5908 /// this nested-name-specifier.
5909 ///
5910 /// \param SS The nested-name-specifier, which is both an input
5911 /// parameter (the nested-name-specifier before this type) and an
5912 /// output parameter (containing the full nested-name-specifier,
5913 /// including this new type).
5914 ///
5915 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5916 /// error recovery. In this case do not emit error message.
5917 ///
5918 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5919 /// are allowed. The bool value pointed by this parameter is set to 'true'
5920 /// if the identifier is treated as if it was followed by ':', not '::'.
5921 ///
5922 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5923 ///
5924 /// \returns true if an error occurred, false otherwise.
5925 bool ActOnCXXNestedNameSpecifier(Scope *S,
5926 NestedNameSpecInfo &IdInfo,
5927 bool EnteringContext,
5928 CXXScopeSpec &SS,
5929 bool ErrorRecoveryLookup = false,
5930 bool *IsCorrectedToColon = nullptr,
5931 bool OnlyNamespace = false);
5932
5933 ExprResult ActOnDecltypeExpression(Expr *E);
5934
5935 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5936 const DeclSpec &DS,
5937 SourceLocation ColonColonLoc);
5938
5939 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5940 NestedNameSpecInfo &IdInfo,
5941 bool EnteringContext);
5942
5943 /// The parser has parsed a nested-name-specifier
5944 /// 'template[opt] template-name < template-args >::'.
5945 ///
5946 /// \param S The scope in which this nested-name-specifier occurs.
5947 ///
5948 /// \param SS The nested-name-specifier, which is both an input
5949 /// parameter (the nested-name-specifier before this type) and an
5950 /// output parameter (containing the full nested-name-specifier,
5951 /// including this new type).
5952 ///
5953 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5954 /// \param TemplateName the template name.
5955 /// \param TemplateNameLoc The location of the template name.
5956 /// \param LAngleLoc The location of the opening angle bracket ('<').
5957 /// \param TemplateArgs The template arguments.
5958 /// \param RAngleLoc The location of the closing angle bracket ('>').
5959 /// \param CCLoc The location of the '::'.
5960 ///
5961 /// \param EnteringContext Whether we're entering the context of the
5962 /// nested-name-specifier.
5963 ///
5964 ///
5965 /// \returns true if an error occurred, false otherwise.
5966 bool ActOnCXXNestedNameSpecifier(Scope *S,
5967 CXXScopeSpec &SS,
5968 SourceLocation TemplateKWLoc,
5969 TemplateTy TemplateName,
5970 SourceLocation TemplateNameLoc,
5971 SourceLocation LAngleLoc,
5972 ASTTemplateArgsPtr TemplateArgs,
5973 SourceLocation RAngleLoc,
5974 SourceLocation CCLoc,
5975 bool EnteringContext);
5976
5977 /// Given a C++ nested-name-specifier, produce an annotation value
5978 /// that the parser can use later to reconstruct the given
5979 /// nested-name-specifier.
5980 ///
5981 /// \param SS A nested-name-specifier.
5982 ///
5983 /// \returns A pointer containing all of the information in the
5984 /// nested-name-specifier \p SS.
5985 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5986
5987 /// Given an annotation pointer for a nested-name-specifier, restore
5988 /// the nested-name-specifier structure.
5989 ///
5990 /// \param Annotation The annotation pointer, produced by
5991 /// \c SaveNestedNameSpecifierAnnotation().
5992 ///
5993 /// \param AnnotationRange The source range corresponding to the annotation.
5994 ///
5995 /// \param SS The nested-name-specifier that will be updated with the contents
5996 /// of the annotation pointer.
5997 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5998 SourceRange AnnotationRange,
5999 CXXScopeSpec &SS);
6000
6001 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6002
6003 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6004 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6005 /// After this method is called, according to [C++ 3.4.3p3], names should be
6006 /// looked up in the declarator-id's scope, until the declarator is parsed and
6007 /// ActOnCXXExitDeclaratorScope is called.
6008 /// The 'SS' should be a non-empty valid CXXScopeSpec.
6009 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6010
6011 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6012 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6013 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6014 /// Used to indicate that names should revert to being looked up in the
6015 /// defining scope.
6016 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6017
6018 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6019 /// initializer for the declaration 'Dcl'.
6020 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6021 /// static data member of class X, names should be looked up in the scope of
6022 /// class X.
6023 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6024
6025 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6026 /// initializer for the declaration 'Dcl'.
6027 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6028
6029 /// Create a new lambda closure type.
6030 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6031 TypeSourceInfo *Info,
6032 bool KnownDependent,
6033 LambdaCaptureDefault CaptureDefault);
6034
6035 /// Start the definition of a lambda expression.
6036 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6037 SourceRange IntroducerRange,
6038 TypeSourceInfo *MethodType,
6039 SourceLocation EndLoc,
6040 ArrayRef<ParmVarDecl *> Params,
6041 ConstexprSpecKind ConstexprKind,
6042 Expr *TrailingRequiresClause);
6043
6044 /// Number lambda for linkage purposes if necessary.
6045 void handleLambdaNumbering(
6046 CXXRecordDecl *Class, CXXMethodDecl *Method,
6047 Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
6048
6049 /// Endow the lambda scope info with the relevant properties.
6050 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6051 CXXMethodDecl *CallOperator,
6052 SourceRange IntroducerRange,
6053 LambdaCaptureDefault CaptureDefault,
6054 SourceLocation CaptureDefaultLoc,
6055 bool ExplicitParams,
6056 bool ExplicitResultType,
6057 bool Mutable);
6058
6059 /// Perform initialization analysis of the init-capture and perform
6060 /// any implicit conversions such as an lvalue-to-rvalue conversion if
6061 /// not being used to initialize a reference.
6062 ParsedType actOnLambdaInitCaptureInitialization(
6063 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6064 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6065 return ParsedType::make(buildLambdaInitCaptureInitialization(
6066 Loc, ByRef, EllipsisLoc, None, Id,
6067 InitKind != LambdaCaptureInitKind::CopyInit, Init));
6068 }
6069 QualType buildLambdaInitCaptureInitialization(
6070 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6071 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6072 Expr *&Init);
6073
6074 /// Create a dummy variable within the declcontext of the lambda's
6075 /// call operator, for name lookup purposes for a lambda init capture.
6076 ///
6077 /// CodeGen handles emission of lambda captures, ignoring these dummy
6078 /// variables appropriately.
6079 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6080 QualType InitCaptureType,
6081 SourceLocation EllipsisLoc,
6082 IdentifierInfo *Id,
6083 unsigned InitStyle, Expr *Init);
6084
6085 /// Add an init-capture to a lambda scope.
6086 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6087
6088 /// Note that we have finished the explicit captures for the
6089 /// given lambda.
6090 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6091
6092 /// \brief This is called after parsing the explicit template parameter list
6093 /// on a lambda (if it exists) in C++2a.
6094 void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6095 ArrayRef<NamedDecl *> TParams,
6096 SourceLocation RAngleLoc);
6097
6098 /// Introduce the lambda parameters into scope.
6099 void addLambdaParameters(
6100 ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6101 CXXMethodDecl *CallOperator, Scope *CurScope);
6102
6103 /// Deduce a block or lambda's return type based on the return
6104 /// statements present in the body.
6105 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6106
6107 /// ActOnStartOfLambdaDefinition - This is called just before we start
6108 /// parsing the body of a lambda; it analyzes the explicit captures and
6109 /// arguments, and sets up various data-structures for the body of the
6110 /// lambda.
6111 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6112 Declarator &ParamInfo, Scope *CurScope);
6113
6114 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6115 /// is invoked to pop the information about the lambda.
6116 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6117 bool IsInstantiation = false);
6118
6119 /// ActOnLambdaExpr - This is called when the body of a lambda expression
6120 /// was successfully completed.
6121 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6122 Scope *CurScope);
6123
6124 /// Does copying/destroying the captured variable have side effects?
6125 bool CaptureHasSideEffects(const sema::Capture &From);
6126
6127 /// Diagnose if an explicit lambda capture is unused. Returns true if a
6128 /// diagnostic is emitted.
6129 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6130 const sema::Capture &From);
6131
6132 /// Build a FieldDecl suitable to hold the given capture.
6133 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6134
6135 /// Initialize the given capture with a suitable expression.
6136 ExprResult BuildCaptureInit(const sema::Capture &Capture,
6137 SourceLocation ImplicitCaptureLoc,
6138 bool IsOpenMPMapping = false);
6139
6140 /// Complete a lambda-expression having processed and attached the
6141 /// lambda body.
6142 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6143 sema::LambdaScopeInfo *LSI);
6144
6145 /// Get the return type to use for a lambda's conversion function(s) to
6146 /// function pointer type, given the type of the call operator.
6147 QualType
6148 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
6149
6150 /// Define the "body" of the conversion from a lambda object to a
6151 /// function pointer.
6152 ///
6153 /// This routine doesn't actually define a sensible body; rather, it fills
6154 /// in the initialization expression needed to copy the lambda object into
6155 /// the block, and IR generation actually generates the real body of the
6156 /// block pointer conversion.
6157 void DefineImplicitLambdaToFunctionPointerConversion(
6158 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6159
6160 /// Define the "body" of the conversion from a lambda object to a
6161 /// block pointer.
6162 ///
6163 /// This routine doesn't actually define a sensible body; rather, it fills
6164 /// in the initialization expression needed to copy the lambda object into
6165 /// the block, and IR generation actually generates the real body of the
6166 /// block pointer conversion.
6167 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6168 CXXConversionDecl *Conv);
6169
6170 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6171 SourceLocation ConvLocation,
6172 CXXConversionDecl *Conv,
6173 Expr *Src);
6174
6175 /// Check whether the given expression is a valid constraint expression.
6176 /// A diagnostic is emitted if it is not, false is returned, and
6177 /// PossibleNonPrimary will be set to true if the failure might be due to a
6178 /// non-primary expression being used as an atomic constraint.
6179 bool CheckConstraintExpression(Expr *CE, Token NextToken = Token(),
6180 bool *PossibleNonPrimary = nullptr,
6181 bool IsTrailingRequiresClause = false);
6182
6183 /// Check whether the given type-dependent expression will be the name of a
6184 /// function or another callable function-like entity (e.g. a function
6185 // template or overload set) for any substitution.
6186 bool IsDependentFunctionNameExpr(Expr *E);
6187
6188private:
6189 /// Caches pairs of template-like decls whose associated constraints were
6190 /// checked for subsumption and whether or not the first's constraints did in
6191 /// fact subsume the second's.
6192 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6193 /// Caches the normalized associated constraints of declarations (concepts or
6194 /// constrained declarations). If an error occurred while normalizing the
6195 /// associated constraints of the template or concept, nullptr will be cached
6196 /// here.
6197 llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6198 NormalizationCache;
6199
6200public:
6201 const NormalizedConstraint *
6202 getNormalizedAssociatedConstraints(
6203 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
6204
6205 /// \brief Check whether the given declaration's associated constraints are
6206 /// at least as constrained than another declaration's according to the
6207 /// partial ordering of constraints.
6208 ///
6209 /// \param Result If no error occurred, receives the result of true if D1 is
6210 /// at least constrained than D2, and false otherwise.
6211 ///
6212 /// \returns true if an error occurred, false otherwise.
6213 bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
6214 NamedDecl *D2, ArrayRef<const Expr *> AC2,
6215 bool &Result);
6216
6217 /// If D1 was not at least as constrained as D2, but would've been if a pair
6218 /// of atomic constraints involved had been declared in a concept and not
6219 /// repeated in two separate places in code.
6220 /// \returns true if such a diagnostic was emitted, false otherwise.
6221 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
6222 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
6223
6224 /// \brief Check whether the given list of constraint expressions are
6225 /// satisfied (as if in a 'conjunction') given template arguments.
6226 /// \param ConstraintExprs a list of constraint expressions, treated as if
6227 /// they were 'AND'ed together.
6228 /// \param TemplateArgs the list of template arguments to substitute into the
6229 /// constraint expression.
6230 /// \param TemplateIDRange The source range of the template id that
6231 /// caused the constraints check.
6232 /// \param Satisfaction if true is returned, will contain details of the
6233 /// satisfaction, with enough information to diagnose an unsatisfied
6234 /// expression.
6235 /// \returns true if an error occurred and satisfaction could not be checked,
6236 /// false otherwise.
6237 bool CheckConstraintSatisfaction(TemplateDecl *Template,
6238 ArrayRef<const Expr *> ConstraintExprs,
6239 ArrayRef<TemplateArgument> TemplateArgs,
6240 SourceRange TemplateIDRange,
6241 ConstraintSatisfaction &Satisfaction);
6242
6243 bool CheckConstraintSatisfaction(ClassTemplatePartialSpecializationDecl *TD,
6244 ArrayRef<const Expr *> ConstraintExprs,
6245 ArrayRef<TemplateArgument> TemplateArgs,
6246 SourceRange TemplateIDRange,
6247 ConstraintSatisfaction &Satisfaction);
6248
6249 bool CheckConstraintSatisfaction(VarTemplatePartialSpecializationDecl *TD,
6250 ArrayRef<const Expr *> ConstraintExprs,
6251 ArrayRef<TemplateArgument> TemplateArgs,
6252 SourceRange TemplateIDRange,
6253 ConstraintSatisfaction &Satisfaction);
6254
6255 /// \brief Check whether the given non-dependent constraint expression is
6256 /// satisfied. Returns false and updates Satisfaction with the satisfaction
6257 /// verdict if successful, emits a diagnostic and returns true if an error
6258 /// occured and satisfaction could not be determined.
6259 ///
6260 /// \returns true if an error occurred, false otherwise.
6261 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
6262 ConstraintSatisfaction &Satisfaction);
6263
6264 /// Check that the associated constraints of a template declaration match the
6265 /// associated constraints of an older declaration of which it is a
6266 /// redeclaration.
6267 bool CheckRedeclarationConstraintMatch(TemplateParameterList *Old,
6268 TemplateParameterList *New);
6269
6270 /// \brief Ensure that the given template arguments satisfy the constraints
6271 /// associated with the given template, emitting a diagnostic if they do not.
6272 ///
6273 /// \param Template The template to which the template arguments are being
6274 /// provided.
6275 ///
6276 /// \param TemplateArgs The converted, canonicalized template arguments.
6277 ///
6278 /// \param TemplateIDRange The source range of the template id that
6279 /// caused the constraints check.
6280 ///
6281 /// \returns true if the constrains are not satisfied or could not be checked
6282 /// for satisfaction, false if the constraints are satisfied.
6283 bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
6284 ArrayRef<TemplateArgument> TemplateArgs,
6285 SourceRange TemplateIDRange);
6286
6287 /// \brief Emit diagnostics explaining why a constraint expression was deemed
6288 /// unsatisfied.
6289 void
6290 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction& Satisfaction);
6291
6292 /// \brief Emit diagnostics explaining why a constraint expression was deemed
6293 /// unsatisfied.
6294 void
6295 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction& Satisfaction);
6296
6297 /// \brief Emit diagnostics explaining why a constraint expression was deemed
6298 /// unsatisfied because it was ill-formed.
6299 void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation,
6300 StringRef Diagnostic);
6301
6302 void
6303 DiagnoseRedeclarationConstraintMismatch(const TemplateParameterList *Old,
6304 const TemplateParameterList *New);
6305
6306 // ParseObjCStringLiteral - Parse Objective-C string literals.
6307 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6308 ArrayRef<Expr *> Strings);
6309
6310 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6311
6312 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6313 /// numeric literal expression. Type of the expression will be "NSNumber *"
6314 /// or "id" if NSNumber is unavailable.
6315 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6316 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6317 bool Value);
6318 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6319
6320 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6321 /// '@' prefixed parenthesized expression. The type of the expression will
6322 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6323 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6324 /// "const char *" or C structure with attribute 'objc_boxable'.
6325 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6326
6327 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6328 Expr *IndexExpr,
6329 ObjCMethodDecl *getterMethod,
6330 ObjCMethodDecl *setterMethod);
6331
6332 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6333 MutableArrayRef<ObjCDictionaryElement> Elements);
6334
6335 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6336 TypeSourceInfo *EncodedTypeInfo,
6337 SourceLocation RParenLoc);
6338 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6339 CXXConversionDecl *Method,
6340 bool HadMultipleCandidates);
6341
6342 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6343 SourceLocation EncodeLoc,
6344 SourceLocation LParenLoc,
6345 ParsedType Ty,
6346 SourceLocation RParenLoc);
6347
6348 /// ParseObjCSelectorExpression - Build selector expression for \@selector
6349 ExprResult ParseObjCSelectorExpression(Selector Sel,
6350 SourceLocation AtLoc,
6351 SourceLocation SelLoc,
6352 SourceLocation LParenLoc,
6353 SourceLocation RParenLoc,
6354 bool WarnMultipleSelectors);
6355
6356 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
6357 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
6358 SourceLocation AtLoc,
6359 SourceLocation ProtoLoc,
6360 SourceLocation LParenLoc,
6361 SourceLocation ProtoIdLoc,
6362 SourceLocation RParenLoc);
6363
6364 //===--------------------------------------------------------------------===//
6365 // C++ Declarations
6366 //
6367 Decl *ActOnStartLinkageSpecification(Scope *S,
6368 SourceLocation ExternLoc,
6369 Expr *LangStr,
6370 SourceLocation LBraceLoc);
6371 Decl *ActOnFinishLinkageSpecification(Scope *S,
6372 Decl *LinkageSpec,
6373 SourceLocation RBraceLoc);
6374
6375
6376 //===--------------------------------------------------------------------===//
6377 // C++ Classes
6378 //
6379 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
6380 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
6381 const CXXScopeSpec *SS = nullptr);
6382 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
6383
6384 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
6385 SourceLocation ColonLoc,
6386 const ParsedAttributesView &Attrs);
6387
6388 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
6389 Declarator &D,
6390 MultiTemplateParamsArg TemplateParameterLists,
6391 Expr *BitfieldWidth, const VirtSpecifiers &VS,
6392 InClassInitStyle InitStyle);
6393
6394 void ActOnStartCXXInClassMemberInitializer();
6395 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
6396 SourceLocation EqualLoc,
6397 Expr *Init);
6398
6399 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6400 Scope *S,
6401 CXXScopeSpec &SS,
6402 IdentifierInfo *MemberOrBase,
6403 ParsedType TemplateTypeTy,
6404 const DeclSpec &DS,
6405 SourceLocation IdLoc,
6406 SourceLocation LParenLoc,
6407 ArrayRef<Expr *> Args,
6408 SourceLocation RParenLoc,
6409 SourceLocation EllipsisLoc);
6410
6411 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6412 Scope *S,
6413 CXXScopeSpec &SS,
6414 IdentifierInfo *MemberOrBase,
6415 ParsedType TemplateTypeTy,
6416 const DeclSpec &DS,
6417 SourceLocation IdLoc,
6418 Expr *InitList,
6419 SourceLocation EllipsisLoc);
6420
6421 MemInitResult BuildMemInitializer(Decl *ConstructorD,
6422 Scope *S,
6423 CXXScopeSpec &SS,
6424 IdentifierInfo *MemberOrBase,
6425 ParsedType TemplateTypeTy,
6426 const DeclSpec &DS,
6427 SourceLocation IdLoc,
6428 Expr *Init,
6429 SourceLocation EllipsisLoc);
6430
6431 MemInitResult BuildMemberInitializer(ValueDecl *Member,
6432 Expr *Init,
6433 SourceLocation IdLoc);
6434
6435 MemInitResult BuildBaseInitializer(QualType BaseType,
6436 TypeSourceInfo *BaseTInfo,
6437 Expr *Init,
6438 CXXRecordDecl *ClassDecl,
6439 SourceLocation EllipsisLoc);
6440
6441 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
6442 Expr *Init,
6443 CXXRecordDecl *ClassDecl);
6444
6445 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6446 CXXCtorInitializer *Initializer);
6447
6448 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6449 ArrayRef<CXXCtorInitializer *> Initializers = None);
6450
6451 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
6452
6453
6454 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6455 /// mark all the non-trivial destructors of its members and bases as
6456 /// referenced.
6457 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6458 CXXRecordDecl *Record);
6459
6460 /// The list of classes whose vtables have been used within
6461 /// this translation unit, and the source locations at which the
6462 /// first use occurred.
6463 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
6464
6465 /// The list of vtables that are required but have not yet been
6466 /// materialized.
6467 SmallVector<VTableUse, 16> VTableUses;
6468
6469 /// The set of classes whose vtables have been used within
6470 /// this translation unit, and a bit that will be true if the vtable is
6471 /// required to be emitted (otherwise, it should be emitted only if needed
6472 /// by code generation).
6473 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6474
6475 /// Load any externally-stored vtable uses.
6476 void LoadExternalVTableUses();
6477
6478 /// Note that the vtable for the given class was used at the
6479 /// given location.
6480 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6481 bool DefinitionRequired = false);
6482
6483 /// Mark the exception specifications of all virtual member functions
6484 /// in the given class as needed.
6485 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6486 const CXXRecordDecl *RD);
6487
6488 /// MarkVirtualMembersReferenced - Will mark all members of the given
6489 /// CXXRecordDecl referenced.
6490 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6491 bool ConstexprOnly = false);
6492
6493 /// Define all of the vtables that have been used in this
6494 /// translation unit and reference any virtual members used by those
6495 /// vtables.
6496 ///
6497 /// \returns true if any work was done, false otherwise.
6498 bool DefineUsedVTables();
6499
6500 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6501
6502 void ActOnMemInitializers(Decl *ConstructorDecl,
6503 SourceLocation ColonLoc,
6504 ArrayRef<CXXCtorInitializer*> MemInits,
6505 bool AnyErrors);
6506
6507 /// Check class-level dllimport/dllexport attribute. The caller must
6508 /// ensure that referenceDLLExportedClassMethods is called some point later
6509 /// when all outer classes of Class are complete.
6510 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6511 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6512
6513 void referenceDLLExportedClassMethods();
6514
6515 void propagateDLLAttrToBaseClassTemplate(
6516 CXXRecordDecl *Class, Attr *ClassAttr,
6517 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6518 SourceLocation BaseLoc);
6519
6520 /// Add gsl::Pointer attribute to std::container::iterator
6521 /// \param ND The declaration that introduces the name
6522 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
6523 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
6524
6525 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
6526 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
6527
6528 /// Add [[gsl::Pointer]] attributes for std:: types.
6529 void inferGslPointerAttribute(TypedefNameDecl *TD);
6530
6531 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6532
6533 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6534 /// conditions that are needed for the attribute to have an effect.
6535 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6536
6537 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6538 Decl *TagDecl, SourceLocation LBrac,
6539 SourceLocation RBrac,
6540 const ParsedAttributesView &AttrList);
6541 void ActOnFinishCXXMemberDecls();
6542 void ActOnFinishCXXNonNestedClass();
6543
6544 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6545 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
6546 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6547 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6548 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6549 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6550 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6551 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6552 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
6553 CachedTokens &Toks);
6554 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
6555 bool IsInsideALocalClassWithinATemplateFunction();
6556
6557 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6558 Expr *AssertExpr,
6559 Expr *AssertMessageExpr,
6560 SourceLocation RParenLoc);
6561 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6562 Expr *AssertExpr,
6563 StringLiteral *AssertMessageExpr,
6564 SourceLocation RParenLoc,
6565 bool Failed);
6566
6567 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
6568 SourceLocation FriendLoc,
6569 TypeSourceInfo *TSInfo);
6570 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6571 MultiTemplateParamsArg TemplateParams);
6572 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6573 MultiTemplateParamsArg TemplateParams);
6574
6575 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6576 StorageClass& SC);
6577 void CheckConstructor(CXXConstructorDecl *Constructor);
6578 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6579 StorageClass& SC);
6580 bool CheckDestructor(CXXDestructorDecl *Destructor);
6581 void CheckConversionDeclarator(Declarator &D, QualType &R,
6582 StorageClass& SC);
6583 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6584 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6585 StorageClass &SC);
6586 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
6587
6588 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6589
6590 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6591 CXXSpecialMember CSM);
6592 void CheckDelayedMemberExceptionSpecs();
6593
6594 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6595 DefaultedComparisonKind DCK);
6596 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6597 FunctionDecl *Spaceship);
6598 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6599 DefaultedComparisonKind DCK);
6600
6601 //===--------------------------------------------------------------------===//
6602 // C++ Derived Classes
6603 //
6604
6605 /// ActOnBaseSpecifier - Parsed a base specifier
6606 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6607 SourceRange SpecifierRange,
6608 bool Virtual, AccessSpecifier Access,
6609 TypeSourceInfo *TInfo,
6610 SourceLocation EllipsisLoc);
6611
6612 BaseResult ActOnBaseSpecifier(Decl *classdecl,
6613 SourceRange SpecifierRange,
6614 ParsedAttributes &Attrs,
6615 bool Virtual, AccessSpecifier Access,
6616 ParsedType basetype,
6617 SourceLocation BaseLoc,
6618 SourceLocation EllipsisLoc);
6619
6620 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6621 MutableArrayRef<CXXBaseSpecifier *> Bases);
6622 void ActOnBaseSpecifiers(Decl *ClassDecl,
6623 MutableArrayRef<CXXBaseSpecifier *> Bases);
6624
6625 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6626 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6627 CXXBasePaths &Paths);
6628
6629 // FIXME: I don't like this name.
6630 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6631
6632 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6633 SourceLocation Loc, SourceRange Range,
6634 CXXCastPath *BasePath = nullptr,
6635 bool IgnoreAccess = false);
6636 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6637 unsigned InaccessibleBaseID,
6638 unsigned AmbigiousBaseConvID,
6639 SourceLocation Loc, SourceRange Range,
6640 DeclarationName Name,
6641 CXXCastPath *BasePath,
6642 bool IgnoreAccess = false);
6643
6644 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6645
6646 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6647 const CXXMethodDecl *Old);
6648
6649 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6650 /// covariant, according to C++ [class.virtual]p5.
6651 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6652 const CXXMethodDecl *Old);
6653
6654 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6655 /// spec is a subset of base spec.
6656 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6657 const CXXMethodDecl *Old);
6658
6659 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6660
6661 /// CheckOverrideControl - Check C++11 override control semantics.
6662 void CheckOverrideControl(NamedDecl *D);
6663
6664 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6665 /// not used in the declaration of an overriding method.
6666 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
6667
6668 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
6669 /// overrides a virtual member function marked 'final', according to
6670 /// C++11 [class.virtual]p4.
6671 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6672 const CXXMethodDecl *Old);
6673
6674
6675 //===--------------------------------------------------------------------===//
6676 // C++ Access Control
6677 //
6678
6679 enum AccessResult {
6680 AR_accessible,
6681 AR_inaccessible,
6682 AR_dependent,
6683 AR_delayed
6684 };
6685
6686 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
6687 NamedDecl *PrevMemberDecl,
6688 AccessSpecifier LexicalAS);
6689
6690 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
6691 DeclAccessPair FoundDecl);
6692 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
6693 DeclAccessPair FoundDecl);
6694 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
6695 SourceRange PlacementRange,
6696 CXXRecordDecl *NamingClass,
6697 DeclAccessPair FoundDecl,
6698 bool Diagnose = true);
6699 AccessResult CheckConstructorAccess(SourceLocation Loc,
6700 CXXConstructorDecl *D,
6701 DeclAccessPair FoundDecl,
6702 const InitializedEntity &Entity,
6703 bool IsCopyBindingRefToTemp = false);
6704 AccessResult CheckConstructorAccess(SourceLocation Loc,
6705 CXXConstructorDecl *D,
6706 DeclAccessPair FoundDecl,
6707 const InitializedEntity &Entity,
6708 const PartialDiagnostic &PDiag);
6709 AccessResult CheckDestructorAccess(SourceLocation Loc,
6710 CXXDestructorDecl *Dtor,
6711 const PartialDiagnostic &PDiag,
6712 QualType objectType = QualType());
6713 AccessResult CheckFriendAccess(NamedDecl *D);
6714 AccessResult CheckMemberAccess(SourceLocation UseLoc,
6715 CXXRecordDecl *NamingClass,
6716 DeclAccessPair Found);
6717 AccessResult
6718 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
6719 CXXRecordDecl *DecomposedClass,
6720 DeclAccessPair Field);
6721 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
6722 Expr *ObjectExpr,
6723 Expr *ArgExpr,
6724 DeclAccessPair FoundDecl);
6725 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
6726 DeclAccessPair FoundDecl);
6727 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
6728 QualType Base, QualType Derived,
6729 const CXXBasePath &Path,
6730 unsigned DiagID,
6731 bool ForceCheck = false,
6732 bool ForceUnprivileged = false);
6733 void CheckLookupAccess(const LookupResult &R);
6734 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
6735 QualType BaseType);
6736 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
6737 DeclAccessPair Found, QualType ObjectType,
6738 SourceLocation Loc,
6739 const PartialDiagnostic &Diag);
6740 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
6741 DeclAccessPair Found,
6742 QualType ObjectType) {
6743 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
6744 SourceLocation(), PDiag());
6745 }
6746
6747 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6748 const MultiLevelTemplateArgumentList &TemplateArgs);
6749 void PerformDependentDiagnostics(const DeclContext *Pattern,
6750 const MultiLevelTemplateArgumentList &TemplateArgs);
6751
6752 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6753
6754 /// When true, access checking violations are treated as SFINAE
6755 /// failures rather than hard errors.
6756 bool AccessCheckingSFINAE;
6757
6758 enum AbstractDiagSelID {
6759 AbstractNone = -1,
6760 AbstractReturnType,
6761 AbstractParamType,
6762 AbstractVariableType,
6763 AbstractFieldType,
6764 AbstractIvarType,
6765 AbstractSynthesizedIvarType,
6766 AbstractArrayType
6767 };
6768
6769 bool isAbstractType(SourceLocation Loc, QualType T);
6770 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6771 TypeDiagnoser &Diagnoser);
6772 template <typename... Ts>
6773 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6774 const Ts &...Args) {
6775 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6776 return RequireNonAbstractType(Loc, T, Diagnoser);
6777 }
6778
6779 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6780
6781 //===--------------------------------------------------------------------===//
6782 // C++ Overloaded Operators [C++ 13.5]
6783 //
6784
6785 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6786
6787 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6788
6789 //===--------------------------------------------------------------------===//
6790 // C++ Templates [C++ 14]
6791 //
6792 void FilterAcceptableTemplateNames(LookupResult &R,
6793 bool AllowFunctionTemplates = true,
6794 bool AllowDependent = true);
6795 bool hasAnyAcceptableTemplateNames(LookupResult &R,
6796 bool AllowFunctionTemplates = true,
6797 bool AllowDependent = true,
6798 bool AllowNonTemplateFunctions = false);
6799 /// Try to interpret the lookup result D as a template-name.
6800 ///
6801 /// \param D A declaration found by name lookup.
6802 /// \param AllowFunctionTemplates Whether function templates should be
6803 /// considered valid results.
6804 /// \param AllowDependent Whether unresolved using declarations (that might
6805 /// name templates) should be considered valid results.
6806 NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
6807 bool AllowFunctionTemplates = true,
6808 bool AllowDependent = true);
6809
6810 enum class AssumedTemplateKind {
6811 /// This is not assumed to be a template name.
6812 None,
6813 /// This is assumed to be a template name because lookup found nothing.
6814 FoundNothing,
6815 /// This is assumed to be a template name because lookup found one or more
6816 /// functions (but no function templates).
6817 FoundFunctions,
6818 };
6819 bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6820 QualType ObjectType, bool EnteringContext,
6821 bool &MemberOfUnknownSpecialization,
6822 SourceLocation TemplateKWLoc = SourceLocation(),
6823 AssumedTemplateKind *ATK = nullptr);
6824
6825 TemplateNameKind isTemplateName(Scope *S,
6826 CXXScopeSpec &SS,
6827 bool hasTemplateKeyword,
6828 const UnqualifiedId &Name,
6829 ParsedType ObjectType,
6830 bool EnteringContext,
6831 TemplateTy &Template,
6832 bool &MemberOfUnknownSpecialization);
6833
6834 /// Try to resolve an undeclared template name as a type template.
6835 ///
6836 /// Sets II to the identifier corresponding to the template name, and updates
6837 /// Name to a corresponding (typo-corrected) type template name and TNK to
6838 /// the corresponding kind, if possible.
6839 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
6840 TemplateNameKind &TNK,
6841 SourceLocation NameLoc,
6842 IdentifierInfo *&II);
6843
6844 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
6845 SourceLocation NameLoc,
6846 bool Diagnose = true);
6847
6848 /// Determine whether a particular identifier might be the name in a C++1z
6849 /// deduction-guide declaration.
6850 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6851 SourceLocation NameLoc,
6852 ParsedTemplateTy *Template = nullptr);
6853
6854 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6855 SourceLocation IILoc,
6856 Scope *S,
6857 const CXXScopeSpec *SS,
6858 TemplateTy &SuggestedTemplate,
6859 TemplateNameKind &SuggestedKind);
6860
6861 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6862 NamedDecl *Instantiation,
6863 bool InstantiatedFromMember,
6864 const NamedDecl *Pattern,
6865 const NamedDecl *PatternDef,
6866 TemplateSpecializationKind TSK,
6867 bool Complain = true);
6868
6869 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6870 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6871
6872 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6873 SourceLocation EllipsisLoc,
6874 SourceLocation KeyLoc,
6875 IdentifierInfo *ParamName,
6876 SourceLocation ParamNameLoc,
6877 unsigned Depth, unsigned Position,
6878 SourceLocation EqualLoc,
6879 ParsedType DefaultArg);
6880
6881 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6882 SourceLocation Loc);
6883 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6884
6885 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6886 unsigned Depth,
6887 unsigned Position,
6888 SourceLocation EqualLoc,
6889 Expr *DefaultArg);
6890 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6891 SourceLocation TmpLoc,
6892 TemplateParameterList *Params,
6893 SourceLocation EllipsisLoc,
6894 IdentifierInfo *ParamName,
6895 SourceLocation ParamNameLoc,
6896 unsigned Depth,
6897 unsigned Position,
6898 SourceLocation EqualLoc,
6899 ParsedTemplateArgument DefaultArg);
6900
6901 TemplateParameterList *
6902 ActOnTemplateParameterList(unsigned Depth,
6903 SourceLocation ExportLoc,
6904 SourceLocation TemplateLoc,
6905 SourceLocation LAngleLoc,
6906 ArrayRef<NamedDecl *> Params,
6907 SourceLocation RAngleLoc,
6908 Expr *RequiresClause);
6909
6910 /// The context in which we are checking a template parameter list.
6911 enum TemplateParamListContext {
6912 TPC_ClassTemplate,
6913 TPC_VarTemplate,
6914 TPC_FunctionTemplate,
6915 TPC_ClassTemplateMember,
6916 TPC_FriendClassTemplate,
6917 TPC_FriendFunctionTemplate,
6918 TPC_FriendFunctionTemplateDefinition,
6919 TPC_TypeAliasTemplate
6920 };
6921
6922 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6923 TemplateParameterList *OldParams,
6924 TemplateParamListContext TPC,
6925 SkipBodyInfo *SkipBody = nullptr);
6926 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6927 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6928 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6929 ArrayRef<TemplateParameterList *> ParamLists,
6930 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6931
6932 DeclResult CheckClassTemplate(
6933 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
6934 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
6935 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
6936 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
6937 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
6938 TemplateParameterList **OuterTemplateParamLists,
6939 SkipBodyInfo *SkipBody = nullptr);
6940
6941 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6942 QualType NTTPType,
6943 SourceLocation Loc);
6944
6945 /// Get a template argument mapping the given template parameter to itself,
6946 /// e.g. for X in \c template<int X>, this would return an expression template
6947 /// argument referencing X.
6948 TemplateArgumentLoc getIdentityTemplateArgumentLoc(Decl *Param,
6949 SourceLocation Location);
6950
6951 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6952 TemplateArgumentListInfo &Out);
6953
6954 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
6955
6956 void NoteAllFoundTemplates(TemplateName Name);
6957
6958 QualType CheckTemplateIdType(TemplateName Template,
6959 SourceLocation TemplateLoc,
6960 TemplateArgumentListInfo &TemplateArgs);
6961
6962 TypeResult
6963 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6964 TemplateTy Template, IdentifierInfo *TemplateII,
6965 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
6966 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
6967 bool IsCtorOrDtorName = false, bool IsClassName = false);
6968
6969 /// Parsed an elaborated-type-specifier that refers to a template-id,
6970 /// such as \c class T::template apply<U>.
6971 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6972 TypeSpecifierType TagSpec,
6973 SourceLocation TagLoc,
6974 CXXScopeSpec &SS,
6975 SourceLocation TemplateKWLoc,
6976 TemplateTy TemplateD,
6977 SourceLocation TemplateLoc,
6978 SourceLocation LAngleLoc,
6979 ASTTemplateArgsPtr TemplateArgsIn,
6980 SourceLocation RAngleLoc);
6981
6982 DeclResult ActOnVarTemplateSpecialization(
6983 Scope *S, Declarator &D, TypeSourceInfo *DI,
6984 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6985 StorageClass SC, bool IsPartialSpecialization);
6986
6987 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6988 SourceLocation TemplateLoc,
6989 SourceLocation TemplateNameLoc,
6990 const TemplateArgumentListInfo &TemplateArgs);
6991
6992 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6993 const DeclarationNameInfo &NameInfo,
6994 VarTemplateDecl *Template,
6995 SourceLocation TemplateLoc,
6996 const TemplateArgumentListInfo *TemplateArgs);
6997
6998 ExprResult
6999 CheckConceptTemplateId(const CXXScopeSpec &SS,
7000 SourceLocation TemplateKWLoc,
7001 SourceLocation ConceptNameLoc, NamedDecl *FoundDecl,
7002 ConceptDecl *NamedConcept,
7003 const TemplateArgumentListInfo *TemplateArgs);
7004
7005 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7006
7007 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7008 SourceLocation TemplateKWLoc,
7009 LookupResult &R,
7010 bool RequiresADL,
7011 const TemplateArgumentListInfo *TemplateArgs);
7012
7013 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7014 SourceLocation TemplateKWLoc,
7015 const DeclarationNameInfo &NameInfo,
7016 const TemplateArgumentListInfo *TemplateArgs);
7017
7018 TemplateNameKind ActOnDependentTemplateName(
7019 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7020 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7021 TemplateTy &Template, bool AllowInjectedClassName = false);
7022
7023 DeclResult ActOnClassTemplateSpecialization(
7024 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7025 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7026 const ParsedAttributesView &Attr,
7027 MultiTemplateParamsArg TemplateParameterLists,
7028 SkipBodyInfo *SkipBody = nullptr);
7029
7030 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7031 TemplateDecl *PrimaryTemplate,
7032 unsigned NumExplicitArgs,
7033 ArrayRef<TemplateArgument> Args);
7034 void CheckTemplatePartialSpecialization(
7035 ClassTemplatePartialSpecializationDecl *Partial);
7036 void CheckTemplatePartialSpecialization(
7037 VarTemplatePartialSpecializationDecl *Partial);
7038
7039 Decl *ActOnTemplateDeclarator(Scope *S,
7040 MultiTemplateParamsArg TemplateParameterLists,
7041 Declarator &D);
7042
7043 bool
7044 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7045 TemplateSpecializationKind NewTSK,
7046 NamedDecl *PrevDecl,
7047 TemplateSpecializationKind PrevTSK,
7048 SourceLocation PrevPtOfInstantiation,
7049 bool &SuppressNew);
7050
7051 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7052 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7053 LookupResult &Previous);
7054
7055 bool CheckFunctionTemplateSpecialization(
7056 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7057 LookupResult &Previous, bool QualifiedFriend = false);
7058 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7059 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7060
7061 DeclResult ActOnExplicitInstantiation(
7062 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7063 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7064 TemplateTy Template, SourceLocation TemplateNameLoc,
7065 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7066 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7067
7068 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7069 SourceLocation TemplateLoc,
7070 unsigned TagSpec, SourceLocation KWLoc,
7071 CXXScopeSpec &SS, IdentifierInfo *Name,
7072 SourceLocation NameLoc,
7073 const ParsedAttributesView &Attr);
7074
7075 DeclResult ActOnExplicitInstantiation(Scope *S,
7076 SourceLocation ExternLoc,
7077 SourceLocation TemplateLoc,
7078 Declarator &D);
7079
7080 TemplateArgumentLoc
7081 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7082 SourceLocation TemplateLoc,
7083 SourceLocation RAngleLoc,
7084 Decl *Param,
7085 SmallVectorImpl<TemplateArgument>
7086 &Converted,
7087 bool &HasDefaultArg);
7088
7089 /// Specifies the context in which a particular template
7090 /// argument is being checked.
7091 enum CheckTemplateArgumentKind {
7092 /// The template argument was specified in the code or was
7093 /// instantiated with some deduced template arguments.
7094 CTAK_Specified,
7095
7096 /// The template argument was deduced via template argument
7097 /// deduction.
7098 CTAK_Deduced,
7099
7100 /// The template argument was deduced from an array bound
7101 /// via template argument deduction.
7102 CTAK_DeducedFromArrayBound
7103 };
7104
7105 bool CheckTemplateArgument(NamedDecl *Param,
7106 TemplateArgumentLoc &Arg,
7107 NamedDecl *Template,
7108 SourceLocation TemplateLoc,
7109 SourceLocation RAngleLoc,
7110 unsigned ArgumentPackIndex,
7111 SmallVectorImpl<TemplateArgument> &Converted,
7112 CheckTemplateArgumentKind CTAK = CTAK_Specified);
7113
7114 /// Check that the given template arguments can be be provided to
7115 /// the given template, converting the arguments along the way.
7116 ///
7117 /// \param Template The template to which the template arguments are being
7118 /// provided.
7119 ///
7120 /// \param TemplateLoc The location of the template name in the source.
7121 ///
7122 /// \param TemplateArgs The list of template arguments. If the template is
7123 /// a template template parameter, this function may extend the set of
7124 /// template arguments to also include substituted, defaulted template
7125 /// arguments.
7126 ///
7127 /// \param PartialTemplateArgs True if the list of template arguments is
7128 /// intentionally partial, e.g., because we're checking just the initial
7129 /// set of template arguments.
7130 ///
7131 /// \param Converted Will receive the converted, canonicalized template
7132 /// arguments.
7133 ///
7134 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
7135 /// contain the converted forms of the template arguments as written.
7136 /// Otherwise, \p TemplateArgs will not be modified.
7137 ///
7138 /// \param ConstraintsNotSatisfied If provided, and an error occured, will
7139 /// receive true if the cause for the error is the associated constraints of
7140 /// the template not being satisfied by the template arguments.
7141 ///
7142 /// \returns true if an error occurred, false otherwise.
7143 bool CheckTemplateArgumentList(TemplateDecl *Template,
7144 SourceLocation TemplateLoc,
7145 TemplateArgumentListInfo &TemplateArgs,
7146 bool PartialTemplateArgs,
7147 SmallVectorImpl<TemplateArgument> &Converted,
7148 bool UpdateArgsWithConversions = true,
7149 bool *ConstraintsNotSatisfied = nullptr);
7150
7151 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
7152 TemplateArgumentLoc &Arg,
7153 SmallVectorImpl<TemplateArgument> &Converted);
7154
7155 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
7156 TypeSourceInfo *Arg);
7157 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7158 QualType InstantiatedParamType, Expr *Arg,
7159 TemplateArgument &Converted,
7160 CheckTemplateArgumentKind CTAK = CTAK_Specified);
7161 bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
7162 TemplateArgumentLoc &Arg);
7163
7164 ExprResult
7165 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7166 QualType ParamType,
7167 SourceLocation Loc);
7168 ExprResult
7169 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7170 SourceLocation Loc);
7171
7172 /// Enumeration describing how template parameter lists are compared
7173 /// for equality.
7174 enum TemplateParameterListEqualKind {
7175 /// We are matching the template parameter lists of two templates
7176 /// that might be redeclarations.
7177 ///
7178 /// \code
7179 /// template<typename T> struct X;
7180 /// template<typename T> struct X;
7181 /// \endcode
7182 TPL_TemplateMatch,
7183
7184 /// We are matching the template parameter lists of two template
7185 /// template parameters as part of matching the template parameter lists
7186 /// of two templates that might be redeclarations.
7187 ///
7188 /// \code
7189 /// template<template<int I> class TT> struct X;
7190 /// template<template<int Value> class Other> struct X;
7191 /// \endcode
7192 TPL_TemplateTemplateParmMatch,
7193
7194 /// We are matching the template parameter lists of a template
7195 /// template argument against the template parameter lists of a template
7196 /// template parameter.
7197 ///
7198 /// \code
7199 /// template<template<int Value> class Metafun> struct X;
7200 /// template<int Value> struct integer_c;
7201 /// X<integer_c> xic;
7202 /// \endcode
7203 TPL_TemplateTemplateArgumentMatch
7204 };
7205
7206 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
7207 TemplateParameterList *Old,
7208 bool Complain,
7209 TemplateParameterListEqualKind Kind,
7210 SourceLocation TemplateArgLoc
7211 = SourceLocation());
7212
7213 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
7214
7215 /// Called when the parser has parsed a C++ typename
7216 /// specifier, e.g., "typename T::type".
7217 ///
7218 /// \param S The scope in which this typename type occurs.
7219 /// \param TypenameLoc the location of the 'typename' keyword
7220 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7221 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
7222 /// \param IdLoc the location of the identifier.
7223 TypeResult
7224 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7225 const CXXScopeSpec &SS, const IdentifierInfo &II,
7226 SourceLocation IdLoc);
7227
7228 /// Called when the parser has parsed a C++ typename
7229 /// specifier that ends in a template-id, e.g.,
7230 /// "typename MetaFun::template apply<T1, T2>".
7231 ///
7232 /// \param S The scope in which this typename type occurs.
7233 /// \param TypenameLoc the location of the 'typename' keyword
7234 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7235 /// \param TemplateLoc the location of the 'template' keyword, if any.
7236 /// \param TemplateName The template name.
7237 /// \param TemplateII The identifier used to name the template.
7238 /// \param TemplateIILoc The location of the template name.
7239 /// \param LAngleLoc The location of the opening angle bracket ('<').
7240 /// \param TemplateArgs The template arguments.
7241 /// \param RAngleLoc The location of the closing angle bracket ('>').
7242 TypeResult
7243 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7244 const CXXScopeSpec &SS,
7245 SourceLocation TemplateLoc,
7246 TemplateTy TemplateName,
7247 IdentifierInfo *TemplateII,
7248 SourceLocation TemplateIILoc,
7249 SourceLocation LAngleLoc,
7250 ASTTemplateArgsPtr TemplateArgs,
7251 SourceLocation RAngleLoc);
7252
7253 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7254 SourceLocation KeywordLoc,
7255 NestedNameSpecifierLoc QualifierLoc,
7256 const IdentifierInfo &II,
7257 SourceLocation IILoc);
7258
7259 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7260 SourceLocation Loc,
7261 DeclarationName Name);
7262 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
7263
7264 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
7265 bool RebuildTemplateParamsInCurrentInstantiation(
7266 TemplateParameterList *Params);
7267
7268 std::string
7269 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7270 const TemplateArgumentList &Args);
7271
7272 std::string
7273 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7274 const TemplateArgument *Args,
7275 unsigned NumArgs);
7276
7277 // Concepts
7278 Decl *ActOnConceptDefinition(
7279 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
7280 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
7281
7282 //===--------------------------------------------------------------------===//
7283 // C++ Variadic Templates (C++0x [temp.variadic])
7284 //===--------------------------------------------------------------------===//
7285
7286 /// Determine whether an unexpanded parameter pack might be permitted in this
7287 /// location. Useful for error recovery.
7288 bool isUnexpandedParameterPackPermitted();
7289
7290 /// The context in which an unexpanded parameter pack is
7291 /// being diagnosed.
7292 ///
7293 /// Note that the values of this enumeration line up with the first
7294 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
7295 enum UnexpandedParameterPackContext {
7296 /// An arbitrary expression.
7297 UPPC_Expression = 0,
7298
7299 /// The base type of a class type.
7300 UPPC_BaseType,
7301
7302 /// The type of an arbitrary declaration.
7303 UPPC_DeclarationType,
7304
7305 /// The type of a data member.
7306 UPPC_DataMemberType,
7307
7308 /// The size of a bit-field.
7309 UPPC_BitFieldWidth,
7310
7311 /// The expression in a static assertion.
7312 UPPC_StaticAssertExpression,
7313
7314 /// The fixed underlying type of an enumeration.
7315 UPPC_FixedUnderlyingType,
7316
7317 /// The enumerator value.
7318 UPPC_EnumeratorValue,
7319
7320 /// A using declaration.
7321 UPPC_UsingDeclaration,
7322
7323 /// A friend declaration.
7324 UPPC_FriendDeclaration,
7325
7326 /// A declaration qualifier.
7327 UPPC_DeclarationQualifier,
7328
7329 /// An initializer.
7330 UPPC_Initializer,
7331
7332 /// A default argument.
7333 UPPC_DefaultArgument,
7334
7335 /// The type of a non-type template parameter.
7336 UPPC_NonTypeTemplateParameterType,
7337
7338 /// The type of an exception.
7339 UPPC_ExceptionType,
7340
7341 /// Partial specialization.
7342 UPPC_PartialSpecialization,
7343
7344 /// Microsoft __if_exists.
7345 UPPC_IfExists,
7346
7347 /// Microsoft __if_not_exists.
7348 UPPC_IfNotExists,
7349
7350 /// Lambda expression.
7351 UPPC_Lambda,
7352
7353 /// Block expression,
7354 UPPC_Block
7355 };
7356
7357 /// Diagnose unexpanded parameter packs.
7358 ///
7359 /// \param Loc The location at which we should emit the diagnostic.
7360 ///
7361 /// \param UPPC The context in which we are diagnosing unexpanded
7362 /// parameter packs.
7363 ///
7364 /// \param Unexpanded the set of unexpanded parameter packs.
7365 ///
7366 /// \returns true if an error occurred, false otherwise.
7367 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
7368 UnexpandedParameterPackContext UPPC,
7369 ArrayRef<UnexpandedParameterPack> Unexpanded);
7370
7371 /// If the given type contains an unexpanded parameter pack,
7372 /// diagnose the error.
7373 ///
7374 /// \param Loc The source location where a diagnostc should be emitted.
7375 ///
7376 /// \param T The type that is being checked for unexpanded parameter
7377 /// packs.
7378 ///
7379 /// \returns true if an error occurred, false otherwise.
7380 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
7381 UnexpandedParameterPackContext UPPC);
7382
7383 /// If the given expression contains an unexpanded parameter
7384 /// pack, diagnose the error.
7385 ///
7386 /// \param E The expression that is being checked for unexpanded
7387 /// parameter packs.
7388 ///
7389 /// \returns true if an error occurred, false otherwise.
7390 bool DiagnoseUnexpandedParameterPack(Expr *E,
7391 UnexpandedParameterPackContext UPPC = UPPC_Expression);
7392
7393 /// If the given nested-name-specifier contains an unexpanded
7394 /// parameter pack, diagnose the error.
7395 ///
7396 /// \param SS The nested-name-specifier that is being checked for
7397 /// unexpanded parameter packs.
7398 ///
7399 /// \returns true if an error occurred, false otherwise.
7400 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
7401 UnexpandedParameterPackContext UPPC);
7402
7403 /// If the given name contains an unexpanded parameter pack,
7404 /// diagnose the error.
7405 ///
7406 /// \param NameInfo The name (with source location information) that
7407 /// is being checked for unexpanded parameter packs.
7408 ///
7409 /// \returns true if an error occurred, false otherwise.
7410 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
7411 UnexpandedParameterPackContext UPPC);
7412
7413 /// If the given template name contains an unexpanded parameter pack,
7414 /// diagnose the error.
7415 ///
7416 /// \param Loc The location of the template name.
7417 ///
7418 /// \param Template The template name that is being checked for unexpanded
7419 /// parameter packs.
7420 ///
7421 /// \returns true if an error occurred, false otherwise.
7422 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
7423 TemplateName Template,
7424 UnexpandedParameterPackContext UPPC);
7425
7426 /// If the given template argument contains an unexpanded parameter
7427 /// pack, diagnose the error.
7428 ///
7429 /// \param Arg The template argument that is being checked for unexpanded
7430 /// parameter packs.
7431 ///
7432 /// \returns true if an error occurred, false otherwise.
7433 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
7434 UnexpandedParameterPackContext UPPC);
7435
7436 /// Collect the set of unexpanded parameter packs within the given
7437 /// template argument.
7438 ///
7439 /// \param Arg The template argument that will be traversed to find
7440 /// unexpanded parameter packs.
7441 void collectUnexpandedParameterPacks(TemplateArgument Arg,
7442 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7443
7444 /// Collect the set of unexpanded parameter packs within the given
7445 /// template argument.
7446 ///
7447 /// \param Arg The template argument that will be traversed to find
7448 /// unexpanded parameter packs.
7449 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
7450 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7451
7452 /// Collect the set of unexpanded parameter packs within the given
7453 /// type.
7454 ///
7455 /// \param T The type that will be traversed to find
7456 /// unexpanded parameter packs.
7457 void collectUnexpandedParameterPacks(QualType T,
7458 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7459
7460 /// Collect the set of unexpanded parameter packs within the given
7461 /// type.
7462 ///
7463 /// \param TL The type that will be traversed to find
7464 /// unexpanded parameter packs.
7465 void collectUnexpandedParameterPacks(TypeLoc TL,
7466 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7467
7468 /// Collect the set of unexpanded parameter packs within the given
7469 /// nested-name-specifier.
7470 ///
7471 /// \param NNS The nested-name-specifier that will be traversed to find
7472 /// unexpanded parameter packs.
7473 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
7474 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7475
7476 /// Collect the set of unexpanded parameter packs within the given
7477 /// name.
7478 ///
7479 /// \param NameInfo The name that will be traversed to find
7480 /// unexpanded parameter packs.
7481 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
7482 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7483
7484 /// Invoked when parsing a template argument followed by an
7485 /// ellipsis, which creates a pack expansion.
7486 ///
7487 /// \param Arg The template argument preceding the ellipsis, which
7488 /// may already be invalid.
7489 ///
7490 /// \param EllipsisLoc The location of the ellipsis.
7491 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
7492 SourceLocation EllipsisLoc);
7493
7494 /// Invoked when parsing a type followed by an ellipsis, which
7495 /// creates a pack expansion.
7496 ///
7497 /// \param Type The type preceding the ellipsis, which will become
7498 /// the pattern of the pack expansion.
7499 ///
7500 /// \param EllipsisLoc The location of the ellipsis.
7501 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
7502
7503 /// Construct a pack expansion type from the pattern of the pack
7504 /// expansion.
7505 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
7506 SourceLocation EllipsisLoc,
7507 Optional<unsigned> NumExpansions);
7508
7509 /// Construct a pack expansion type from the pattern of the pack
7510 /// expansion.
7511 QualType CheckPackExpansion(QualType Pattern,
7512 SourceRange PatternRange,
7513 SourceLocation EllipsisLoc,
7514 Optional<unsigned> NumExpansions);
7515
7516 /// Invoked when parsing an expression followed by an ellipsis, which
7517 /// creates a pack expansion.
7518 ///
7519 /// \param Pattern The expression preceding the ellipsis, which will become
7520 /// the pattern of the pack expansion.
7521 ///
7522 /// \param EllipsisLoc The location of the ellipsis.
7523 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
7524
7525 /// Invoked when parsing an expression followed by an ellipsis, which
7526 /// creates a pack expansion.
7527 ///
7528 /// \param Pattern The expression preceding the ellipsis, which will become
7529 /// the pattern of the pack expansion.
7530 ///
7531 /// \param EllipsisLoc The location of the ellipsis.
7532 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
7533 Optional<unsigned> NumExpansions);
7534
7535 /// Determine whether we could expand a pack expansion with the
7536 /// given set of parameter packs into separate arguments by repeatedly
7537 /// transforming the pattern.
7538 ///
7539 /// \param EllipsisLoc The location of the ellipsis that identifies the
7540 /// pack expansion.
7541 ///
7542 /// \param PatternRange The source range that covers the entire pattern of
7543 /// the pack expansion.
7544 ///
7545 /// \param Unexpanded The set of unexpanded parameter packs within the
7546 /// pattern.
7547 ///
7548 /// \param ShouldExpand Will be set to \c true if the transformer should
7549 /// expand the corresponding pack expansions into separate arguments. When
7550 /// set, \c NumExpansions must also be set.
7551 ///
7552 /// \param RetainExpansion Whether the caller should add an unexpanded
7553 /// pack expansion after all of the expanded arguments. This is used
7554 /// when extending explicitly-specified template argument packs per
7555 /// C++0x [temp.arg.explicit]p9.
7556 ///
7557 /// \param NumExpansions The number of separate arguments that will be in
7558 /// the expanded form of the corresponding pack expansion. This is both an
7559 /// input and an output parameter, which can be set by the caller if the
7560 /// number of expansions is known a priori (e.g., due to a prior substitution)
7561 /// and will be set by the callee when the number of expansions is known.
7562 /// The callee must set this value when \c ShouldExpand is \c true; it may
7563 /// set this value in other cases.
7564 ///
7565 /// \returns true if an error occurred (e.g., because the parameter packs
7566 /// are to be instantiated with arguments of different lengths), false
7567 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
7568 /// must be set.
7569 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
7570 SourceRange PatternRange,
7571 ArrayRef<UnexpandedParameterPack> Unexpanded,
7572 const MultiLevelTemplateArgumentList &TemplateArgs,
7573 bool &ShouldExpand,
7574 bool &RetainExpansion,
7575 Optional<unsigned> &NumExpansions);
7576
7577 /// Determine the number of arguments in the given pack expansion
7578 /// type.
7579 ///
7580 /// This routine assumes that the number of arguments in the expansion is
7581 /// consistent across all of the unexpanded parameter packs in its pattern.
7582 ///
7583 /// Returns an empty Optional if the type can't be expanded.
7584 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
7585 const MultiLevelTemplateArgumentList &TemplateArgs);
7586
7587 /// Determine whether the given declarator contains any unexpanded
7588 /// parameter packs.
7589 ///
7590 /// This routine is used by the parser to disambiguate function declarators
7591 /// with an ellipsis prior to the ')', e.g.,
7592 ///
7593 /// \code
7594 /// void f(T...);
7595 /// \endcode
7596 ///
7597 /// To determine whether we have an (unnamed) function parameter pack or
7598 /// a variadic function.
7599 ///
7600 /// \returns true if the declarator contains any unexpanded parameter packs,
7601 /// false otherwise.
7602 bool containsUnexpandedParameterPacks(Declarator &D);
7603
7604 /// Returns the pattern of the pack expansion for a template argument.
7605 ///
7606 /// \param OrigLoc The template argument to expand.
7607 ///
7608 /// \param Ellipsis Will be set to the location of the ellipsis.
7609 ///
7610 /// \param NumExpansions Will be set to the number of expansions that will
7611 /// be generated from this pack expansion, if known a priori.
7612 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
7613 TemplateArgumentLoc OrigLoc,
7614 SourceLocation &Ellipsis,
7615 Optional<unsigned> &NumExpansions) const;
7616
7617 /// Given a template argument that contains an unexpanded parameter pack, but
7618 /// which has already been substituted, attempt to determine the number of
7619 /// elements that will be produced once this argument is fully-expanded.
7620 ///
7621 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
7622 /// avoid actually expanding the pack where possible.
7623 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
7624
7625 //===--------------------------------------------------------------------===//
7626 // C++ Template Argument Deduction (C++ [temp.deduct])
7627 //===--------------------------------------------------------------------===//
7628
7629 /// Adjust the type \p ArgFunctionType to match the calling convention,
7630 /// noreturn, and optionally the exception specification of \p FunctionType.
7631 /// Deduction often wants to ignore these properties when matching function
7632 /// types.
7633 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
7634 bool AdjustExceptionSpec = false);
7635
7636 /// Describes the result of template argument deduction.
7637 ///
7638 /// The TemplateDeductionResult enumeration describes the result of
7639 /// template argument deduction, as returned from
7640 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
7641 /// structure provides additional information about the results of
7642 /// template argument deduction, e.g., the deduced template argument
7643 /// list (if successful) or the specific template parameters or
7644 /// deduced arguments that were involved in the failure.
7645 enum TemplateDeductionResult {
7646 /// Template argument deduction was successful.
7647 TDK_Success = 0,
7648 /// The declaration was invalid; do nothing.
7649 TDK_Invalid,
7650 /// Template argument deduction exceeded the maximum template
7651 /// instantiation depth (which has already been diagnosed).
7652 TDK_InstantiationDepth,
7653 /// Template argument deduction did not deduce a value
7654 /// for every template parameter.
7655 TDK_Incomplete,
7656 /// Template argument deduction did not deduce a value for every
7657 /// expansion of an expanded template parameter pack.
7658 TDK_IncompletePack,
7659 /// Template argument deduction produced inconsistent
7660 /// deduced values for the given template parameter.
7661 TDK_Inconsistent,
7662 /// Template argument deduction failed due to inconsistent
7663 /// cv-qualifiers on a template parameter type that would
7664 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
7665 /// but were given a non-const "X".
7666 TDK_Underqualified,
7667 /// Substitution of the deduced template argument values
7668 /// resulted in an error.
7669 TDK_SubstitutionFailure,
7670 /// After substituting deduced template arguments, a dependent
7671 /// parameter type did not match the corresponding argument.
7672 TDK_DeducedMismatch,
7673 /// After substituting deduced template arguments, an element of
7674 /// a dependent parameter type did not match the corresponding element
7675 /// of the corresponding argument (when deducing from an initializer list).
7676 TDK_DeducedMismatchNested,
7677 /// A non-depnedent component of the parameter did not match the
7678 /// corresponding component of the argument.
7679 TDK_NonDeducedMismatch,
7680 /// When performing template argument deduction for a function
7681 /// template, there were too many call arguments.
7682 TDK_TooManyArguments,
7683 /// When performing template argument deduction for a function
7684 /// template, there were too few call arguments.
7685 TDK_TooFewArguments,
7686 /// The explicitly-specified template arguments were not valid
7687 /// template arguments for the given template.
7688 TDK_InvalidExplicitArguments,
7689 /// Checking non-dependent argument conversions failed.
7690 TDK_NonDependentConversionFailure,
7691 /// The deduced arguments did not satisfy the constraints associated
7692 /// with the template.
7693 TDK_ConstraintsNotSatisfied,
7694 /// Deduction failed; that's all we know.
7695 TDK_MiscellaneousDeductionFailure,
7696 /// CUDA Target attributes do not match.
7697 TDK_CUDATargetMismatch
7698 };
7699
7700 TemplateDeductionResult
7701 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
7702 const TemplateArgumentList &TemplateArgs,
7703 sema::TemplateDeductionInfo &Info);
7704
7705 TemplateDeductionResult
7706 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
7707 const TemplateArgumentList &TemplateArgs,
7708 sema::TemplateDeductionInfo &Info);
7709
7710 TemplateDeductionResult SubstituteExplicitTemplateArguments(
7711 FunctionTemplateDecl *FunctionTemplate,
7712 TemplateArgumentListInfo &ExplicitTemplateArgs,
7713 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7714 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
7715 sema::TemplateDeductionInfo &Info);
7716
7717 /// brief A function argument from which we performed template argument
7718 // deduction for a call.
7719 struct OriginalCallArg {
7720 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
7721 unsigned ArgIdx, QualType OriginalArgType)
7722 : OriginalParamType(OriginalParamType),
7723 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
7724 OriginalArgType(OriginalArgType) {}
7725
7726 QualType OriginalParamType;
7727 bool DecomposedParam;
7728 unsigned ArgIdx;
7729 QualType OriginalArgType;
7730 };
7731
7732 TemplateDeductionResult FinishTemplateArgumentDeduction(
7733 FunctionTemplateDecl *FunctionTemplate,
7734 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7735 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
7736 sema::TemplateDeductionInfo &Info,
7737 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
7738 bool PartialOverloading = false,
7739 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
7740
7741 TemplateDeductionResult DeduceTemplateArguments(
7742 FunctionTemplateDecl *FunctionTemplate,
7743 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7744 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
7745 bool PartialOverloading,
7746 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
7747
7748 TemplateDeductionResult
7749 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7750 TemplateArgumentListInfo *ExplicitTemplateArgs,
7751 QualType ArgFunctionType,
7752 FunctionDecl *&Specialization,
7753 sema::TemplateDeductionInfo &Info,
7754 bool IsAddressOfFunction = false);
7755
7756 TemplateDeductionResult
7757 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7758 QualType ToType,
7759 CXXConversionDecl *&Specialization,
7760 sema::TemplateDeductionInfo &Info);
7761
7762 TemplateDeductionResult
7763 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7764 TemplateArgumentListInfo *ExplicitTemplateArgs,
7765 FunctionDecl *&Specialization,
7766 sema::TemplateDeductionInfo &Info,
7767 bool IsAddressOfFunction = false);
7768
7769 /// Substitute Replacement for \p auto in \p TypeWithAuto
7770 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
7771 /// Substitute Replacement for auto in TypeWithAuto
7772 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
7773 QualType Replacement);
7774 /// Completely replace the \c auto in \p TypeWithAuto by
7775 /// \p Replacement. This does not retain any \c auto type sugar.
7776 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
7777
7778 /// Result type of DeduceAutoType.
7779 enum DeduceAutoResult {
7780 DAR_Succeeded,
7781 DAR_Failed,
7782 DAR_FailedAlreadyDiagnosed
7783 };
7784
7785 DeduceAutoResult
7786 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
7787 Optional<unsigned> DependentDeductionDepth = None);
7788 DeduceAutoResult
7789 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
7790 Optional<unsigned> DependentDeductionDepth = None);
7791 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
7792 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
7793 bool Diagnose = true);
7794
7795 /// Declare implicit deduction guides for a class template if we've
7796 /// not already done so.
7797 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7798 SourceLocation Loc);
7799
7800 QualType DeduceTemplateSpecializationFromInitializer(
7801 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7802 const InitializationKind &Kind, MultiExprArg Init);
7803
7804 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7805 QualType Type, TypeSourceInfo *TSI,
7806 SourceRange Range, bool DirectInit,
7807 Expr *Init);
7808
7809 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7810
7811 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7812 SourceLocation ReturnLoc,
7813 Expr *&RetExpr, AutoType *AT);
7814
7815 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7816 FunctionTemplateDecl *FT2,
7817 SourceLocation Loc,
7818 TemplatePartialOrderingContext TPOC,
7819 unsigned NumCallArguments1,
7820 unsigned NumCallArguments2);
7821 UnresolvedSetIterator
7822 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7823 TemplateSpecCandidateSet &FailedCandidates,
7824 SourceLocation Loc,
7825 const PartialDiagnostic &NoneDiag,
7826 const PartialDiagnostic &AmbigDiag,
7827 const PartialDiagnostic &CandidateDiag,
7828 bool Complain = true, QualType TargetType = QualType());
7829
7830 ClassTemplatePartialSpecializationDecl *
7831 getMoreSpecializedPartialSpecialization(
7832 ClassTemplatePartialSpecializationDecl *PS1,
7833 ClassTemplatePartialSpecializationDecl *PS2,
7834 SourceLocation Loc);
7835
7836 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7837 sema::TemplateDeductionInfo &Info);
7838
7839 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7840 VarTemplatePartialSpecializationDecl *PS1,
7841 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7842
7843 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7844 sema::TemplateDeductionInfo &Info);
7845
7846 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7847 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
7848
7849 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7850 unsigned Depth, llvm::SmallBitVector &Used);
7851
7852 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7853 bool OnlyDeduced,
7854 unsigned Depth,
7855 llvm::SmallBitVector &Used);
7856 void MarkDeducedTemplateParameters(
7857 const FunctionTemplateDecl *FunctionTemplate,
7858 llvm::SmallBitVector &Deduced) {
7859 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
7860 }
7861 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
7862 const FunctionTemplateDecl *FunctionTemplate,
7863 llvm::SmallBitVector &Deduced);
7864
7865 //===--------------------------------------------------------------------===//
7866 // C++ Template Instantiation
7867 //
7868
7869 MultiLevelTemplateArgumentList
7870 getTemplateInstantiationArgs(NamedDecl *D,
7871 const TemplateArgumentList *Innermost = nullptr,
7872 bool RelativeToPrimary = false,
7873 const FunctionDecl *Pattern = nullptr);
7874
7875 /// A context in which code is being synthesized (where a source location
7876 /// alone is not sufficient to identify the context). This covers template
7877 /// instantiation and various forms of implicitly-generated functions.
7878 struct CodeSynthesisContext {
7879 /// The kind of template instantiation we are performing
7880 enum SynthesisKind {
7881 /// We are instantiating a template declaration. The entity is
7882 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7883 TemplateInstantiation,
7884
7885 /// We are instantiating a default argument for a template
7886 /// parameter. The Entity is the template parameter whose argument is
7887 /// being instantiated, the Template is the template, and the
7888 /// TemplateArgs/NumTemplateArguments provide the template arguments as
7889 /// specified.
7890 DefaultTemplateArgumentInstantiation,
7891
7892 /// We are instantiating a default argument for a function.
7893 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7894 /// provides the template arguments as specified.
7895 DefaultFunctionArgumentInstantiation,
7896
7897 /// We are substituting explicit template arguments provided for
7898 /// a function template. The entity is a FunctionTemplateDecl.
7899 ExplicitTemplateArgumentSubstitution,
7900
7901 /// We are substituting template argument determined as part of
7902 /// template argument deduction for either a class template
7903 /// partial specialization or a function template. The
7904 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7905 /// a TemplateDecl.
7906 DeducedTemplateArgumentSubstitution,
7907
7908 /// We are substituting prior template arguments into a new
7909 /// template parameter. The template parameter itself is either a
7910 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7911 PriorTemplateArgumentSubstitution,
7912
7913 /// We are checking the validity of a default template argument that
7914 /// has been used when naming a template-id.
7915 DefaultTemplateArgumentChecking,
7916
7917 /// We are computing the exception specification for a defaulted special
7918 /// member function.
7919 ExceptionSpecEvaluation,
7920
7921 /// We are instantiating the exception specification for a function
7922 /// template which was deferred until it was needed.
7923 ExceptionSpecInstantiation,
7924
7925 /// We are declaring an implicit special member function.
7926 DeclaringSpecialMember,
7927
7928 /// We are declaring an implicit 'operator==' for a defaulted
7929 /// 'operator<=>'.
7930 DeclaringImplicitEqualityComparison,
7931
7932 /// We are defining a synthesized function (such as a defaulted special
7933 /// member).
7934 DefiningSynthesizedFunction,
7935
7936 // We are checking the constraints associated with a constrained entity or
7937 // the constraint expression of a concept. This includes the checks that
7938 // atomic constraints have the type 'bool' and that they can be constant
7939 // evaluated.
7940 ConstraintsCheck,
7941
7942 // We are substituting template arguments into a constraint expression.
7943 ConstraintSubstitution,
7944
7945 // We are normalizing a constraint expression.
7946 ConstraintNormalization,
7947
7948 // We are substituting into the parameter mapping of an atomic constraint
7949 // during normalization.
7950 ParameterMappingSubstitution,
7951
7952 /// We are rewriting a comparison operator in terms of an operator<=>.
7953 RewritingOperatorAsSpaceship,
7954
7955 /// Added for Template instantiation observation.
7956 /// Memoization means we are _not_ instantiating a template because
7957 /// it is already instantiated (but we entered a context where we
7958 /// would have had to if it was not already instantiated).
7959 Memoization
7960 } Kind;
7961
7962 /// Was the enclosing context a non-instantiation SFINAE context?
7963 bool SavedInNonInstantiationSFINAEContext;
7964
7965 /// The point of instantiation or synthesis within the source code.
7966 SourceLocation PointOfInstantiation;
7967
7968 /// The entity that is being synthesized.
7969 Decl *Entity;
7970
7971 /// The template (or partial specialization) in which we are
7972 /// performing the instantiation, for substitutions of prior template
7973 /// arguments.
7974 NamedDecl *Template;
7975
7976 /// The list of template arguments we are substituting, if they
7977 /// are not part of the entity.
7978 const TemplateArgument *TemplateArgs;
7979
7980 // FIXME: Wrap this union around more members, or perhaps store the
7981 // kind-specific members in the RAII object owning the context.
7982 union {
7983 /// The number of template arguments in TemplateArgs.
7984 unsigned NumTemplateArgs;
7985
7986 /// The special member being declared or defined.
7987 CXXSpecialMember SpecialMember;
7988 };
7989
7990 ArrayRef<TemplateArgument> template_arguments() const {
7991 assert(Kind != DeclaringSpecialMember)((Kind != DeclaringSpecialMember) ? static_cast<void> (
0) : __assert_fail ("Kind != DeclaringSpecialMember", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 7991, __PRETTY_FUNCTION__))
;
7992 return {TemplateArgs, NumTemplateArgs};
7993 }
7994
7995 /// The template deduction info object associated with the
7996 /// substitution or checking of explicit or deduced template arguments.
7997 sema::TemplateDeductionInfo *DeductionInfo;
7998
7999 /// The source range that covers the construct that cause
8000 /// the instantiation, e.g., the template-id that causes a class
8001 /// template instantiation.
8002 SourceRange InstantiationRange;
8003
8004 CodeSynthesisContext()
8005 : Kind(TemplateInstantiation),
8006 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8007 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8008 DeductionInfo(nullptr) {}
8009
8010 /// Determines whether this template is an actual instantiation
8011 /// that should be counted toward the maximum instantiation depth.
8012 bool isInstantiationRecord() const;
8013 };
8014
8015 /// List of active code synthesis contexts.
8016 ///
8017 /// This vector is treated as a stack. As synthesis of one entity requires
8018 /// synthesis of another, additional contexts are pushed onto the stack.
8019 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8020
8021 /// Specializations whose definitions are currently being instantiated.
8022 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8023
8024 /// Non-dependent types used in templates that have already been instantiated
8025 /// by some template instantiation.
8026 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8027
8028 /// Extra modules inspected when performing a lookup during a template
8029 /// instantiation. Computed lazily.
8030 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8031
8032 /// Cache of additional modules that should be used for name lookup
8033 /// within the current template instantiation. Computed lazily; use
8034 /// getLookupModules() to get a complete set.
8035 llvm::DenseSet<Module*> LookupModulesCache;
8036
8037 /// Get the set of additional modules that should be checked during
8038 /// name lookup. A module and its imports become visible when instanting a
8039 /// template defined within it.
8040 llvm::DenseSet<Module*> &getLookupModules();
8041
8042 /// Map from the most recent declaration of a namespace to the most
8043 /// recent visible declaration of that namespace.
8044 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
8045
8046 /// Whether we are in a SFINAE context that is not associated with
8047 /// template instantiation.
8048 ///
8049 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
8050 /// of a template instantiation or template argument deduction.
8051 bool InNonInstantiationSFINAEContext;
8052
8053 /// The number of \p CodeSynthesisContexts that are not template
8054 /// instantiations and, therefore, should not be counted as part of the
8055 /// instantiation depth.
8056 ///
8057 /// When the instantiation depth reaches the user-configurable limit
8058 /// \p LangOptions::InstantiationDepth we will abort instantiation.
8059 // FIXME: Should we have a similar limit for other forms of synthesis?
8060 unsigned NonInstantiationEntries;
8061
8062 /// The depth of the context stack at the point when the most recent
8063 /// error or warning was produced.
8064 ///
8065 /// This value is used to suppress printing of redundant context stacks
8066 /// when there are multiple errors or warnings in the same instantiation.
8067 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
8068 unsigned LastEmittedCodeSynthesisContextDepth = 0;
8069
8070 /// The template instantiation callbacks to trace or track
8071 /// instantiations (objects can be chained).
8072 ///
8073 /// This callbacks is used to print, trace or track template
8074 /// instantiations as they are being constructed.
8075 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
8076 TemplateInstCallbacks;
8077
8078 /// The current index into pack expansion arguments that will be
8079 /// used for substitution of parameter packs.
8080 ///
8081 /// The pack expansion index will be -1 to indicate that parameter packs
8082 /// should be instantiated as themselves. Otherwise, the index specifies
8083 /// which argument within the parameter pack will be used for substitution.
8084 int ArgumentPackSubstitutionIndex;
8085
8086 /// RAII object used to change the argument pack substitution index
8087 /// within a \c Sema object.
8088 ///
8089 /// See \c ArgumentPackSubstitutionIndex for more information.
8090 class ArgumentPackSubstitutionIndexRAII {
8091 Sema &Self;
8092 int OldSubstitutionIndex;
8093
8094 public:
8095 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
8096 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
8097 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
8098 }
8099
8100 ~ArgumentPackSubstitutionIndexRAII() {
8101 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
8102 }
8103 };
8104
8105 friend class ArgumentPackSubstitutionRAII;
8106
8107 /// For each declaration that involved template argument deduction, the
8108 /// set of diagnostics that were suppressed during that template argument
8109 /// deduction.
8110 ///
8111 /// FIXME: Serialize this structure to the AST file.
8112 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
8113 SuppressedDiagnosticsMap;
8114 SuppressedDiagnosticsMap SuppressedDiagnostics;
8115
8116 /// A stack object to be created when performing template
8117 /// instantiation.
8118 ///
8119 /// Construction of an object of type \c InstantiatingTemplate
8120 /// pushes the current instantiation onto the stack of active
8121 /// instantiations. If the size of this stack exceeds the maximum
8122 /// number of recursive template instantiations, construction
8123 /// produces an error and evaluates true.
8124 ///
8125 /// Destruction of this object will pop the named instantiation off
8126 /// the stack.
8127 struct InstantiatingTemplate {
8128 /// Note that we are instantiating a class template,
8129 /// function template, variable template, alias template,
8130 /// or a member thereof.
8131 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8132 Decl *Entity,
8133 SourceRange InstantiationRange = SourceRange());
8134
8135 struct ExceptionSpecification {};
8136 /// Note that we are instantiating an exception specification
8137 /// of a function template.
8138 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8139 FunctionDecl *Entity, ExceptionSpecification,
8140 SourceRange InstantiationRange = SourceRange());
8141
8142 /// Note that we are instantiating a default argument in a
8143 /// template-id.
8144 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8145 TemplateParameter Param, TemplateDecl *Template,
8146 ArrayRef<TemplateArgument> TemplateArgs,
8147 SourceRange InstantiationRange = SourceRange());
8148
8149 /// Note that we are substituting either explicitly-specified or
8150 /// deduced template arguments during function template argument deduction.
8151 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8152 FunctionTemplateDecl *FunctionTemplate,
8153 ArrayRef<TemplateArgument> TemplateArgs,
8154 CodeSynthesisContext::SynthesisKind Kind,
8155 sema::TemplateDeductionInfo &DeductionInfo,
8156 SourceRange InstantiationRange = SourceRange());
8157
8158 /// Note that we are instantiating as part of template
8159 /// argument deduction for a class template declaration.
8160 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8161 TemplateDecl *Template,
8162 ArrayRef<TemplateArgument> TemplateArgs,
8163 sema::TemplateDeductionInfo &DeductionInfo,
8164 SourceRange InstantiationRange = SourceRange());
8165
8166 /// Note that we are instantiating as part of template
8167 /// argument deduction for a class template partial
8168 /// specialization.
8169 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8170 ClassTemplatePartialSpecializationDecl *PartialSpec,
8171 ArrayRef<TemplateArgument> TemplateArgs,
8172 sema::TemplateDeductionInfo &DeductionInfo,
8173 SourceRange InstantiationRange = SourceRange());
8174
8175 /// Note that we are instantiating as part of template
8176 /// argument deduction for a variable template partial
8177 /// specialization.
8178 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8179 VarTemplatePartialSpecializationDecl *PartialSpec,
8180 ArrayRef<TemplateArgument> TemplateArgs,
8181 sema::TemplateDeductionInfo &DeductionInfo,
8182 SourceRange InstantiationRange = SourceRange());
8183
8184 /// Note that we are instantiating a default argument for a function
8185 /// parameter.
8186 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8187 ParmVarDecl *Param,
8188 ArrayRef<TemplateArgument> TemplateArgs,
8189 SourceRange InstantiationRange = SourceRange());
8190
8191 /// Note that we are substituting prior template arguments into a
8192 /// non-type parameter.
8193 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8194 NamedDecl *Template,
8195 NonTypeTemplateParmDecl *Param,
8196 ArrayRef<TemplateArgument> TemplateArgs,
8197 SourceRange InstantiationRange);
8198
8199 /// Note that we are substituting prior template arguments into a
8200 /// template template parameter.
8201 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8202 NamedDecl *Template,
8203 TemplateTemplateParmDecl *Param,
8204 ArrayRef<TemplateArgument> TemplateArgs,
8205 SourceRange InstantiationRange);
8206
8207 /// Note that we are checking the default template argument
8208 /// against the template parameter for a given template-id.
8209 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8210 TemplateDecl *Template,
8211 NamedDecl *Param,
8212 ArrayRef<TemplateArgument> TemplateArgs,
8213 SourceRange InstantiationRange);
8214
8215 struct ConstraintsCheck {};
8216 /// \brief Note that we are checking the constraints associated with some
8217 /// constrained entity (a concept declaration or a template with associated
8218 /// constraints).
8219 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8220 ConstraintsCheck, NamedDecl *Template,
8221 ArrayRef<TemplateArgument> TemplateArgs,
8222 SourceRange InstantiationRange);
8223
8224 struct ConstraintSubstitution {};
8225 /// \brief Note that we are checking a constraint expression associated
8226 /// with a template declaration or as part of the satisfaction check of a
8227 /// concept.
8228 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8229 ConstraintSubstitution, NamedDecl *Template,
8230 sema::TemplateDeductionInfo &DeductionInfo,
8231 SourceRange InstantiationRange);
8232
8233 struct ConstraintNormalization {};
8234 /// \brief Note that we are normalizing a constraint expression.
8235 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8236 ConstraintNormalization, NamedDecl *Template,
8237 SourceRange InstantiationRange);
8238
8239 struct ParameterMappingSubstitution {};
8240 /// \brief Note that we are subtituting into the parameter mapping of an
8241 /// atomic constraint during constraint normalization.
8242 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8243 ParameterMappingSubstitution, NamedDecl *Template,
8244 SourceRange InstantiationRange);
8245
8246 /// Note that we have finished instantiating this template.
8247 void Clear();
8248
8249 ~InstantiatingTemplate() { Clear(); }
8250
8251 /// Determines whether we have exceeded the maximum
8252 /// recursive template instantiations.
8253 bool isInvalid() const { return Invalid; }
8254
8255 /// Determine whether we are already instantiating this
8256 /// specialization in some surrounding active instantiation.
8257 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
8258
8259 private:
8260 Sema &SemaRef;
8261 bool Invalid;
8262 bool AlreadyInstantiating;
8263 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
8264 SourceRange InstantiationRange);
8265
8266 InstantiatingTemplate(
8267 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
8268 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
8269 Decl *Entity, NamedDecl *Template = nullptr,
8270 ArrayRef<TemplateArgument> TemplateArgs = None,
8271 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
8272
8273 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
8274
8275 InstantiatingTemplate&
8276 operator=(const InstantiatingTemplate&) = delete;
8277 };
8278
8279 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
8280 void popCodeSynthesisContext();
8281
8282 /// Determine whether we are currently performing template instantiation.
8283 bool inTemplateInstantiation() const {
8284 return CodeSynthesisContexts.size() > NonInstantiationEntries;
8285 }
8286
8287 void PrintContextStack() {
8288 if (!CodeSynthesisContexts.empty() &&
8289 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
8290 PrintInstantiationStack();
8291 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
8292 }
8293 if (PragmaAttributeCurrentTargetDecl)
8294 PrintPragmaAttributeInstantiationPoint();
8295 }
8296 void PrintInstantiationStack();
8297
8298 void PrintPragmaAttributeInstantiationPoint();
8299
8300 /// Determines whether we are currently in a context where
8301 /// template argument substitution failures are not considered
8302 /// errors.
8303 ///
8304 /// \returns An empty \c Optional if we're not in a SFINAE context.
8305 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
8306 /// template-deduction context object, which can be used to capture
8307 /// diagnostics that will be suppressed.
8308 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
8309
8310 /// Determines whether we are currently in a context that
8311 /// is not evaluated as per C++ [expr] p5.
8312 bool isUnevaluatedContext() const {
8313 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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 8314, __PRETTY_FUNCTION__))
8314 "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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 8314, __PRETTY_FUNCTION__))
;
8315 return ExprEvalContexts.back().isUnevaluated();
8316 }
8317
8318 /// RAII class used to determine whether SFINAE has
8319 /// trapped any errors that occur during template argument
8320 /// deduction.
8321 class SFINAETrap {
8322 Sema &SemaRef;
8323 unsigned PrevSFINAEErrors;
8324 bool PrevInNonInstantiationSFINAEContext;
8325 bool PrevAccessCheckingSFINAE;
8326 bool PrevLastDiagnosticIgnored;
8327
8328 public:
8329 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
8330 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
8331 PrevInNonInstantiationSFINAEContext(
8332 SemaRef.InNonInstantiationSFINAEContext),
8333 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
8334 PrevLastDiagnosticIgnored(
8335 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
8336 {
8337 if (!SemaRef.isSFINAEContext())
8338 SemaRef.InNonInstantiationSFINAEContext = true;
8339 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
8340 }
8341
8342 ~SFINAETrap() {
8343 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
8344 SemaRef.InNonInstantiationSFINAEContext
8345 = PrevInNonInstantiationSFINAEContext;
8346 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
8347 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
8348 PrevLastDiagnosticIgnored);
8349 }
8350
8351 /// Determine whether any SFINAE errors have been trapped.
8352 bool hasErrorOccurred() const {
8353 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
8354 }
8355 };
8356
8357 /// RAII class used to indicate that we are performing provisional
8358 /// semantic analysis to determine the validity of a construct, so
8359 /// typo-correction and diagnostics in the immediate context (not within
8360 /// implicitly-instantiated templates) should be suppressed.
8361 class TentativeAnalysisScope {
8362 Sema &SemaRef;
8363 // FIXME: Using a SFINAETrap for this is a hack.
8364 SFINAETrap Trap;
8365 bool PrevDisableTypoCorrection;
8366 public:
8367 explicit TentativeAnalysisScope(Sema &SemaRef)
8368 : SemaRef(SemaRef), Trap(SemaRef, true),
8369 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
8370 SemaRef.DisableTypoCorrection = true;
8371 }
8372 ~TentativeAnalysisScope() {
8373 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
8374 }
8375 };
8376
8377 /// The current instantiation scope used to store local
8378 /// variables.
8379 LocalInstantiationScope *CurrentInstantiationScope;
8380
8381 /// Tracks whether we are in a context where typo correction is
8382 /// disabled.
8383 bool DisableTypoCorrection;
8384
8385 /// The number of typos corrected by CorrectTypo.
8386 unsigned TyposCorrected;
8387
8388 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
8389 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
8390
8391 /// A cache containing identifiers for which typo correction failed and
8392 /// their locations, so that repeated attempts to correct an identifier in a
8393 /// given location are ignored if typo correction already failed for it.
8394 IdentifierSourceLocations TypoCorrectionFailures;
8395
8396 /// Worker object for performing CFG-based warnings.
8397 sema::AnalysisBasedWarnings AnalysisWarnings;
8398 threadSafety::BeforeSet *ThreadSafetyDeclCache;
8399
8400 /// An entity for which implicit template instantiation is required.
8401 ///
8402 /// The source location associated with the declaration is the first place in
8403 /// the source code where the declaration was "used". It is not necessarily
8404 /// the point of instantiation (which will be either before or after the
8405 /// namespace-scope declaration that triggered this implicit instantiation),
8406 /// However, it is the location that diagnostics should generally refer to,
8407 /// because users will need to know what code triggered the instantiation.
8408 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
8409
8410 /// The queue of implicit template instantiations that are required
8411 /// but have not yet been performed.
8412 std::deque<PendingImplicitInstantiation> PendingInstantiations;
8413
8414 /// Queue of implicit template instantiations that cannot be performed
8415 /// eagerly.
8416 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
8417
8418 class GlobalEagerInstantiationScope {
8419 public:
8420 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
8421 : S(S), Enabled(Enabled) {
8422 if (!Enabled) return;
8423
8424 SavedPendingInstantiations.swap(S.PendingInstantiations);
8425 SavedVTableUses.swap(S.VTableUses);
8426 }
8427
8428 void perform() {
8429 if (Enabled) {
8430 S.DefineUsedVTables();
8431 S.PerformPendingInstantiations();
8432 }
8433 }
8434
8435 ~GlobalEagerInstantiationScope() {
8436 if (!Enabled) return;
8437
8438 // Restore the set of pending vtables.
8439 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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 8440, __PRETTY_FUNCTION__))
8440 "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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 8440, __PRETTY_FUNCTION__))
;
8441 S.VTableUses.swap(SavedVTableUses);
8442
8443 // Restore the set of pending implicit instantiations.
8444 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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 8445, __PRETTY_FUNCTION__))
8445 "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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 8445, __PRETTY_FUNCTION__))
;
8446 S.PendingInstantiations.swap(SavedPendingInstantiations);
8447 }
8448
8449 private:
8450 Sema &S;
8451 SmallVector<VTableUse, 16> SavedVTableUses;
8452 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
8453 bool Enabled;
8454 };
8455
8456 /// The queue of implicit template instantiations that are required
8457 /// and must be performed within the current local scope.
8458 ///
8459 /// This queue is only used for member functions of local classes in
8460 /// templates, which must be instantiated in the same scope as their
8461 /// enclosing function, so that they can reference function-local
8462 /// types, static variables, enumerators, etc.
8463 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
8464
8465 class LocalEagerInstantiationScope {
8466 public:
8467 LocalEagerInstantiationScope(Sema &S) : S(S) {
8468 SavedPendingLocalImplicitInstantiations.swap(
8469 S.PendingLocalImplicitInstantiations);
8470 }
8471
8472 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
8473
8474 ~LocalEagerInstantiationScope() {
8475 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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 8476, __PRETTY_FUNCTION__))
8476 "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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 8476, __PRETTY_FUNCTION__))
;
8477 SavedPendingLocalImplicitInstantiations.swap(
8478 S.PendingLocalImplicitInstantiations);
8479 }
8480
8481 private:
8482 Sema &S;
8483 std::deque<PendingImplicitInstantiation>
8484 SavedPendingLocalImplicitInstantiations;
8485 };
8486
8487 /// A helper class for building up ExtParameterInfos.
8488 class ExtParameterInfoBuilder {
8489 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
8490 bool HasInteresting = false;
8491
8492 public:
8493 /// Set the ExtParameterInfo for the parameter at the given index,
8494 ///
8495 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
8496 assert(Infos.size() <= index)((Infos.size() <= index) ? static_cast<void> (0) : __assert_fail
("Infos.size() <= index", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 8496, __PRETTY_FUNCTION__))
;
8497 Infos.resize(index);
8498 Infos.push_back(info);
8499
8500 if (!HasInteresting)
8501 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
8502 }
8503
8504 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
8505 /// ExtParameterInfo array we've built up.
8506 const FunctionProtoType::ExtParameterInfo *
8507 getPointerOrNull(unsigned numParams) {
8508 if (!HasInteresting) return nullptr;
8509 Infos.resize(numParams);
8510 return Infos.data();
8511 }
8512 };
8513
8514 void PerformPendingInstantiations(bool LocalOnly = false);
8515
8516 TypeSourceInfo *SubstType(TypeSourceInfo *T,
8517 const MultiLevelTemplateArgumentList &TemplateArgs,
8518 SourceLocation Loc, DeclarationName Entity,
8519 bool AllowDeducedTST = false);
8520
8521 QualType SubstType(QualType T,
8522 const MultiLevelTemplateArgumentList &TemplateArgs,
8523 SourceLocation Loc, DeclarationName Entity);
8524
8525 TypeSourceInfo *SubstType(TypeLoc TL,
8526 const MultiLevelTemplateArgumentList &TemplateArgs,
8527 SourceLocation Loc, DeclarationName Entity);
8528
8529 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
8530 const MultiLevelTemplateArgumentList &TemplateArgs,
8531 SourceLocation Loc,
8532 DeclarationName Entity,
8533 CXXRecordDecl *ThisContext,
8534 Qualifiers ThisTypeQuals);
8535 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
8536 const MultiLevelTemplateArgumentList &Args);
8537 bool SubstExceptionSpec(SourceLocation Loc,
8538 FunctionProtoType::ExceptionSpecInfo &ESI,
8539 SmallVectorImpl<QualType> &ExceptionStorage,
8540 const MultiLevelTemplateArgumentList &Args);
8541 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
8542 const MultiLevelTemplateArgumentList &TemplateArgs,
8543 int indexAdjustment,
8544 Optional<unsigned> NumExpansions,
8545 bool ExpectParameterPack);
8546 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
8547 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
8548 const MultiLevelTemplateArgumentList &TemplateArgs,
8549 SmallVectorImpl<QualType> &ParamTypes,
8550 SmallVectorImpl<ParmVarDecl *> *OutParams,
8551 ExtParameterInfoBuilder &ParamInfos);
8552 ExprResult SubstExpr(Expr *E,
8553 const MultiLevelTemplateArgumentList &TemplateArgs);
8554
8555 /// Substitute the given template arguments into a list of
8556 /// expressions, expanding pack expansions if required.
8557 ///
8558 /// \param Exprs The list of expressions to substitute into.
8559 ///
8560 /// \param IsCall Whether this is some form of call, in which case
8561 /// default arguments will be dropped.
8562 ///
8563 /// \param TemplateArgs The set of template arguments to substitute.
8564 ///
8565 /// \param Outputs Will receive all of the substituted arguments.
8566 ///
8567 /// \returns true if an error occurred, false otherwise.
8568 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
8569 const MultiLevelTemplateArgumentList &TemplateArgs,
8570 SmallVectorImpl<Expr *> &Outputs);
8571
8572 StmtResult SubstStmt(Stmt *S,
8573 const MultiLevelTemplateArgumentList &TemplateArgs);
8574
8575 TemplateParameterList *
8576 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
8577 const MultiLevelTemplateArgumentList &TemplateArgs);
8578
8579 bool
8580 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
8581 const MultiLevelTemplateArgumentList &TemplateArgs,
8582 TemplateArgumentListInfo &Outputs);
8583
8584
8585 Decl *SubstDecl(Decl *D, DeclContext *Owner,
8586 const MultiLevelTemplateArgumentList &TemplateArgs);
8587
8588 /// Substitute the name and return type of a defaulted 'operator<=>' to form
8589 /// an implicit 'operator=='.
8590 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
8591 FunctionDecl *Spaceship);
8592
8593 ExprResult SubstInitializer(Expr *E,
8594 const MultiLevelTemplateArgumentList &TemplateArgs,
8595 bool CXXDirectInit);
8596
8597 bool
8598 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
8599 CXXRecordDecl *Pattern,
8600 const MultiLevelTemplateArgumentList &TemplateArgs);
8601
8602 bool
8603 InstantiateClass(SourceLocation PointOfInstantiation,
8604 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
8605 const MultiLevelTemplateArgumentList &TemplateArgs,
8606 TemplateSpecializationKind TSK,
8607 bool Complain = true);
8608
8609 bool InstantiateEnum(SourceLocation PointOfInstantiation,
8610 EnumDecl *Instantiation, EnumDecl *Pattern,
8611 const MultiLevelTemplateArgumentList &TemplateArgs,
8612 TemplateSpecializationKind TSK);
8613
8614 bool InstantiateInClassInitializer(
8615 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
8616 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
8617
8618 struct LateInstantiatedAttribute {
8619 const Attr *TmplAttr;
8620 LocalInstantiationScope *Scope;
8621 Decl *NewDecl;
8622
8623 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
8624 Decl *D)
8625 : TmplAttr(A), Scope(S), NewDecl(D)
8626 { }
8627 };
8628 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
8629
8630 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
8631 const Decl *Pattern, Decl *Inst,
8632 LateInstantiatedAttrVec *LateAttrs = nullptr,
8633 LocalInstantiationScope *OuterMostScope = nullptr);
8634
8635 void
8636 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
8637 const Decl *Pattern, Decl *Inst,
8638 LateInstantiatedAttrVec *LateAttrs = nullptr,
8639 LocalInstantiationScope *OuterMostScope = nullptr);
8640
8641 bool usesPartialOrExplicitSpecialization(
8642 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
8643
8644 bool
8645 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
8646 ClassTemplateSpecializationDecl *ClassTemplateSpec,
8647 TemplateSpecializationKind TSK,
8648 bool Complain = true);
8649
8650 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
8651 CXXRecordDecl *Instantiation,
8652 const MultiLevelTemplateArgumentList &TemplateArgs,
8653 TemplateSpecializationKind TSK);
8654
8655 void InstantiateClassTemplateSpecializationMembers(
8656 SourceLocation PointOfInstantiation,
8657 ClassTemplateSpecializationDecl *ClassTemplateSpec,
8658 TemplateSpecializationKind TSK);
8659
8660 NestedNameSpecifierLoc
8661 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
8662 const MultiLevelTemplateArgumentList &TemplateArgs);
8663
8664 DeclarationNameInfo
8665 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
8666 const MultiLevelTemplateArgumentList &TemplateArgs);
8667 TemplateName
8668 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
8669 SourceLocation Loc,
8670 const MultiLevelTemplateArgumentList &TemplateArgs);
8671 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
8672 TemplateArgumentListInfo &Result,
8673 const MultiLevelTemplateArgumentList &TemplateArgs);
8674
8675 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
8676 FunctionDecl *Function);
8677 bool CheckInstantiatedFunctionTemplateConstraints(
8678 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
8679 ArrayRef<TemplateArgument> TemplateArgs,
8680 ConstraintSatisfaction &Satisfaction);
8681 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
8682 const TemplateArgumentList *Args,
8683 SourceLocation Loc);
8684 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
8685 FunctionDecl *Function,
8686 bool Recursive = false,
8687 bool DefinitionRequired = false,
8688 bool AtEndOfTU = false);
8689 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
8690 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
8691 const TemplateArgumentList &TemplateArgList,
8692 const TemplateArgumentListInfo &TemplateArgsInfo,
8693 SmallVectorImpl<TemplateArgument> &Converted,
8694 SourceLocation PointOfInstantiation, void *InsertPos,
8695 LateInstantiatedAttrVec *LateAttrs = nullptr,
8696 LocalInstantiationScope *StartingScope = nullptr);
8697 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
8698 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
8699 const MultiLevelTemplateArgumentList &TemplateArgs);
8700 void
8701 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
8702 const MultiLevelTemplateArgumentList &TemplateArgs,
8703 LateInstantiatedAttrVec *LateAttrs,
8704 DeclContext *Owner,
8705 LocalInstantiationScope *StartingScope,
8706 bool InstantiatingVarTemplate = false,
8707 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
8708
8709 VarDecl *getVarTemplateSpecialization(
8710 VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
8711 const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
8712
8713 void InstantiateVariableInitializer(
8714 VarDecl *Var, VarDecl *OldVar,
8715 const MultiLevelTemplateArgumentList &TemplateArgs);
8716 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
8717 VarDecl *Var, bool Recursive = false,
8718 bool DefinitionRequired = false,
8719 bool AtEndOfTU = false);
8720
8721 void InstantiateMemInitializers(CXXConstructorDecl *New,
8722 const CXXConstructorDecl *Tmpl,
8723 const MultiLevelTemplateArgumentList &TemplateArgs);
8724
8725 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
8726 const MultiLevelTemplateArgumentList &TemplateArgs,
8727 bool FindingInstantiatedContext = false);
8728 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
8729 const MultiLevelTemplateArgumentList &TemplateArgs);
8730
8731 // Objective-C declarations.
8732 enum ObjCContainerKind {
8733 OCK_None = -1,
8734 OCK_Interface = 0,
8735 OCK_Protocol,
8736 OCK_Category,
8737 OCK_ClassExtension,
8738 OCK_Implementation,
8739 OCK_CategoryImplementation
8740 };
8741 ObjCContainerKind getObjCContainerKind() const;
8742
8743 DeclResult actOnObjCTypeParam(Scope *S,
8744 ObjCTypeParamVariance variance,
8745 SourceLocation varianceLoc,
8746 unsigned index,
8747 IdentifierInfo *paramName,
8748 SourceLocation paramLoc,
8749 SourceLocation colonLoc,
8750 ParsedType typeBound);
8751
8752 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
8753 ArrayRef<Decl *> typeParams,
8754 SourceLocation rAngleLoc);
8755 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
8756
8757 Decl *ActOnStartClassInterface(
8758 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8759 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8760 IdentifierInfo *SuperName, SourceLocation SuperLoc,
8761 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
8762 Decl *const *ProtoRefs, unsigned NumProtoRefs,
8763 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8764 const ParsedAttributesView &AttrList);
8765
8766 void ActOnSuperClassOfClassInterface(Scope *S,
8767 SourceLocation AtInterfaceLoc,
8768 ObjCInterfaceDecl *IDecl,
8769 IdentifierInfo *ClassName,
8770 SourceLocation ClassLoc,
8771 IdentifierInfo *SuperName,
8772 SourceLocation SuperLoc,
8773 ArrayRef<ParsedType> SuperTypeArgs,
8774 SourceRange SuperTypeArgsRange);
8775
8776 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
8777 SmallVectorImpl<SourceLocation> &ProtocolLocs,
8778 IdentifierInfo *SuperName,
8779 SourceLocation SuperLoc);
8780
8781 Decl *ActOnCompatibilityAlias(
8782 SourceLocation AtCompatibilityAliasLoc,
8783 IdentifierInfo *AliasName, SourceLocation AliasLocation,
8784 IdentifierInfo *ClassName, SourceLocation ClassLocation);
8785
8786 bool CheckForwardProtocolDeclarationForCircularDependency(
8787 IdentifierInfo *PName,
8788 SourceLocation &PLoc, SourceLocation PrevLoc,
8789 const ObjCList<ObjCProtocolDecl> &PList);
8790
8791 Decl *ActOnStartProtocolInterface(
8792 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
8793 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
8794 unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
8795 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
8796
8797 Decl *ActOnStartCategoryInterface(
8798 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8799 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8800 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
8801 Decl *const *ProtoRefs, unsigned NumProtoRefs,
8802 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8803 const ParsedAttributesView &AttrList);
8804
8805 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
8806 IdentifierInfo *ClassName,
8807 SourceLocation ClassLoc,
8808 IdentifierInfo *SuperClassname,
8809 SourceLocation SuperClassLoc,
8810 const ParsedAttributesView &AttrList);
8811
8812 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
8813 IdentifierInfo *ClassName,
8814 SourceLocation ClassLoc,
8815 IdentifierInfo *CatName,
8816 SourceLocation CatLoc,
8817 const ParsedAttributesView &AttrList);
8818
8819 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
8820 ArrayRef<Decl *> Decls);
8821
8822 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
8823 IdentifierInfo **IdentList,
8824 SourceLocation *IdentLocs,
8825 ArrayRef<ObjCTypeParamList *> TypeParamLists,
8826 unsigned NumElts);
8827
8828 DeclGroupPtrTy
8829 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
8830 ArrayRef<IdentifierLocPair> IdentList,
8831 const ParsedAttributesView &attrList);
8832
8833 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
8834 ArrayRef<IdentifierLocPair> ProtocolId,
8835 SmallVectorImpl<Decl *> &Protocols);
8836
8837 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
8838 SourceLocation ProtocolLoc,
8839 IdentifierInfo *TypeArgId,
8840 SourceLocation TypeArgLoc,
8841 bool SelectProtocolFirst = false);
8842
8843 /// Given a list of identifiers (and their locations), resolve the
8844 /// names to either Objective-C protocol qualifiers or type
8845 /// arguments, as appropriate.
8846 void actOnObjCTypeArgsOrProtocolQualifiers(
8847 Scope *S,
8848 ParsedType baseType,
8849 SourceLocation lAngleLoc,
8850 ArrayRef<IdentifierInfo *> identifiers,
8851 ArrayRef<SourceLocation> identifierLocs,
8852 SourceLocation rAngleLoc,
8853 SourceLocation &typeArgsLAngleLoc,
8854 SmallVectorImpl<ParsedType> &typeArgs,
8855 SourceLocation &typeArgsRAngleLoc,
8856 SourceLocation &protocolLAngleLoc,
8857 SmallVectorImpl<Decl *> &protocols,
8858 SourceLocation &protocolRAngleLoc,
8859 bool warnOnIncompleteProtocols);
8860
8861 /// Build a an Objective-C protocol-qualified 'id' type where no
8862 /// base type was specified.
8863 TypeResult actOnObjCProtocolQualifierType(
8864 SourceLocation lAngleLoc,
8865 ArrayRef<Decl *> protocols,
8866 ArrayRef<SourceLocation> protocolLocs,
8867 SourceLocation rAngleLoc);
8868
8869 /// Build a specialized and/or protocol-qualified Objective-C type.
8870 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
8871 Scope *S,
8872 SourceLocation Loc,
8873 ParsedType BaseType,
8874 SourceLocation TypeArgsLAngleLoc,
8875 ArrayRef<ParsedType> TypeArgs,
8876 SourceLocation TypeArgsRAngleLoc,
8877 SourceLocation ProtocolLAngleLoc,
8878 ArrayRef<Decl *> Protocols,
8879 ArrayRef<SourceLocation> ProtocolLocs,
8880 SourceLocation ProtocolRAngleLoc);
8881
8882 /// Build an Objective-C type parameter type.
8883 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
8884 SourceLocation ProtocolLAngleLoc,
8885 ArrayRef<ObjCProtocolDecl *> Protocols,
8886 ArrayRef<SourceLocation> ProtocolLocs,
8887 SourceLocation ProtocolRAngleLoc,
8888 bool FailOnError = false);
8889
8890 /// Build an Objective-C object pointer type.
8891 QualType BuildObjCObjectType(QualType BaseType,
8892 SourceLocation Loc,
8893 SourceLocation TypeArgsLAngleLoc,
8894 ArrayRef<TypeSourceInfo *> TypeArgs,
8895 SourceLocation TypeArgsRAngleLoc,
8896 SourceLocation ProtocolLAngleLoc,
8897 ArrayRef<ObjCProtocolDecl *> Protocols,
8898 ArrayRef<SourceLocation> ProtocolLocs,
8899 SourceLocation ProtocolRAngleLoc,
8900 bool FailOnError = false);
8901
8902 /// Ensure attributes are consistent with type.
8903 /// \param [in, out] Attributes The attributes to check; they will
8904 /// be modified to be consistent with \p PropertyTy.
8905 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
8906 SourceLocation Loc,
8907 unsigned &Attributes,
8908 bool propertyInPrimaryClass);
8909
8910 /// Process the specified property declaration and create decls for the
8911 /// setters and getters as needed.
8912 /// \param property The property declaration being processed
8913 void ProcessPropertyDecl(ObjCPropertyDecl *property);
8914
8915
8916 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
8917 ObjCPropertyDecl *SuperProperty,
8918 const IdentifierInfo *Name,
8919 bool OverridingProtocolProperty);
8920
8921 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
8922 ObjCInterfaceDecl *ID);
8923
8924 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
8925 ArrayRef<Decl *> allMethods = None,
8926 ArrayRef<DeclGroupPtrTy> allTUVars = None);
8927
8928 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
8929 SourceLocation LParenLoc,
8930 FieldDeclarator &FD, ObjCDeclSpec &ODS,
8931 Selector GetterSel, Selector SetterSel,
8932 tok::ObjCKeywordKind MethodImplKind,
8933 DeclContext *lexicalDC = nullptr);
8934
8935 Decl *ActOnPropertyImplDecl(Scope *S,
8936 SourceLocation AtLoc,
8937 SourceLocation PropertyLoc,
8938 bool ImplKind,
8939 IdentifierInfo *PropertyId,
8940 IdentifierInfo *PropertyIvar,
8941 SourceLocation PropertyIvarLoc,
8942 ObjCPropertyQueryKind QueryKind);
8943
8944 enum ObjCSpecialMethodKind {
8945 OSMK_None,
8946 OSMK_Alloc,
8947 OSMK_New,
8948 OSMK_Copy,
8949 OSMK_RetainingInit,
8950 OSMK_NonRetainingInit
8951 };
8952
8953 struct ObjCArgInfo {
8954 IdentifierInfo *Name;
8955 SourceLocation NameLoc;
8956 // The Type is null if no type was specified, and the DeclSpec is invalid
8957 // in this case.
8958 ParsedType Type;
8959 ObjCDeclSpec DeclSpec;
8960
8961 /// ArgAttrs - Attribute list for this argument.
8962 ParsedAttributesView ArgAttrs;
8963 };
8964
8965 Decl *ActOnMethodDeclaration(
8966 Scope *S,
8967 SourceLocation BeginLoc, // location of the + or -.
8968 SourceLocation EndLoc, // location of the ; or {.
8969 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
8970 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
8971 // optional arguments. The number of types/arguments is obtained
8972 // from the Sel.getNumArgs().
8973 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
8974 unsigned CNumArgs, // c-style args
8975 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
8976 bool isVariadic, bool MethodDefinition);
8977
8978 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8979 const ObjCObjectPointerType *OPT,
8980 bool IsInstance);
8981 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8982 bool IsInstance);
8983
8984 bool CheckARCMethodDecl(ObjCMethodDecl *method);
8985 bool inferObjCARCLifetime(ValueDecl *decl);
8986
8987 void deduceOpenCLAddressSpace(ValueDecl *decl);
8988
8989 ExprResult
8990 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8991 Expr *BaseExpr,
8992 SourceLocation OpLoc,
8993 DeclarationName MemberName,
8994 SourceLocation MemberLoc,
8995 SourceLocation SuperLoc, QualType SuperType,
8996 bool Super);
8997
8998 ExprResult
8999 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9000 IdentifierInfo &propertyName,
9001 SourceLocation receiverNameLoc,
9002 SourceLocation propertyNameLoc);
9003
9004 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9005
9006 /// Describes the kind of message expression indicated by a message
9007 /// send that starts with an identifier.
9008 enum ObjCMessageKind {
9009 /// The message is sent to 'super'.
9010 ObjCSuperMessage,
9011 /// The message is an instance message.
9012 ObjCInstanceMessage,
9013 /// The message is a class message, and the identifier is a type
9014 /// name.
9015 ObjCClassMessage
9016 };
9017
9018 ObjCMessageKind getObjCMessageKind(Scope *S,
9019 IdentifierInfo *Name,
9020 SourceLocation NameLoc,
9021 bool IsSuper,
9022 bool HasTrailingDot,
9023 ParsedType &ReceiverType);
9024
9025 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
9026 Selector Sel,
9027 SourceLocation LBracLoc,
9028 ArrayRef<SourceLocation> SelectorLocs,
9029 SourceLocation RBracLoc,
9030 MultiExprArg Args);
9031
9032 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
9033 QualType ReceiverType,
9034 SourceLocation SuperLoc,
9035 Selector Sel,
9036 ObjCMethodDecl *Method,
9037 SourceLocation LBracLoc,
9038 ArrayRef<SourceLocation> SelectorLocs,
9039 SourceLocation RBracLoc,
9040 MultiExprArg Args,
9041 bool isImplicit = false);
9042
9043 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
9044 bool isSuperReceiver,
9045 SourceLocation Loc,
9046 Selector Sel,
9047 ObjCMethodDecl *Method,
9048 MultiExprArg Args);
9049
9050 ExprResult ActOnClassMessage(Scope *S,
9051 ParsedType Receiver,
9052 Selector Sel,
9053 SourceLocation LBracLoc,
9054 ArrayRef<SourceLocation> SelectorLocs,
9055 SourceLocation RBracLoc,
9056 MultiExprArg Args);
9057
9058 ExprResult BuildInstanceMessage(Expr *Receiver,
9059 QualType ReceiverType,
9060 SourceLocation SuperLoc,
9061 Selector Sel,
9062 ObjCMethodDecl *Method,
9063 SourceLocation LBracLoc,
9064 ArrayRef<SourceLocation> SelectorLocs,
9065 SourceLocation RBracLoc,
9066 MultiExprArg Args,
9067 bool isImplicit = false);
9068
9069 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
9070 QualType ReceiverType,
9071 SourceLocation Loc,
9072 Selector Sel,
9073 ObjCMethodDecl *Method,
9074 MultiExprArg Args);
9075
9076 ExprResult ActOnInstanceMessage(Scope *S,
9077 Expr *Receiver,
9078 Selector Sel,
9079 SourceLocation LBracLoc,
9080 ArrayRef<SourceLocation> SelectorLocs,
9081 SourceLocation RBracLoc,
9082 MultiExprArg Args);
9083
9084 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
9085 ObjCBridgeCastKind Kind,
9086 SourceLocation BridgeKeywordLoc,
9087 TypeSourceInfo *TSInfo,
9088 Expr *SubExpr);
9089
9090 ExprResult ActOnObjCBridgedCast(Scope *S,
9091 SourceLocation LParenLoc,
9092 ObjCBridgeCastKind Kind,
9093 SourceLocation BridgeKeywordLoc,
9094 ParsedType Type,
9095 SourceLocation RParenLoc,
9096 Expr *SubExpr);
9097
9098 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
9099
9100 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
9101
9102 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
9103 CastKind &Kind);
9104
9105 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
9106 QualType DestType, QualType SrcType,
9107 ObjCInterfaceDecl *&RelatedClass,
9108 ObjCMethodDecl *&ClassMethod,
9109 ObjCMethodDecl *&InstanceMethod,
9110 TypedefNameDecl *&TDNDecl,
9111 bool CfToNs, bool Diagnose = true);
9112
9113 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
9114 QualType DestType, QualType SrcType,
9115 Expr *&SrcExpr, bool Diagnose = true);
9116
9117 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
9118 bool Diagnose = true);
9119
9120 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
9121
9122 /// Check whether the given new method is a valid override of the
9123 /// given overridden method, and set any properties that should be inherited.
9124 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
9125 const ObjCMethodDecl *Overridden);
9126
9127 /// Describes the compatibility of a result type with its method.
9128 enum ResultTypeCompatibilityKind {
9129 RTC_Compatible,
9130 RTC_Incompatible,
9131 RTC_Unknown
9132 };
9133
9134 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
9135 ObjCMethodDecl *overridden);
9136
9137 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
9138 ObjCInterfaceDecl *CurrentClass,
9139 ResultTypeCompatibilityKind RTC);
9140
9141 enum PragmaOptionsAlignKind {
9142 POAK_Native, // #pragma options align=native
9143 POAK_Natural, // #pragma options align=natural
9144 POAK_Packed, // #pragma options align=packed
9145 POAK_Power, // #pragma options align=power
9146 POAK_Mac68k, // #pragma options align=mac68k
9147 POAK_Reset // #pragma options align=reset
9148 };
9149
9150 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
9151 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
9152 PragmaClangSectionAction Action,
9153 PragmaClangSectionKind SecKind, StringRef SecName);
9154
9155 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
9156 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
9157 SourceLocation PragmaLoc);
9158
9159 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
9160 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
9161 StringRef SlotLabel, Expr *Alignment);
9162
9163 enum class PragmaPackDiagnoseKind {
9164 NonDefaultStateAtInclude,
9165 ChangedStateAtExit
9166 };
9167
9168 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
9169 SourceLocation IncludeLoc);
9170 void DiagnoseUnterminatedPragmaPack();
9171
9172 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
9173 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
9174
9175 /// ActOnPragmaMSComment - Called on well formed
9176 /// \#pragma comment(kind, "arg").
9177 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
9178 StringRef Arg);
9179
9180 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
9181 /// pointers_to_members(representation method[, general purpose
9182 /// representation]).
9183 void ActOnPragmaMSPointersToMembers(
9184 LangOptions::PragmaMSPointersToMembersKind Kind,
9185 SourceLocation PragmaLoc);
9186
9187 /// Called on well formed \#pragma vtordisp().
9188 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
9189 SourceLocation PragmaLoc,
9190 MSVtorDispMode Value);
9191
9192 enum PragmaSectionKind {
9193 PSK_DataSeg,
9194 PSK_BSSSeg,
9195 PSK_ConstSeg,
9196 PSK_CodeSeg,
9197 };
9198
9199 bool UnifySection(StringRef SectionName,
9200 int SectionFlags,
9201 DeclaratorDecl *TheDecl);
9202 bool UnifySection(StringRef SectionName,
9203 int SectionFlags,
9204 SourceLocation PragmaSectionLocation);
9205
9206 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
9207 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
9208 PragmaMsStackAction Action,
9209 llvm::StringRef StackSlotLabel,
9210 StringLiteral *SegmentName,
9211 llvm::StringRef PragmaName);
9212
9213 /// Called on well formed \#pragma section().
9214 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
9215 int SectionFlags, StringLiteral *SegmentName);
9216
9217 /// Called on well-formed \#pragma init_seg().
9218 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
9219 StringLiteral *SegmentName);
9220
9221 /// Called on #pragma clang __debug dump II
9222 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9223
9224 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
9225 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
9226 StringRef Value);
9227
9228 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
9229 void ActOnPragmaUnused(const Token &Identifier,
9230 Scope *curScope,
9231 SourceLocation PragmaLoc);
9232
9233 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
9234 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
9235 SourceLocation PragmaLoc);
9236
9237 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
9238 SourceLocation Loc);
9239 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
9240
9241 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
9242 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
9243 SourceLocation PragmaLoc,
9244 SourceLocation WeakNameLoc);
9245
9246 /// ActOnPragmaRedefineExtname - Called on well formed
9247 /// \#pragma redefine_extname oldname newname.
9248 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
9249 IdentifierInfo* AliasName,
9250 SourceLocation PragmaLoc,
9251 SourceLocation WeakNameLoc,
9252 SourceLocation AliasNameLoc);
9253
9254 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
9255 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
9256 IdentifierInfo* AliasName,
9257 SourceLocation PragmaLoc,
9258 SourceLocation WeakNameLoc,
9259 SourceLocation AliasNameLoc);
9260
9261 /// ActOnPragmaFPContract - Called on well formed
9262 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
9263 /// \#pragma clang fp contract
9264 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
9265
9266 /// ActOnPragmaFenvAccess - Called on well formed
9267 /// \#pragma STDC FENV_ACCESS
9268 void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC);
9269
9270 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
9271 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
9272 void AddAlignmentAttributesForRecord(RecordDecl *RD);
9273
9274 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
9275 void AddMsStructLayoutForRecord(RecordDecl *RD);
9276
9277 /// FreePackedContext - Deallocate and null out PackContext.
9278 void FreePackedContext();
9279
9280 /// PushNamespaceVisibilityAttr - Note that we've entered a
9281 /// namespace with a visibility attribute.
9282 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
9283 SourceLocation Loc);
9284
9285 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
9286 /// add an appropriate visibility attribute.
9287 void AddPushedVisibilityAttribute(Decl *RD);
9288
9289 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
9290 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
9291 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
9292
9293 /// FreeVisContext - Deallocate and null out VisContext.
9294 void FreeVisContext();
9295
9296 /// AddCFAuditedAttribute - Check whether we're currently within
9297 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
9298 /// the appropriate attribute.
9299 void AddCFAuditedAttribute(Decl *D);
9300
9301 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
9302 SourceLocation PragmaLoc,
9303 attr::ParsedSubjectMatchRuleSet Rules);
9304 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
9305 const IdentifierInfo *Namespace);
9306
9307 /// Called on well-formed '\#pragma clang attribute pop'.
9308 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
9309 const IdentifierInfo *Namespace);
9310
9311 /// Adds the attributes that have been specified using the
9312 /// '\#pragma clang attribute push' directives to the given declaration.
9313 void AddPragmaAttributes(Scope *S, Decl *D);
9314
9315 void DiagnoseUnterminatedPragmaAttribute();
9316
9317 /// Called on well formed \#pragma clang optimize.
9318 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
9319
9320 /// Get the location for the currently active "\#pragma clang optimize
9321 /// off". If this location is invalid, then the state of the pragma is "on".
9322 SourceLocation getOptimizeOffPragmaLocation() const {
9323 return OptimizeOffPragmaLocation;
9324 }
9325
9326 /// Only called on function definitions; if there is a pragma in scope
9327 /// with the effect of a range-based optnone, consider marking the function
9328 /// with attribute optnone.
9329 void AddRangeBasedOptnone(FunctionDecl *FD);
9330
9331 /// Adds the 'optnone' attribute to the function declaration if there
9332 /// are no conflicts; Loc represents the location causing the 'optnone'
9333 /// attribute to be added (usually because of a pragma).
9334 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
9335
9336 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
9337 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9338 bool IsPackExpansion);
9339 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
9340 bool IsPackExpansion);
9341
9342 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
9343 /// declaration.
9344 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9345 Expr *OE);
9346
9347 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
9348 /// declaration.
9349 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
9350 Expr *ParamExpr);
9351
9352 /// AddAlignValueAttr - Adds an align_value attribute to a particular
9353 /// declaration.
9354 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
9355
9356 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
9357 /// declaration.
9358 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
9359 Expr *MaxThreads, Expr *MinBlocks);
9360
9361 /// AddModeAttr - Adds a mode attribute to a particular declaration.
9362 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
9363 bool InInstantiation = false);
9364
9365 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
9366 ParameterABI ABI);
9367
9368 enum class RetainOwnershipKind {NS, CF, OS};
9369 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
9370 RetainOwnershipKind K, bool IsTemplateInstantiation);
9371
9372 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
9373 /// attribute to a particular declaration.
9374 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
9375 Expr *Min, Expr *Max);
9376
9377 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
9378 /// particular declaration.
9379 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
9380 Expr *Min, Expr *Max);
9381
9382 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
9383
9384 //===--------------------------------------------------------------------===//
9385 // C++ Coroutines TS
9386 //
9387 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
9388 StringRef Keyword);
9389 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9390 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9391 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
9392
9393 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9394 bool IsImplicit = false);
9395 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9396 UnresolvedLookupExpr* Lookup);
9397 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
9398 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
9399 bool IsImplicit = false);
9400 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
9401 bool buildCoroutineParameterMoves(SourceLocation Loc);
9402 VarDecl *buildCoroutinePromise(SourceLocation Loc);
9403 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
9404 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
9405 SourceLocation FuncLoc);
9406
9407 //===--------------------------------------------------------------------===//
9408 // OpenCL extensions.
9409 //
9410private:
9411 std::string CurrOpenCLExtension;
9412 /// Extensions required by an OpenCL type.
9413 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
9414 /// Extensions required by an OpenCL declaration.
9415 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
9416public:
9417 llvm::StringRef getCurrentOpenCLExtension() const {
9418 return CurrOpenCLExtension;
9419 }
9420
9421 /// Check if a function declaration \p FD associates with any
9422 /// extensions present in OpenCLDeclExtMap and if so return the
9423 /// extension(s) name(s).
9424 std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
9425
9426 /// Check if a function type \p FT associates with any
9427 /// extensions present in OpenCLTypeExtMap and if so return the
9428 /// extension(s) name(s).
9429 std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
9430
9431 /// Find an extension in an appropriate extension map and return its name
9432 template<typename T, typename MapT>
9433 std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
9434
9435 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
9436 CurrOpenCLExtension = Ext;
9437 }
9438
9439 /// Set OpenCL extensions for a type which can only be used when these
9440 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
9441 /// \param Exts A space separated list of OpenCL extensions.
9442 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
9443
9444 /// Set OpenCL extensions for a declaration which can only be
9445 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
9446 /// nothing.
9447 /// \param Exts A space separated list of OpenCL extensions.
9448 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
9449
9450 /// Set current OpenCL extensions for a type which can only be used
9451 /// when these OpenCL extensions are enabled. If current OpenCL extension is
9452 /// empty, do nothing.
9453 void setCurrentOpenCLExtensionForType(QualType T);
9454
9455 /// Set current OpenCL extensions for a declaration which
9456 /// can only be used when these OpenCL extensions are enabled. If current
9457 /// OpenCL extension is empty, do nothing.
9458 void setCurrentOpenCLExtensionForDecl(Decl *FD);
9459
9460 bool isOpenCLDisabledDecl(Decl *FD);
9461
9462 /// Check if type \p T corresponding to declaration specifier \p DS
9463 /// is disabled due to required OpenCL extensions being disabled. If so,
9464 /// emit diagnostics.
9465 /// \return true if type is disabled.
9466 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
9467
9468 /// Check if declaration \p D used by expression \p E
9469 /// is disabled due to required OpenCL extensions being disabled. If so,
9470 /// emit diagnostics.
9471 /// \return true if type is disabled.
9472 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
9473
9474 //===--------------------------------------------------------------------===//
9475 // OpenMP directives and clauses.
9476 //
9477private:
9478 void *VarDataSharingAttributesStack;
9479 /// Number of nested '#pragma omp declare target' directives.
9480 unsigned DeclareTargetNestingLevel = 0;
9481 /// Initialization of data-sharing attributes stack.
9482 void InitDataSharingAttributesStack();
9483 void DestroyDataSharingAttributesStack();
9484 ExprResult
9485 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
9486 bool StrictlyPositive = true);
9487 /// Returns OpenMP nesting level for current directive.
9488 unsigned getOpenMPNestingLevel() const;
9489
9490 /// Adjusts the function scopes index for the target-based regions.
9491 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
9492 unsigned Level) const;
9493
9494 /// Returns the number of scopes associated with the construct on the given
9495 /// OpenMP level.
9496 int getNumberOfConstructScopes(unsigned Level) const;
9497
9498 /// Push new OpenMP function region for non-capturing function.
9499 void pushOpenMPFunctionRegion();
9500
9501 /// Pop OpenMP function region for non-capturing function.
9502 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
9503
9504 /// Check whether we're allowed to call Callee from the current function.
9505 void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
9506 bool CheckForDelayedContext = true);
9507
9508 /// Check whether we're allowed to call Callee from the current function.
9509 void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
9510 bool CheckCaller = true);
9511
9512 /// Check if the expression is allowed to be used in expressions for the
9513 /// OpenMP devices.
9514 void checkOpenMPDeviceExpr(const Expr *E);
9515
9516 /// Finishes analysis of the deferred functions calls that may be declared as
9517 /// host/nohost during device/host compilation.
9518 void finalizeOpenMPDelayedAnalysis();
9519
9520 /// Checks if a type or a declaration is disabled due to the owning extension
9521 /// being disabled, and emits diagnostic messages if it is disabled.
9522 /// \param D type or declaration to be checked.
9523 /// \param DiagLoc source location for the diagnostic message.
9524 /// \param DiagInfo information to be emitted for the diagnostic message.
9525 /// \param SrcRange source range of the declaration.
9526 /// \param Map maps type or declaration to the extensions.
9527 /// \param Selector selects diagnostic message: 0 for type and 1 for
9528 /// declaration.
9529 /// \return true if the type or declaration is disabled.
9530 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
9531 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
9532 MapT &Map, unsigned Selector = 0,
9533 SourceRange SrcRange = SourceRange());
9534
9535 /// Marks all the functions that might be required for the currently active
9536 /// OpenMP context.
9537 void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
9538 FunctionDecl *Func,
9539 bool MightBeOdrUse);
9540
9541public:
9542 /// Struct to store the context selectors info for declare variant directive.
9543 using OMPCtxStringType = SmallString<8>;
9544 using OMPCtxSelectorData =
9545 OpenMPCtxSelectorData<SmallVector<OMPCtxStringType, 4>, ExprResult>;
9546
9547 /// Checks if the variant/multiversion functions are compatible.
9548 bool areMultiversionVariantFunctionsCompatible(
9549 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9550 const PartialDiagnostic &NoProtoDiagID,
9551 const PartialDiagnosticAt &NoteCausedDiagIDAt,
9552 const PartialDiagnosticAt &NoSupportDiagIDAt,
9553 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9554 bool ConstexprSupported, bool CLinkageMayDiffer);
9555
9556 /// Function tries to capture lambda's captured variables in the OpenMP region
9557 /// before the original lambda is captured.
9558 void tryCaptureOpenMPLambdas(ValueDecl *V);
9559
9560 /// Return true if the provided declaration \a VD should be captured by
9561 /// reference.
9562 /// \param Level Relative level of nested OpenMP construct for that the check
9563 /// is performed.
9564 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
9565 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
9566 unsigned OpenMPCaptureLevel) const;
9567
9568 /// Check if the specified variable is used in one of the private
9569 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
9570 /// constructs.
9571 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
9572 unsigned StopAt = 0);
9573 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9574 ExprObjectKind OK, SourceLocation Loc);
9575
9576 /// If the current region is a loop-based region, mark the start of the loop
9577 /// construct.
9578 void startOpenMPLoop();
9579
9580 /// If the current region is a range loop-based region, mark the start of the
9581 /// loop construct.
9582 void startOpenMPCXXRangeFor();
9583
9584 /// Check if the specified variable is used in 'private' clause.
9585 /// \param Level Relative level of nested OpenMP construct for that the check
9586 /// is performed.
9587 bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
9588
9589 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
9590 /// for \p FD based on DSA for the provided corresponding captured declaration
9591 /// \p D.
9592 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
9593
9594 /// Check if the specified variable is captured by 'target' directive.
9595 /// \param Level Relative level of nested OpenMP construct for that the check
9596 /// is performed.
9597 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
9598
9599 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
9600 Expr *Op);
9601 /// Called on start of new data sharing attribute block.
9602 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
9603 const DeclarationNameInfo &DirName, Scope *CurScope,
9604 SourceLocation Loc);
9605 /// Start analysis of clauses.
9606 void StartOpenMPClause(OpenMPClauseKind K);
9607 /// End analysis of clauses.
9608 void EndOpenMPClause();
9609 /// Called on end of data sharing attribute block.
9610 void EndOpenMPDSABlock(Stmt *CurDirective);
9611
9612 /// Check if the current region is an OpenMP loop region and if it is,
9613 /// mark loop control variable, used in \p Init for loop initialization, as
9614 /// private by default.
9615 /// \param Init First part of the for loop.
9616 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
9617
9618 // OpenMP directives and clauses.
9619 /// Called on correct id-expression from the '#pragma omp
9620 /// threadprivate'.
9621 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
9622 const DeclarationNameInfo &Id,
9623 OpenMPDirectiveKind Kind);
9624 /// Called on well-formed '#pragma omp threadprivate'.
9625 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
9626 SourceLocation Loc,
9627 ArrayRef<Expr *> VarList);
9628 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
9629 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
9630 ArrayRef<Expr *> VarList);
9631 /// Called on well-formed '#pragma omp allocate'.
9632 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
9633 ArrayRef<Expr *> VarList,
9634 ArrayRef<OMPClause *> Clauses,
9635 DeclContext *Owner = nullptr);
9636 /// Called on well-formed '#pragma omp requires'.
9637 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
9638 ArrayRef<OMPClause *> ClauseList);
9639 /// Check restrictions on Requires directive
9640 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
9641 ArrayRef<OMPClause *> Clauses);
9642 /// Check if the specified type is allowed to be used in 'omp declare
9643 /// reduction' construct.
9644 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
9645 TypeResult ParsedType);
9646 /// Called on start of '#pragma omp declare reduction'.
9647 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
9648 Scope *S, DeclContext *DC, DeclarationName Name,
9649 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
9650 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
9651 /// Initialize declare reduction construct initializer.
9652 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
9653 /// Finish current declare reduction construct initializer.
9654 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
9655 /// Initialize declare reduction construct initializer.
9656 /// \return omp_priv variable.
9657 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
9658 /// Finish current declare reduction construct initializer.
9659 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
9660 VarDecl *OmpPrivParm);
9661 /// Called at the end of '#pragma omp declare reduction'.
9662 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
9663 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
9664
9665 /// Check variable declaration in 'omp declare mapper' construct.
9666 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
9667 /// Check if the specified type is allowed to be used in 'omp declare
9668 /// mapper' construct.
9669 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
9670 TypeResult ParsedType);
9671 /// Called on start of '#pragma omp declare mapper'.
9672 OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
9673 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
9674 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
9675 Decl *PrevDeclInScope = nullptr);
9676 /// Build the mapper variable of '#pragma omp declare mapper'.
9677 void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
9678 Scope *S, QualType MapperType,
9679 SourceLocation StartLoc,
9680 DeclarationName VN);
9681 /// Called at the end of '#pragma omp declare mapper'.
9682 DeclGroupPtrTy
9683 ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
9684 ArrayRef<OMPClause *> ClauseList);
9685
9686 /// Called on the start of target region i.e. '#pragma omp declare target'.
9687 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
9688 /// Called at the end of target region i.e. '#pragme omp end declare target'.
9689 void ActOnFinishOpenMPDeclareTargetDirective();
9690 /// Searches for the provided declaration name for OpenMP declare target
9691 /// directive.
9692 NamedDecl *
9693 lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
9694 const DeclarationNameInfo &Id,
9695 NamedDeclSetType &SameDirectiveDecls);
9696 /// Called on correct id-expression from the '#pragma omp declare target'.
9697 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
9698 OMPDeclareTargetDeclAttr::MapTypeTy MT,
9699 OMPDeclareTargetDeclAttr::DevTypeTy DT);
9700 /// Check declaration inside target region.
9701 void
9702 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
9703 SourceLocation IdLoc = SourceLocation());
9704 /// Return true inside OpenMP declare target region.
9705 bool isInOpenMPDeclareTargetContext() const {
9706 return DeclareTargetNestingLevel > 0;
9707 }
9708 /// Return true inside OpenMP target region.
9709 bool isInOpenMPTargetExecutionDirective() const;
9710
9711 /// Return the number of captured regions created for an OpenMP directive.
9712 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
9713
9714 /// Initialization of captured region for OpenMP region.
9715 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
9716 /// End of OpenMP region.
9717 ///
9718 /// \param S Statement associated with the current OpenMP region.
9719 /// \param Clauses List of clauses for the current OpenMP region.
9720 ///
9721 /// \returns Statement for finished OpenMP region.
9722 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
9723 StmtResult ActOnOpenMPExecutableDirective(
9724 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
9725 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
9726 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
9727 /// Called on well-formed '\#pragma omp parallel' after parsing
9728 /// of the associated statement.
9729 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
9730 Stmt *AStmt,
9731 SourceLocation StartLoc,
9732 SourceLocation EndLoc);
9733 using VarsWithInheritedDSAType =
9734 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
9735 /// Called on well-formed '\#pragma omp simd' after parsing
9736 /// of the associated statement.
9737 StmtResult
9738 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9739 SourceLocation StartLoc, SourceLocation EndLoc,
9740 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9741 /// Called on well-formed '\#pragma omp for' after parsing
9742 /// of the associated statement.
9743 StmtResult
9744 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9745 SourceLocation StartLoc, SourceLocation EndLoc,
9746 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9747 /// Called on well-formed '\#pragma omp for simd' after parsing
9748 /// of the associated statement.
9749 StmtResult
9750 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9751 SourceLocation StartLoc, SourceLocation EndLoc,
9752 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9753 /// Called on well-formed '\#pragma omp sections' after parsing
9754 /// of the associated statement.
9755 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9756 Stmt *AStmt, SourceLocation StartLoc,
9757 SourceLocation EndLoc);
9758 /// Called on well-formed '\#pragma omp section' after parsing of the
9759 /// associated statement.
9760 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
9761 SourceLocation EndLoc);
9762 /// Called on well-formed '\#pragma omp single' after parsing of the
9763 /// associated statement.
9764 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9765 Stmt *AStmt, SourceLocation StartLoc,
9766 SourceLocation EndLoc);
9767 /// Called on well-formed '\#pragma omp master' after parsing of the
9768 /// associated statement.
9769 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
9770 SourceLocation EndLoc);
9771 /// Called on well-formed '\#pragma omp critical' after parsing of the
9772 /// associated statement.
9773 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
9774 ArrayRef<OMPClause *> Clauses,
9775 Stmt *AStmt, SourceLocation StartLoc,
9776 SourceLocation EndLoc);
9777 /// Called on well-formed '\#pragma omp parallel for' after parsing
9778 /// of the associated statement.
9779 StmtResult ActOnOpenMPParallelForDirective(
9780 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9781 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9782 /// Called on well-formed '\#pragma omp parallel for simd' after
9783 /// parsing of the associated statement.
9784 StmtResult ActOnOpenMPParallelForSimdDirective(
9785 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9786 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9787 /// Called on well-formed '\#pragma omp parallel master' after
9788 /// parsing of the associated statement.
9789 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
9790 Stmt *AStmt,
9791 SourceLocation StartLoc,
9792 SourceLocation EndLoc);
9793 /// Called on well-formed '\#pragma omp parallel sections' after
9794 /// parsing of the associated statement.
9795 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
9796 Stmt *AStmt,
9797 SourceLocation StartLoc,
9798 SourceLocation EndLoc);
9799 /// Called on well-formed '\#pragma omp task' after parsing of the
9800 /// associated statement.
9801 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
9802 Stmt *AStmt, SourceLocation StartLoc,
9803 SourceLocation EndLoc);
9804 /// Called on well-formed '\#pragma omp taskyield'.
9805 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
9806 SourceLocation EndLoc);
9807 /// Called on well-formed '\#pragma omp barrier'.
9808 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
9809 SourceLocation EndLoc);
9810 /// Called on well-formed '\#pragma omp taskwait'.
9811 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
9812 SourceLocation EndLoc);
9813 /// Called on well-formed '\#pragma omp taskgroup'.
9814 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
9815 Stmt *AStmt, SourceLocation StartLoc,
9816 SourceLocation EndLoc);
9817 /// Called on well-formed '\#pragma omp flush'.
9818 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
9819 SourceLocation StartLoc,
9820 SourceLocation EndLoc);
9821 /// Called on well-formed '\#pragma omp ordered' after parsing of the
9822 /// associated statement.
9823 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
9824 Stmt *AStmt, SourceLocation StartLoc,
9825 SourceLocation EndLoc);
9826 /// Called on well-formed '\#pragma omp atomic' after parsing of the
9827 /// associated statement.
9828 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
9829 Stmt *AStmt, SourceLocation StartLoc,
9830 SourceLocation EndLoc);
9831 /// Called on well-formed '\#pragma omp target' after parsing of the
9832 /// associated statement.
9833 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9834 Stmt *AStmt, SourceLocation StartLoc,
9835 SourceLocation EndLoc);
9836 /// Called on well-formed '\#pragma omp target data' after parsing of
9837 /// the associated statement.
9838 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9839 Stmt *AStmt, SourceLocation StartLoc,
9840 SourceLocation EndLoc);
9841 /// Called on well-formed '\#pragma omp target enter data' after
9842 /// parsing of the associated statement.
9843 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9844 SourceLocation StartLoc,
9845 SourceLocation EndLoc,
9846 Stmt *AStmt);
9847 /// Called on well-formed '\#pragma omp target exit data' after
9848 /// parsing of the associated statement.
9849 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9850 SourceLocation StartLoc,
9851 SourceLocation EndLoc,
9852 Stmt *AStmt);
9853 /// Called on well-formed '\#pragma omp target parallel' after
9854 /// parsing of the associated statement.
9855 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9856 Stmt *AStmt,
9857 SourceLocation StartLoc,
9858 SourceLocation EndLoc);
9859 /// Called on well-formed '\#pragma omp target parallel for' after
9860 /// parsing of the associated statement.
9861 StmtResult ActOnOpenMPTargetParallelForDirective(
9862 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9863 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9864 /// Called on well-formed '\#pragma omp teams' after parsing of the
9865 /// associated statement.
9866 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9867 Stmt *AStmt, SourceLocation StartLoc,
9868 SourceLocation EndLoc);
9869 /// Called on well-formed '\#pragma omp cancellation point'.
9870 StmtResult
9871 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9872 SourceLocation EndLoc,
9873 OpenMPDirectiveKind CancelRegion);
9874 /// Called on well-formed '\#pragma omp cancel'.
9875 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9876 SourceLocation StartLoc,
9877 SourceLocation EndLoc,
9878 OpenMPDirectiveKind CancelRegion);
9879 /// Called on well-formed '\#pragma omp taskloop' after parsing of the
9880 /// associated statement.
9881 StmtResult
9882 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9883 SourceLocation StartLoc, SourceLocation EndLoc,
9884 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9885 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
9886 /// the associated statement.
9887 StmtResult ActOnOpenMPTaskLoopSimdDirective(
9888 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9889 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9890 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
9891 /// associated statement.
9892 StmtResult ActOnOpenMPMasterTaskLoopDirective(
9893 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9894 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9895 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
9896 /// the associated statement.
9897 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
9898 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9899 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9900 /// Called on well-formed '\#pragma omp parallel master taskloop' after
9901 /// parsing of the associated statement.
9902 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
9903 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9904 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9905 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
9906 /// parsing of the associated statement.
9907 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9908 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9909 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9910 /// Called on well-formed '\#pragma omp distribute' after parsing
9911 /// of the associated statement.
9912 StmtResult
9913 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9914 SourceLocation StartLoc, SourceLocation EndLoc,
9915 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9916 /// Called on well-formed '\#pragma omp target update'.
9917 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9918 SourceLocation StartLoc,
9919 SourceLocation EndLoc,
9920 Stmt *AStmt);
9921 /// Called on well-formed '\#pragma omp distribute parallel for' after
9922 /// parsing of the associated statement.
9923 StmtResult ActOnOpenMPDistributeParallelForDirective(
9924 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9925 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9926 /// Called on well-formed '\#pragma omp distribute parallel for simd'
9927 /// after parsing of the associated statement.
9928 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
9929 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9930 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9931 /// Called on well-formed '\#pragma omp distribute simd' after
9932 /// parsing of the associated statement.
9933 StmtResult ActOnOpenMPDistributeSimdDirective(
9934 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9935 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9936 /// Called on well-formed '\#pragma omp target parallel for simd' after
9937 /// parsing of the associated statement.
9938 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
9939 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9940 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9941 /// Called on well-formed '\#pragma omp target simd' after parsing of
9942 /// the associated statement.
9943 StmtResult
9944 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9945 SourceLocation StartLoc, SourceLocation EndLoc,
9946 VarsWithInheritedDSAType &VarsWithImplicitDSA);
9947 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
9948 /// the associated statement.
9949 StmtResult ActOnOpenMPTeamsDistributeDirective(
9950 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9951 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9952 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
9953 /// of the associated statement.
9954 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
9955 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9956 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9957 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
9958 /// after parsing of the associated statement.
9959 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
9960 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9961 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9962 /// Called on well-formed '\#pragma omp teams distribute parallel for'
9963 /// after parsing of the associated statement.
9964 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
9965 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9966 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9967 /// Called on well-formed '\#pragma omp target teams' after parsing of the
9968 /// associated statement.
9969 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
9970 Stmt *AStmt,
9971 SourceLocation StartLoc,
9972 SourceLocation EndLoc);
9973 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
9974 /// of the associated statement.
9975 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
9976 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9977 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9978 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
9979 /// after parsing of the associated statement.
9980 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
9981 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9982 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9983 /// Called on well-formed '\#pragma omp target teams distribute parallel for
9984 /// simd' after parsing of the associated statement.
9985 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
9986 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9987 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9988 /// Called on well-formed '\#pragma omp target teams distribute simd' after
9989 /// parsing of the associated statement.
9990 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
9991 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9992 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9993
9994 /// Checks correctness of linear modifiers.
9995 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9996 SourceLocation LinLoc);
9997 /// Checks that the specified declaration matches requirements for the linear
9998 /// decls.
9999 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
10000 OpenMPLinearClauseKind LinKind, QualType Type);
10001
10002 /// Called on well-formed '\#pragma omp declare simd' after parsing of
10003 /// the associated method/function.
10004 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
10005 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
10006 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
10007 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
10008 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
10009
10010 /// Checks '\#pragma omp declare variant' variant function and original
10011 /// functions after parsing of the associated method/function.
10012 /// \param DG Function declaration to which declare variant directive is
10013 /// applied to.
10014 /// \param VariantRef Expression that references the variant function, which
10015 /// must be used instead of the original one, specified in \p DG.
10016 /// \returns None, if the function/variant function are not compatible with
10017 /// the pragma, pair of original function/variant ref expression otherwise.
10018 Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(
10019 DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR);
10020
10021 /// Called on well-formed '\#pragma omp declare variant' after parsing of
10022 /// the associated method/function.
10023 /// \param FD Function declaration to which declare variant directive is
10024 /// applied to.
10025 /// \param VariantRef Expression that references the variant function, which
10026 /// must be used instead of the original one, specified in \p DG.
10027 /// \param Data Set of context-specific data for the specified context
10028 /// selector.
10029 void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
10030 SourceRange SR,
10031 ArrayRef<OMPCtxSelectorData> Data);
10032
10033 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
10034 Expr *Expr,
10035 SourceLocation StartLoc,
10036 SourceLocation LParenLoc,
10037 SourceLocation EndLoc);
10038 /// Called on well-formed 'allocator' clause.
10039 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
10040 SourceLocation StartLoc,
10041 SourceLocation LParenLoc,
10042 SourceLocation EndLoc);
10043 /// Called on well-formed 'if' clause.
10044 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10045 Expr *Condition, SourceLocation StartLoc,
10046 SourceLocation LParenLoc,
10047 SourceLocation NameModifierLoc,
10048 SourceLocation ColonLoc,
10049 SourceLocation EndLoc);
10050 /// Called on well-formed 'final' clause.
10051 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
10052 SourceLocation LParenLoc,
10053 SourceLocation EndLoc);
10054 /// Called on well-formed 'num_threads' clause.
10055 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
10056 SourceLocation StartLoc,
10057 SourceLocation LParenLoc,
10058 SourceLocation EndLoc);
10059 /// Called on well-formed 'safelen' clause.
10060 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
10061 SourceLocation StartLoc,
10062 SourceLocation LParenLoc,
10063 SourceLocation EndLoc);
10064 /// Called on well-formed 'simdlen' clause.
10065 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
10066 SourceLocation LParenLoc,
10067 SourceLocation EndLoc);
10068 /// Called on well-formed 'collapse' clause.
10069 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
10070 SourceLocation StartLoc,
10071 SourceLocation LParenLoc,
10072 SourceLocation EndLoc);
10073 /// Called on well-formed 'ordered' clause.
10074 OMPClause *
10075 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
10076 SourceLocation LParenLoc = SourceLocation(),
10077 Expr *NumForLoops = nullptr);
10078 /// Called on well-formed 'grainsize' clause.
10079 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
10080 SourceLocation LParenLoc,
10081 SourceLocation EndLoc);
10082 /// Called on well-formed 'num_tasks' clause.
10083 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
10084 SourceLocation LParenLoc,
10085 SourceLocation EndLoc);
10086 /// Called on well-formed 'hint' clause.
10087 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10088 SourceLocation LParenLoc,
10089 SourceLocation EndLoc);
10090
10091 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
10092 unsigned Argument,
10093 SourceLocation ArgumentLoc,
10094 SourceLocation StartLoc,
10095 SourceLocation LParenLoc,
10096 SourceLocation EndLoc);
10097 /// Called on well-formed 'default' clause.
10098 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
10099 SourceLocation KindLoc,
10100 SourceLocation StartLoc,
10101 SourceLocation LParenLoc,
10102 SourceLocation EndLoc);
10103 /// Called on well-formed 'proc_bind' clause.
10104 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
10105 SourceLocation KindLoc,
10106 SourceLocation StartLoc,
10107 SourceLocation LParenLoc,
10108 SourceLocation EndLoc);
10109
10110 OMPClause *ActOnOpenMPSingleExprWithArgClause(
10111 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
10112 SourceLocation StartLoc, SourceLocation LParenLoc,
10113 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
10114 SourceLocation EndLoc);
10115 /// Called on well-formed 'schedule' clause.
10116 OMPClause *ActOnOpenMPScheduleClause(
10117 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
10118 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10119 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10120 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
10121
10122 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
10123 SourceLocation EndLoc);
10124 /// Called on well-formed 'nowait' clause.
10125 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10126 SourceLocation EndLoc);
10127 /// Called on well-formed 'untied' clause.
10128 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10129 SourceLocation EndLoc);
10130 /// Called on well-formed 'mergeable' clause.
10131 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10132 SourceLocation EndLoc);
10133 /// Called on well-formed 'read' clause.
10134 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
10135 SourceLocation EndLoc);
10136 /// Called on well-formed 'write' clause.
10137 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
10138 SourceLocation EndLoc);
10139 /// Called on well-formed 'update' clause.
10140 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10141 SourceLocation EndLoc);
10142 /// Called on well-formed 'capture' clause.
10143 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10144 SourceLocation EndLoc);
10145 /// Called on well-formed 'seq_cst' clause.
10146 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10147 SourceLocation EndLoc);
10148 /// Called on well-formed 'threads' clause.
10149 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10150 SourceLocation EndLoc);
10151 /// Called on well-formed 'simd' clause.
10152 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10153 SourceLocation EndLoc);
10154 /// Called on well-formed 'nogroup' clause.
10155 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10156 SourceLocation EndLoc);
10157 /// Called on well-formed 'unified_address' clause.
10158 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10159 SourceLocation EndLoc);
10160
10161 /// Called on well-formed 'unified_address' clause.
10162 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10163 SourceLocation EndLoc);
10164
10165 /// Called on well-formed 'reverse_offload' clause.
10166 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10167 SourceLocation EndLoc);
10168
10169 /// Called on well-formed 'dynamic_allocators' clause.
10170 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10171 SourceLocation EndLoc);
10172
10173 /// Called on well-formed 'atomic_default_mem_order' clause.
10174 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
10175 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
10176 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10177
10178 OMPClause *ActOnOpenMPVarListClause(
10179 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
10180 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10181 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10182 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
10183 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10184 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
10185 SourceLocation DepLinMapLastLoc);
10186 /// Called on well-formed 'allocate' clause.
10187 OMPClause *
10188 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
10189 SourceLocation StartLoc, SourceLocation ColonLoc,
10190 SourceLocation LParenLoc, SourceLocation EndLoc);
10191 /// Called on well-formed 'private' clause.
10192 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10193 SourceLocation StartLoc,
10194 SourceLocation LParenLoc,
10195 SourceLocation EndLoc);
10196 /// Called on well-formed 'firstprivate' clause.
10197 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10198 SourceLocation StartLoc,
10199 SourceLocation LParenLoc,
10200 SourceLocation EndLoc);
10201 /// Called on well-formed 'lastprivate' clause.
10202 OMPClause *ActOnOpenMPLastprivateClause(
10203 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
10204 SourceLocation LPKindLoc, SourceLocation ColonLoc,
10205 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10206 /// Called on well-formed 'shared' clause.
10207 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10208 SourceLocation StartLoc,
10209 SourceLocation LParenLoc,
10210 SourceLocation EndLoc);
10211 /// Called on well-formed 'reduction' clause.
10212 OMPClause *ActOnOpenMPReductionClause(
10213 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10214 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10215 CXXScopeSpec &ReductionIdScopeSpec,
10216 const DeclarationNameInfo &ReductionId,
10217 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10218 /// Called on well-formed 'task_reduction' clause.
10219 OMPClause *ActOnOpenMPTaskReductionClause(
10220 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10221 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10222 CXXScopeSpec &ReductionIdScopeSpec,
10223 const DeclarationNameInfo &ReductionId,
10224 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10225 /// Called on well-formed 'in_reduction' clause.
10226 OMPClause *ActOnOpenMPInReductionClause(
10227 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10228 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10229 CXXScopeSpec &ReductionIdScopeSpec,
10230 const DeclarationNameInfo &ReductionId,
10231 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10232 /// Called on well-formed 'linear' clause.
10233 OMPClause *
10234 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
10235 SourceLocation StartLoc, SourceLocation LParenLoc,
10236 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
10237 SourceLocation ColonLoc, SourceLocation EndLoc);
10238 /// Called on well-formed 'aligned' clause.
10239 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
10240 Expr *Alignment,
10241 SourceLocation StartLoc,
10242 SourceLocation LParenLoc,
10243 SourceLocation ColonLoc,
10244 SourceLocation EndLoc);
10245 /// Called on well-formed 'copyin' clause.
10246 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10247 SourceLocation StartLoc,
10248 SourceLocation LParenLoc,
10249 SourceLocation EndLoc);
10250 /// Called on well-formed 'copyprivate' clause.
10251 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10252 SourceLocation StartLoc,
10253 SourceLocation LParenLoc,
10254 SourceLocation EndLoc);
10255 /// Called on well-formed 'flush' pseudo clause.
10256 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10257 SourceLocation StartLoc,
10258 SourceLocation LParenLoc,
10259 SourceLocation EndLoc);
10260 /// Called on well-formed 'depend' clause.
10261 OMPClause *
10262 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
10263 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
10264 SourceLocation StartLoc, SourceLocation LParenLoc,
10265 SourceLocation EndLoc);
10266 /// Called on well-formed 'device' clause.
10267 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10268 SourceLocation LParenLoc,
10269 SourceLocation EndLoc);
10270 /// Called on well-formed 'map' clause.
10271 OMPClause *
10272 ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10273 ArrayRef<SourceLocation> MapTypeModifiersLoc,
10274 CXXScopeSpec &MapperIdScopeSpec,
10275 DeclarationNameInfo &MapperId,
10276 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10277 SourceLocation MapLoc, SourceLocation ColonLoc,
10278 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
10279 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10280 /// Called on well-formed 'num_teams' clause.
10281 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
10282 SourceLocation LParenLoc,
10283 SourceLocation EndLoc);
10284 /// Called on well-formed 'thread_limit' clause.
10285 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10286 SourceLocation StartLoc,
10287 SourceLocation LParenLoc,
10288 SourceLocation EndLoc);
10289 /// Called on well-formed 'priority' clause.
10290 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
10291 SourceLocation LParenLoc,
10292 SourceLocation EndLoc);
10293 /// Called on well-formed 'dist_schedule' clause.
10294 OMPClause *ActOnOpenMPDistScheduleClause(
10295 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
10296 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
10297 SourceLocation CommaLoc, SourceLocation EndLoc);
10298 /// Called on well-formed 'defaultmap' clause.
10299 OMPClause *ActOnOpenMPDefaultmapClause(
10300 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10301 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10302 SourceLocation KindLoc, SourceLocation EndLoc);
10303 /// Called on well-formed 'to' clause.
10304 OMPClause *
10305 ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
10306 DeclarationNameInfo &MapperId,
10307 const OMPVarListLocTy &Locs,
10308 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10309 /// Called on well-formed 'from' clause.
10310 OMPClause *ActOnOpenMPFromClause(
10311 ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
10312 DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
10313 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10314 /// Called on well-formed 'use_device_ptr' clause.
10315 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10316 const OMPVarListLocTy &Locs);
10317 /// Called on well-formed 'is_device_ptr' clause.
10318 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10319 const OMPVarListLocTy &Locs);
10320 /// Called on well-formed 'nontemporal' clause.
10321 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
10322 SourceLocation StartLoc,
10323 SourceLocation LParenLoc,
10324 SourceLocation EndLoc);
10325
10326 /// The kind of conversion being performed.
10327 enum CheckedConversionKind {
10328 /// An implicit conversion.
10329 CCK_ImplicitConversion,
10330 /// A C-style cast.
10331 CCK_CStyleCast,
10332 /// A functional-style cast.
10333 CCK_FunctionalCast,
10334 /// A cast other than a C-style cast.
10335 CCK_OtherCast,
10336 /// A conversion for an operand of a builtin overloaded operator.
10337 CCK_ForBuiltinOverloadedOp
10338 };
10339
10340 static bool isCast(CheckedConversionKind CCK) {
10341 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
10342 CCK == CCK_OtherCast;
10343 }
10344
10345 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
10346 /// cast. If there is already an implicit cast, merge into the existing one.
10347 /// If isLvalue, the result of the cast is an lvalue.
10348 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
10349 ExprValueKind VK = VK_RValue,
10350 const CXXCastPath *BasePath = nullptr,
10351 CheckedConversionKind CCK
10352 = CCK_ImplicitConversion);
10353
10354 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
10355 /// to the conversion from scalar type ScalarTy to the Boolean type.
10356 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
10357
10358 /// IgnoredValueConversions - Given that an expression's result is
10359 /// syntactically ignored, perform any conversions that are
10360 /// required.
10361 ExprResult IgnoredValueConversions(Expr *E);
10362
10363 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
10364 // functions and arrays to their respective pointers (C99 6.3.2.1).
10365 ExprResult UsualUnaryConversions(Expr *E);
10366
10367 /// CallExprUnaryConversions - a special case of an unary conversion
10368 /// performed on a function designator of a call expression.
10369 ExprResult CallExprUnaryConversions(Expr *E);
10370
10371 // DefaultFunctionArrayConversion - converts functions and arrays
10372 // to their respective pointers (C99 6.3.2.1).
10373 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
10374
10375 // DefaultFunctionArrayLvalueConversion - converts functions and
10376 // arrays to their respective pointers and performs the
10377 // lvalue-to-rvalue conversion.
10378 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
10379 bool Diagnose = true);
10380
10381 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
10382 // the operand. This is DefaultFunctionArrayLvalueConversion,
10383 // except that it assumes the operand isn't of function or array
10384 // type.
10385 ExprResult DefaultLvalueConversion(Expr *E);
10386
10387 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
10388 // do not have a prototype. Integer promotions are performed on each
10389 // argument, and arguments that have type float are promoted to double.
10390 ExprResult DefaultArgumentPromotion(Expr *E);
10391
10392 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
10393 /// it as an xvalue. In C++98, the result will still be a prvalue, because
10394 /// we don't have xvalues there.
10395 ExprResult TemporaryMaterializationConversion(Expr *E);
10396
10397 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
10398 enum VariadicCallType {
10399 VariadicFunction,
10400 VariadicBlock,
10401 VariadicMethod,
10402 VariadicConstructor,
10403 VariadicDoesNotApply
10404 };
10405
10406 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
10407 const FunctionProtoType *Proto,
10408 Expr *Fn);
10409
10410 // Used for determining in which context a type is allowed to be passed to a
10411 // vararg function.
10412 enum VarArgKind {
10413 VAK_Valid,
10414 VAK_ValidInCXX11,
10415 VAK_Undefined,
10416 VAK_MSVCUndefined,
10417 VAK_Invalid
10418 };
10419
10420 // Determines which VarArgKind fits an expression.
10421 VarArgKind isValidVarArgType(const QualType &Ty);
10422
10423 /// Check to see if the given expression is a valid argument to a variadic
10424 /// function, issuing a diagnostic if not.
10425 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
10426
10427 /// Check to see if a given expression could have '.c_str()' called on it.
10428 bool hasCStrMethod(const Expr *E);
10429
10430 /// GatherArgumentsForCall - Collector argument expressions for various
10431 /// form of call prototypes.
10432 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
10433 const FunctionProtoType *Proto,
10434 unsigned FirstParam, ArrayRef<Expr *> Args,
10435 SmallVectorImpl<Expr *> &AllArgs,
10436 VariadicCallType CallType = VariadicDoesNotApply,
10437 bool AllowExplicit = false,
10438 bool IsListInitialization = false);
10439
10440 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
10441 // will create a runtime trap if the resulting type is not a POD type.
10442 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
10443 FunctionDecl *FDecl);
10444
10445 /// Context in which we're performing a usual arithmetic conversion.
10446 enum ArithConvKind {
10447 /// An arithmetic operation.
10448 ACK_Arithmetic,
10449 /// A bitwise operation.
10450 ACK_BitwiseOp,
10451 /// A comparison.
10452 ACK_Comparison,
10453 /// A conditional (?:) operator.
10454 ACK_Conditional,
10455 /// A compound assignment expression.
10456 ACK_CompAssign,
10457 };
10458
10459 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
10460 // operands and then handles various conversions that are common to binary
10461 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
10462 // routine returns the first non-arithmetic type found. The client is
10463 // responsible for emitting appropriate error diagnostics.
10464 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
10465 SourceLocation Loc, ArithConvKind ACK);
10466
10467 /// AssignConvertType - All of the 'assignment' semantic checks return this
10468 /// enum to indicate whether the assignment was allowed. These checks are
10469 /// done for simple assignments, as well as initialization, return from
10470 /// function, argument passing, etc. The query is phrased in terms of a
10471 /// source and destination type.
10472 enum AssignConvertType {
10473 /// Compatible - the types are compatible according to the standard.
10474 Compatible,
10475
10476 /// PointerToInt - The assignment converts a pointer to an int, which we
10477 /// accept as an extension.
10478 PointerToInt,
10479
10480 /// IntToPointer - The assignment converts an int to a pointer, which we
10481 /// accept as an extension.
10482 IntToPointer,
10483
10484 /// FunctionVoidPointer - The assignment is between a function pointer and
10485 /// void*, which the standard doesn't allow, but we accept as an extension.
10486 FunctionVoidPointer,
10487
10488 /// IncompatiblePointer - The assignment is between two pointers types that
10489 /// are not compatible, but we accept them as an extension.
10490 IncompatiblePointer,
10491
10492 /// IncompatiblePointerSign - The assignment is between two pointers types
10493 /// which point to integers which have a different sign, but are otherwise
10494 /// identical. This is a subset of the above, but broken out because it's by
10495 /// far the most common case of incompatible pointers.
10496 IncompatiblePointerSign,
10497
10498 /// CompatiblePointerDiscardsQualifiers - The assignment discards
10499 /// c/v/r qualifiers, which we accept as an extension.
10500 CompatiblePointerDiscardsQualifiers,
10501
10502 /// IncompatiblePointerDiscardsQualifiers - The assignment
10503 /// discards qualifiers that we don't permit to be discarded,
10504 /// like address spaces.
10505 IncompatiblePointerDiscardsQualifiers,
10506
10507 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
10508 /// changes address spaces in nested pointer types which is not allowed.
10509 /// For instance, converting __private int ** to __generic int ** is
10510 /// illegal even though __private could be converted to __generic.
10511 IncompatibleNestedPointerAddressSpaceMismatch,
10512
10513 /// IncompatibleNestedPointerQualifiers - The assignment is between two
10514 /// nested pointer types, and the qualifiers other than the first two
10515 /// levels differ e.g. char ** -> const char **, but we accept them as an
10516 /// extension.
10517 IncompatibleNestedPointerQualifiers,
10518
10519 /// IncompatibleVectors - The assignment is between two vector types that
10520 /// have the same size, which we accept as an extension.
10521 IncompatibleVectors,
10522
10523 /// IntToBlockPointer - The assignment converts an int to a block
10524 /// pointer. We disallow this.
10525 IntToBlockPointer,
10526
10527 /// IncompatibleBlockPointer - The assignment is between two block
10528 /// pointers types that are not compatible.
10529 IncompatibleBlockPointer,
10530
10531 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
10532 /// id type and something else (that is incompatible with it). For example,
10533 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
10534 IncompatibleObjCQualifiedId,
10535
10536 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
10537 /// object with __weak qualifier.
10538 IncompatibleObjCWeakRef,
10539
10540 /// Incompatible - We reject this conversion outright, it is invalid to
10541 /// represent it in the AST.
10542 Incompatible
10543 };
10544
10545 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
10546 /// assignment conversion type specified by ConvTy. This returns true if the
10547 /// conversion was invalid or false if the conversion was accepted.
10548 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
10549 SourceLocation Loc,
10550 QualType DstType, QualType SrcType,
10551 Expr *SrcExpr, AssignmentAction Action,
10552 bool *Complained = nullptr);
10553
10554 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
10555 /// enum. If AllowMask is true, then we also allow the complement of a valid
10556 /// value, to be used as a mask.
10557 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
10558 bool AllowMask) const;
10559
10560 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
10561 /// integer not in the range of enum values.
10562 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
10563 Expr *SrcExpr);
10564
10565 /// CheckAssignmentConstraints - Perform type checking for assignment,
10566 /// argument passing, variable initialization, and function return values.
10567 /// C99 6.5.16.
10568 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
10569 QualType LHSType,
10570 QualType RHSType);
10571
10572 /// Check assignment constraints and optionally prepare for a conversion of
10573 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
10574 /// is true.
10575 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
10576 ExprResult &RHS,
10577 CastKind &Kind,
10578 bool ConvertRHS = true);
10579
10580 /// Check assignment constraints for an assignment of RHS to LHSType.
10581 ///
10582 /// \param LHSType The destination type for the assignment.
10583 /// \param RHS The source expression for the assignment.
10584 /// \param Diagnose If \c true, diagnostics may be produced when checking
10585 /// for assignability. If a diagnostic is produced, \p RHS will be
10586 /// set to ExprError(). Note that this function may still return
10587 /// without producing a diagnostic, even for an invalid assignment.
10588 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
10589 /// in an audited Core Foundation API and does not need to be checked
10590 /// for ARC retain issues.
10591 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
10592 /// conversions necessary to perform the assignment. If \c false,
10593 /// \p Diagnose must also be \c false.
10594 AssignConvertType CheckSingleAssignmentConstraints(
10595 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
10596 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
10597
10598 // If the lhs type is a transparent union, check whether we
10599 // can initialize the transparent union with the given expression.
10600 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
10601 ExprResult &RHS);
10602
10603 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
10604
10605 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
10606
10607 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10608 AssignmentAction Action,
10609 bool AllowExplicit = false);
10610 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10611 AssignmentAction Action,
10612 bool AllowExplicit,
10613 ImplicitConversionSequence& ICS);
10614 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10615 const ImplicitConversionSequence& ICS,
10616 AssignmentAction Action,
10617 CheckedConversionKind CCK
10618 = CCK_ImplicitConversion);
10619 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10620 const StandardConversionSequence& SCS,
10621 AssignmentAction Action,
10622 CheckedConversionKind CCK);
10623
10624 ExprResult PerformQualificationConversion(
10625 Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
10626 CheckedConversionKind CCK = CCK_ImplicitConversion);
10627
10628 /// the following "Check" methods will return a valid/converted QualType
10629 /// or a null QualType (indicating an error diagnostic was issued).
10630
10631 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
10632 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10633 ExprResult &RHS);
10634 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10635 ExprResult &RHS);
10636 QualType CheckPointerToMemberOperands( // C++ 5.5
10637 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
10638 SourceLocation OpLoc, bool isIndirect);
10639 QualType CheckMultiplyDivideOperands( // C99 6.5.5
10640 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
10641 bool IsDivide);
10642 QualType CheckRemainderOperands( // C99 6.5.5
10643 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10644 bool IsCompAssign = false);
10645 QualType CheckAdditionOperands( // C99 6.5.6
10646 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10647 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
10648 QualType CheckSubtractionOperands( // C99 6.5.6
10649 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10650 QualType* CompLHSTy = nullptr);
10651 QualType CheckShiftOperands( // C99 6.5.7
10652 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10653 BinaryOperatorKind Opc, bool IsCompAssign = false);
10654 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
10655 QualType CheckCompareOperands( // C99 6.5.8/9
10656 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10657 BinaryOperatorKind Opc);
10658 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
10659 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10660 BinaryOperatorKind Opc);
10661 QualType CheckLogicalOperands( // C99 6.5.[13,14]
10662 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10663 BinaryOperatorKind Opc);
10664 // CheckAssignmentOperands is used for both simple and compound assignment.
10665 // For simple assignment, pass both expressions and a null converted type.
10666 // For compound assignment, pass both expressions and the converted type.
10667 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
10668 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
10669
10670 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
10671 UnaryOperatorKind Opcode, Expr *Op);
10672 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
10673 BinaryOperatorKind Opcode,
10674 Expr *LHS, Expr *RHS);
10675 ExprResult checkPseudoObjectRValue(Expr *E);
10676 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
10677
10678 QualType CheckConditionalOperands( // C99 6.5.15
10679 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
10680 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
10681 QualType CXXCheckConditionalOperands( // C++ 5.16
10682 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
10683 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
10684 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
10685 bool ConvertArgs = true);
10686 QualType FindCompositePointerType(SourceLocation Loc,
10687 ExprResult &E1, ExprResult &E2,
10688 bool ConvertArgs = true) {
10689 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
10690 QualType Composite =
10691 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
10692 E1 = E1Tmp;
10693 E2 = E2Tmp;
10694 return Composite;
10695 }
10696
10697 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
10698 SourceLocation QuestionLoc);
10699
10700 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
10701 SourceLocation QuestionLoc);
10702
10703 void DiagnoseAlwaysNonNullPointer(Expr *E,
10704 Expr::NullPointerConstantKind NullType,
10705 bool IsEqual, SourceRange Range);
10706
10707 /// type checking for vector binary operators.
10708 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10709 SourceLocation Loc, bool IsCompAssign,
10710 bool AllowBothBool, bool AllowBoolConversion);
10711 QualType GetSignedVectorType(QualType V);
10712 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10713 SourceLocation Loc,
10714 BinaryOperatorKind Opc);
10715 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10716 SourceLocation Loc);
10717
10718 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
10719 bool isLaxVectorConversion(QualType srcType, QualType destType);
10720
10721 /// type checking declaration initializers (C99 6.7.8)
10722 bool CheckForConstantInitializer(Expr *e, QualType t);
10723
10724 // type checking C++ declaration initializers (C++ [dcl.init]).
10725
10726 /// ReferenceCompareResult - Expresses the result of comparing two
10727 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10728 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10729 enum ReferenceCompareResult {
10730 /// Ref_Incompatible - The two types are incompatible, so direct
10731 /// reference binding is not possible.
10732 Ref_Incompatible = 0,
10733 /// Ref_Related - The two types are reference-related, which means
10734 /// that their unqualified forms (T1 and T2) are either the same
10735 /// or T1 is a base class of T2.
10736 Ref_Related,
10737 /// Ref_Compatible - The two types are reference-compatible.
10738 Ref_Compatible
10739 };
10740
10741 // Fake up a scoped enumeration that still contextually converts to bool.
10742 struct ReferenceConversionsScope {
10743 /// The conversions that would be performed on an lvalue of type T2 when
10744 /// binding a reference of type T1 to it, as determined when evaluating
10745 /// whether T1 is reference-compatible with T2.
10746 enum ReferenceConversions {
10747 Qualification = 0x1,
10748 NestedQualification = 0x2,
10749 Function = 0x4,
10750 DerivedToBase = 0x8,
10751 ObjC = 0x10,
10752 ObjCLifetime = 0x20,
10753
10754 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)LLVM_BITMASK_LARGEST_ENUMERATOR = ObjCLifetime
10755 };
10756 };
10757 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10758
10759 ReferenceCompareResult
10760 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10761 ReferenceConversions *Conv = nullptr);
10762
10763 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10764 Expr *CastExpr, CastKind &CastKind,
10765 ExprValueKind &VK, CXXCastPath &Path);
10766
10767 /// Force an expression with unknown-type to an expression of the
10768 /// given type.
10769 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
10770
10771 /// Type-check an expression that's being passed to an
10772 /// __unknown_anytype parameter.
10773 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
10774 Expr *result, QualType &paramType);
10775
10776 // CheckVectorCast - check type constraints for vectors.
10777 // Since vectors are an extension, there are no C standard reference for this.
10778 // We allow casting between vectors and integer datatypes of the same size.
10779 // returns true if the cast is invalid
10780 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
10781 CastKind &Kind);
10782
10783 /// Prepare `SplattedExpr` for a vector splat operation, adding
10784 /// implicit casts if necessary.
10785 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
10786
10787 // CheckExtVectorCast - check type constraints for extended vectors.
10788 // Since vectors are an extension, there are no C standard reference for this.
10789 // We allow casting between vectors and integer datatypes of the same size,
10790 // or vectors and the element type of that vector.
10791 // returns the cast expr
10792 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
10793 CastKind &Kind);
10794
10795 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
10796 SourceLocation LParenLoc,
10797 Expr *CastExpr,
10798 SourceLocation RParenLoc);
10799
10800 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
10801
10802 /// Checks for invalid conversions and casts between
10803 /// retainable pointers and other pointer kinds for ARC and Weak.
10804 ARCConversionResult CheckObjCConversion(SourceRange castRange,
10805 QualType castType, Expr *&op,
10806 CheckedConversionKind CCK,
10807 bool Diagnose = true,
10808 bool DiagnoseCFAudited = false,
10809 BinaryOperatorKind Opc = BO_PtrMemD
10810 );
10811
10812 Expr *stripARCUnbridgedCast(Expr *e);
10813 void diagnoseARCUnbridgedCast(Expr *e);
10814
10815 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
10816 QualType ExprType);
10817
10818 /// checkRetainCycles - Check whether an Objective-C message send
10819 /// might create an obvious retain cycle.
10820 void checkRetainCycles(ObjCMessageExpr *msg);
10821 void checkRetainCycles(Expr *receiver, Expr *argument);
10822 void checkRetainCycles(VarDecl *Var, Expr *Init);
10823
10824 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
10825 /// to weak/__unsafe_unretained type.
10826 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
10827
10828 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
10829 /// to weak/__unsafe_unretained expression.
10830 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
10831
10832 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
10833 /// \param Method - May be null.
10834 /// \param [out] ReturnType - The return type of the send.
10835 /// \return true iff there were any incompatible types.
10836 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
10837 MultiExprArg Args, Selector Sel,
10838 ArrayRef<SourceLocation> SelectorLocs,
10839 ObjCMethodDecl *Method, bool isClassMessage,
10840 bool isSuperMessage, SourceLocation lbrac,
10841 SourceLocation rbrac, SourceRange RecRange,
10842 QualType &ReturnType, ExprValueKind &VK);
10843
10844 /// Determine the result of a message send expression based on
10845 /// the type of the receiver, the method expected to receive the message,
10846 /// and the form of the message send.
10847 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
10848 ObjCMethodDecl *Method, bool isClassMessage,
10849 bool isSuperMessage);
10850
10851 /// If the given expression involves a message send to a method
10852 /// with a related result type, emit a note describing what happened.
10853 void EmitRelatedResultTypeNote(const Expr *E);
10854
10855 /// Given that we had incompatible pointer types in a return
10856 /// statement, check whether we're in a method with a related result
10857 /// type, and if so, emit a note describing what happened.
10858 void EmitRelatedResultTypeNoteForReturn(QualType destType);
10859
10860 class ConditionResult {
10861 Decl *ConditionVar;
10862 FullExprArg Condition;
10863 bool Invalid;
10864 bool HasKnownValue;
10865 bool KnownValue;
10866
10867 friend class Sema;
10868 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
10869 bool IsConstexpr)
10870 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
10871 HasKnownValue(IsConstexpr && Condition.get() &&
10872 !Condition.get()->isValueDependent()),
10873 KnownValue(HasKnownValue &&
10874 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
10875 explicit ConditionResult(bool Invalid)
10876 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
10877 HasKnownValue(false), KnownValue(false) {}
10878
10879 public:
10880 ConditionResult() : ConditionResult(false) {}
10881 bool isInvalid() const { return Invalid; }
10882 std::pair<VarDecl *, Expr *> get() const {
10883 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
10884 Condition.get());
10885 }
10886 llvm::Optional<bool> getKnownValue() const {
10887 if (!HasKnownValue)
10888 return None;
10889 return KnownValue;
10890 }
10891 };
10892 static ConditionResult ConditionError() { return ConditionResult(true); }
10893
10894 enum class ConditionKind {
10895 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
10896 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
10897 Switch ///< An integral condition for a 'switch' statement.
10898 };
10899
10900 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
10901 Expr *SubExpr, ConditionKind CK);
10902
10903 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
10904 SourceLocation StmtLoc,
10905 ConditionKind CK);
10906
10907 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
10908
10909 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
10910 SourceLocation StmtLoc,
10911 ConditionKind CK);
10912 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
10913
10914 /// CheckBooleanCondition - Diagnose problems involving the use of
10915 /// the given expression as a boolean condition (e.g. in an if
10916 /// statement). Also performs the standard function and array
10917 /// decays, possibly changing the input variable.
10918 ///
10919 /// \param Loc - A location associated with the condition, e.g. the
10920 /// 'if' keyword.
10921 /// \return true iff there were any errors
10922 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
10923 bool IsConstexpr = false);
10924
10925 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
10926 /// found in an explicit(bool) specifier.
10927 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
10928
10929 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
10930 /// Returns true if the explicit specifier is now resolved.
10931 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
10932
10933 /// DiagnoseAssignmentAsCondition - Given that an expression is
10934 /// being used as a boolean condition, warn if it's an assignment.
10935 void DiagnoseAssignmentAsCondition(Expr *E);
10936
10937 /// Redundant parentheses over an equality comparison can indicate
10938 /// that the user intended an assignment used as condition.
10939 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
10940
10941 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
10942 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
10943
10944 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
10945 /// the specified width and sign. If an overflow occurs, detect it and emit
10946 /// the specified diagnostic.
10947 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
10948 unsigned NewWidth, bool NewSign,
10949 SourceLocation Loc, unsigned DiagID);
10950
10951 /// Checks that the Objective-C declaration is declared in the global scope.
10952 /// Emits an error and marks the declaration as invalid if it's not declared
10953 /// in the global scope.
10954 bool CheckObjCDeclScope(Decl *D);
10955
10956 /// Abstract base class used for diagnosing integer constant
10957 /// expression violations.
10958 class VerifyICEDiagnoser {
10959 public:
10960 bool Suppress;
10961
10962 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
10963
10964 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
10965 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
10966 virtual ~VerifyICEDiagnoser() { }
10967 };
10968
10969 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
10970 /// and reports the appropriate diagnostics. Returns false on success.
10971 /// Can optionally return the value of the expression.
10972 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10973 VerifyICEDiagnoser &Diagnoser,
10974 bool AllowFold = true);
10975 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10976 unsigned DiagID,
10977 bool AllowFold = true);
10978 ExprResult VerifyIntegerConstantExpression(Expr *E,
10979 llvm::APSInt *Result = nullptr);
10980
10981 /// VerifyBitField - verifies that a bit field expression is an ICE and has
10982 /// the correct width, and that the field type is valid.
10983 /// Returns false on success.
10984 /// Can optionally return whether the bit-field is of width 0
10985 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
10986 QualType FieldTy, bool IsMsStruct,
10987 Expr *BitWidth, bool *ZeroWidth = nullptr);
10988
10989private:
10990 unsigned ForceCUDAHostDeviceDepth = 0;
10991
10992public:
10993 /// Increments our count of the number of times we've seen a pragma forcing
10994 /// functions to be __host__ __device__. So long as this count is greater
10995 /// than zero, all functions encountered will be __host__ __device__.
10996 void PushForceCUDAHostDevice();
10997
10998 /// Decrements our count of the number of times we've seen a pragma forcing
10999 /// functions to be __host__ __device__. Returns false if the count is 0
11000 /// before incrementing, so you can emit an error.
11001 bool PopForceCUDAHostDevice();
11002
11003 /// Diagnostics that are emitted only if we discover that the given function
11004 /// must be codegen'ed. Because handling these correctly adds overhead to
11005 /// compilation, this is currently only enabled for CUDA compilations.
11006 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
11007 std::vector<PartialDiagnosticAt>>
11008 DeviceDeferredDiags;
11009
11010 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
11011 /// key in a hashtable, both the FD and location are hashed.
11012 struct FunctionDeclAndLoc {
11013 CanonicalDeclPtr<FunctionDecl> FD;
11014 SourceLocation Loc;
11015 };
11016
11017 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
11018 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
11019 /// same deferred diag twice.
11020 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
11021
11022 /// An inverse call graph, mapping known-emitted functions to one of their
11023 /// known-emitted callers (plus the location of the call).
11024 ///
11025 /// Functions that we can tell a priori must be emitted aren't added to this
11026 /// map.
11027 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
11028 /* Caller = */ FunctionDeclAndLoc>
11029 DeviceKnownEmittedFns;
11030
11031 /// A partial call graph maintained during CUDA/OpenMP device code compilation
11032 /// to support deferred diagnostics.
11033 ///
11034 /// Functions are only added here if, at the time they're considered, they are
11035 /// not known-emitted. As soon as we discover that a function is
11036 /// known-emitted, we remove it and everything it transitively calls from this
11037 /// set and add those functions to DeviceKnownEmittedFns.
11038 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
11039 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
11040 SourceLocation>>
11041 DeviceCallGraph;
11042
11043 /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
11044 /// deferred.
11045 ///
11046 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
11047 /// which are not allowed to appear inside __device__ functions and are
11048 /// allowed to appear in __host__ __device__ functions only if the host+device
11049 /// function is never codegen'ed.
11050 ///
11051 /// To handle this, we use the notion of "deferred diagnostics", where we
11052 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
11053 ///
11054 /// This class lets you emit either a regular diagnostic, a deferred
11055 /// diagnostic, or no diagnostic at all, according to an argument you pass to
11056 /// its constructor, thus simplifying the process of creating these "maybe
11057 /// deferred" diagnostics.
11058 class DeviceDiagBuilder {
11059 public:
11060 enum Kind {
11061 /// Emit no diagnostics.
11062 K_Nop,
11063 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
11064 K_Immediate,
11065 /// Emit the diagnostic immediately, and, if it's a warning or error, also
11066 /// emit a call stack showing how this function can be reached by an a
11067 /// priori known-emitted function.
11068 K_ImmediateWithCallStack,
11069 /// Create a deferred diagnostic, which is emitted only if the function
11070 /// it's attached to is codegen'ed. Also emit a call stack as with
11071 /// K_ImmediateWithCallStack.
11072 K_Deferred
11073 };
11074
11075 DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
11076 FunctionDecl *Fn, Sema &S);
11077 DeviceDiagBuilder(DeviceDiagBuilder &&D);
11078 DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
11079 ~DeviceDiagBuilder();
11080
11081 /// Convertible to bool: True if we immediately emitted an error, false if
11082 /// we didn't emit an error or we created a deferred error.
11083 ///
11084 /// Example usage:
11085 ///
11086 /// if (DeviceDiagBuilder(...) << foo << bar)
11087 /// return ExprError();
11088 ///
11089 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
11090 /// want to use these instead of creating a DeviceDiagBuilder yourself.
11091 operator bool() const { return ImmediateDiag.hasValue(); }
11092
11093 template <typename T>
11094 friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
11095 const T &Value) {
11096 if (Diag.ImmediateDiag.hasValue())
11097 *Diag.ImmediateDiag << Value;
11098 else if (Diag.PartialDiagId.hasValue())
11099 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
11100 << Value;
11101 return Diag;
11102 }
11103
11104 private:
11105 Sema &S;
11106 SourceLocation Loc;
11107 unsigned DiagID;
11108 FunctionDecl *Fn;
11109 bool ShowCallStack;
11110
11111 // Invariant: At most one of these Optionals has a value.
11112 // FIXME: Switch these to a Variant once that exists.
11113 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
11114 llvm::Optional<unsigned> PartialDiagId;
11115 };
11116
11117 /// Indicate that this function (and thus everything it transtively calls)
11118 /// will be codegen'ed, and emit any deferred diagnostics on this function and
11119 /// its (transitive) callees.
11120 void markKnownEmitted(
11121 Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
11122 SourceLocation OrigLoc,
11123 const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted);
11124
11125 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
11126 /// is "used as device code".
11127 ///
11128 /// - If CurContext is a __host__ function, does not emit any diagnostics.
11129 /// - If CurContext is a __device__ or __global__ function, emits the
11130 /// diagnostics immediately.
11131 /// - If CurContext is a __host__ __device__ function and we are compiling for
11132 /// the device, creates a diagnostic which is emitted if and when we realize
11133 /// that the function will be codegen'ed.
11134 ///
11135 /// Example usage:
11136 ///
11137 /// // Variable-length arrays are not allowed in CUDA device code.
11138 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
11139 /// return ExprError();
11140 /// // Otherwise, continue parsing as normal.
11141 DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
11142
11143 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
11144 /// is "used as host code".
11145 ///
11146 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
11147 DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
11148
11149 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
11150 /// context is "used as device code".
11151 ///
11152 /// - If CurContext is a `declare target` function or it is known that the
11153 /// function is emitted for the device, emits the diagnostics immediately.
11154 /// - If CurContext is a non-`declare target` function and we are compiling
11155 /// for the device, creates a diagnostic which is emitted if and when we
11156 /// realize that the function will be codegen'ed.
11157 ///
11158 /// Example usage:
11159 ///
11160 /// // Variable-length arrays are not allowed in NVPTX device code.
11161 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
11162 /// return ExprError();
11163 /// // Otherwise, continue parsing as normal.
11164 DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
11165
11166 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
11167 /// context is "used as host code".
11168 ///
11169 /// - If CurContext is a `declare target` function or it is known that the
11170 /// function is emitted for the host, emits the diagnostics immediately.
11171 /// - If CurContext is a non-host function, just ignore it.
11172 ///
11173 /// Example usage:
11174 ///
11175 /// // Variable-length arrays are not allowed in NVPTX device code.
11176 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
11177 /// return ExprError();
11178 /// // Otherwise, continue parsing as normal.
11179 DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
11180
11181 DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
11182
11183 enum CUDAFunctionTarget {
11184 CFT_Device,
11185 CFT_Global,
11186 CFT_Host,
11187 CFT_HostDevice,
11188 CFT_InvalidTarget
11189 };
11190
11191 /// Determines whether the given function is a CUDA device/host/kernel/etc.
11192 /// function.
11193 ///
11194 /// Use this rather than examining the function's attributes yourself -- you
11195 /// will get it wrong. Returns CFT_Host if D is null.
11196 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
11197 bool IgnoreImplicitHDAttr = false);
11198 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
11199
11200 /// Gets the CUDA target for the current context.
11201 CUDAFunctionTarget CurrentCUDATarget() {
11202 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
11203 }
11204
11205 // CUDA function call preference. Must be ordered numerically from
11206 // worst to best.
11207 enum CUDAFunctionPreference {
11208 CFP_Never, // Invalid caller/callee combination.
11209 CFP_WrongSide, // Calls from host-device to host or device
11210 // function that do not match current compilation
11211 // mode.
11212 CFP_HostDevice, // Any calls to host/device functions.
11213 CFP_SameSide, // Calls from host-device to host or device
11214 // function matching current compilation mode.
11215 CFP_Native, // host-to-host or device-to-device calls.
11216 };
11217
11218 /// Identifies relative preference of a given Caller/Callee
11219 /// combination, based on their host/device attributes.
11220 /// \param Caller function which needs address of \p Callee.
11221 /// nullptr in case of global context.
11222 /// \param Callee target function
11223 ///
11224 /// \returns preference value for particular Caller/Callee combination.
11225 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
11226 const FunctionDecl *Callee);
11227
11228 /// Determines whether Caller may invoke Callee, based on their CUDA
11229 /// host/device attributes. Returns false if the call is not allowed.
11230 ///
11231 /// Note: Will return true for CFP_WrongSide calls. These may appear in
11232 /// semantically correct CUDA programs, but only if they're never codegen'ed.
11233 bool IsAllowedCUDACall(const FunctionDecl *Caller,
11234 const FunctionDecl *Callee) {
11235 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
11236 }
11237
11238 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
11239 /// depending on FD and the current compilation settings.
11240 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
11241 const LookupResult &Previous);
11242
11243public:
11244 /// Check whether we're allowed to call Callee from the current context.
11245 ///
11246 /// - If the call is never allowed in a semantically-correct program
11247 /// (CFP_Never), emits an error and returns false.
11248 ///
11249 /// - If the call is allowed in semantically-correct programs, but only if
11250 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
11251 /// be emitted if and when the caller is codegen'ed, and returns true.
11252 ///
11253 /// Will only create deferred diagnostics for a given SourceLocation once,
11254 /// so you can safely call this multiple times without generating duplicate
11255 /// deferred errors.
11256 ///
11257 /// - Otherwise, returns true without emitting any diagnostics.
11258 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
11259
11260 /// Set __device__ or __host__ __device__ attributes on the given lambda
11261 /// operator() method.
11262 ///
11263 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
11264 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
11265 /// functions become __host__ __device__ themselves.
11266 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
11267
11268 /// Finds a function in \p Matches with highest calling priority
11269 /// from \p Caller context and erases all functions with lower
11270 /// calling priority.
11271 void EraseUnwantedCUDAMatches(
11272 const FunctionDecl *Caller,
11273 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
11274
11275 /// Given a implicit special member, infer its CUDA target from the
11276 /// calls it needs to make to underlying base/field special members.
11277 /// \param ClassDecl the class for which the member is being created.
11278 /// \param CSM the kind of special member.
11279 /// \param MemberDecl the special member itself.
11280 /// \param ConstRHS true if this is a copy operation with a const object on
11281 /// its RHS.
11282 /// \param Diagnose true if this call should emit diagnostics.
11283 /// \return true if there was an error inferring.
11284 /// The result of this call is implicit CUDA target attribute(s) attached to
11285 /// the member declaration.
11286 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
11287 CXXSpecialMember CSM,
11288 CXXMethodDecl *MemberDecl,
11289 bool ConstRHS,
11290 bool Diagnose);
11291
11292 /// \return true if \p CD can be considered empty according to CUDA
11293 /// (E.2.3.1 in CUDA 7.5 Programming guide).
11294 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
11295 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
11296
11297 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
11298 // case of error emits appropriate diagnostic and invalidates \p Var.
11299 //
11300 // \details CUDA allows only empty constructors as initializers for global
11301 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
11302 // __shared__ variables whether they are local or not (they all are implicitly
11303 // static in CUDA). One exception is that CUDA allows constant initializers
11304 // for __constant__ and __device__ variables.
11305 void checkAllowedCUDAInitializer(VarDecl *VD);
11306
11307 /// Check whether NewFD is a valid overload for CUDA. Emits
11308 /// diagnostics and invalidates NewFD if not.
11309 void checkCUDATargetOverload(FunctionDecl *NewFD,
11310 const LookupResult &Previous);
11311 /// Copies target attributes from the template TD to the function FD.
11312 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
11313
11314 /// Returns the name of the launch configuration function. This is the name
11315 /// of the function that will be called to configure kernel call, with the
11316 /// parameters specified via <<<>>>.
11317 std::string getCudaConfigureFuncName() const;
11318
11319 /// \name Code completion
11320 //@{
11321 /// Describes the context in which code completion occurs.
11322 enum ParserCompletionContext {
11323 /// Code completion occurs at top-level or namespace context.
11324 PCC_Namespace,
11325 /// Code completion occurs within a class, struct, or union.
11326 PCC_Class,
11327 /// Code completion occurs within an Objective-C interface, protocol,
11328 /// or category.
11329 PCC_ObjCInterface,
11330 /// Code completion occurs within an Objective-C implementation or
11331 /// category implementation
11332 PCC_ObjCImplementation,
11333 /// Code completion occurs within the list of instance variables
11334 /// in an Objective-C interface, protocol, category, or implementation.
11335 PCC_ObjCInstanceVariableList,
11336 /// Code completion occurs following one or more template
11337 /// headers.
11338 PCC_Template,
11339 /// Code completion occurs following one or more template
11340 /// headers within a class.
11341 PCC_MemberTemplate,
11342 /// Code completion occurs within an expression.
11343 PCC_Expression,
11344 /// Code completion occurs within a statement, which may
11345 /// also be an expression or a declaration.
11346 PCC_Statement,
11347 /// Code completion occurs at the beginning of the
11348 /// initialization statement (or expression) in a for loop.
11349 PCC_ForInit,
11350 /// Code completion occurs within the condition of an if,
11351 /// while, switch, or for statement.
11352 PCC_Condition,
11353 /// Code completion occurs within the body of a function on a
11354 /// recovery path, where we do not have a specific handle on our position
11355 /// in the grammar.
11356 PCC_RecoveryInFunction,
11357 /// Code completion occurs where only a type is permitted.
11358 PCC_Type,
11359 /// Code completion occurs in a parenthesized expression, which
11360 /// might also be a type cast.
11361 PCC_ParenthesizedExpression,
11362 /// Code completion occurs within a sequence of declaration
11363 /// specifiers within a function, method, or block.
11364 PCC_LocalDeclarationSpecifiers
11365 };
11366
11367 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
11368 void CodeCompleteOrdinaryName(Scope *S,
11369 ParserCompletionContext CompletionContext);
11370 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
11371 bool AllowNonIdentifiers,
11372 bool AllowNestedNameSpecifiers);
11373
11374 struct CodeCompleteExpressionData;
11375 void CodeCompleteExpression(Scope *S,
11376 const CodeCompleteExpressionData &Data);
11377 void CodeCompleteExpression(Scope *S, QualType PreferredType,
11378 bool IsParenthesized = false);
11379 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
11380 SourceLocation OpLoc, bool IsArrow,
11381 bool IsBaseExprStatement,
11382 QualType PreferredType);
11383 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
11384 QualType PreferredType);
11385 void CodeCompleteTag(Scope *S, unsigned TagSpec);
11386 void CodeCompleteTypeQualifiers(DeclSpec &DS);
11387 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
11388 const VirtSpecifiers *VS = nullptr);
11389 void CodeCompleteBracketDeclarator(Scope *S);
11390 void CodeCompleteCase(Scope *S);
11391 /// Reports signatures for a call to CodeCompleteConsumer and returns the
11392 /// preferred type for the current argument. Returned type can be null.
11393 QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
11394 SourceLocation OpenParLoc);
11395 QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
11396 SourceLocation Loc,
11397 ArrayRef<Expr *> Args,
11398 SourceLocation OpenParLoc);
11399 QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
11400 CXXScopeSpec SS,
11401 ParsedType TemplateTypeTy,
11402 ArrayRef<Expr *> ArgExprs,
11403 IdentifierInfo *II,
11404 SourceLocation OpenParLoc);
11405 void CodeCompleteInitializer(Scope *S, Decl *D);
11406 void CodeCompleteAfterIf(Scope *S);
11407
11408 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
11409 bool IsUsingDeclaration, QualType BaseType,
11410 QualType PreferredType);
11411 void CodeCompleteUsing(Scope *S);
11412 void CodeCompleteUsingDirective(Scope *S);
11413 void CodeCompleteNamespaceDecl(Scope *S);
11414 void CodeCompleteNamespaceAliasDecl(Scope *S);
11415 void CodeCompleteOperatorName(Scope *S);
11416 void CodeCompleteConstructorInitializer(
11417 Decl *Constructor,
11418 ArrayRef<CXXCtorInitializer *> Initializers);
11419
11420 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
11421 bool AfterAmpersand);
11422
11423 void CodeCompleteObjCAtDirective(Scope *S);
11424 void CodeCompleteObjCAtVisibility(Scope *S);
11425 void CodeCompleteObjCAtStatement(Scope *S);
11426 void CodeCompleteObjCAtExpression(Scope *S);
11427 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
11428 void CodeCompleteObjCPropertyGetter(Scope *S);
11429 void CodeCompleteObjCPropertySetter(Scope *S);
11430 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
11431 bool IsParameter);
11432 void CodeCompleteObjCMessageReceiver(Scope *S);
11433 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
11434 ArrayRef<IdentifierInfo *> SelIdents,
11435 bool AtArgumentExpression);
11436 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
11437 ArrayRef<IdentifierInfo *> SelIdents,
11438 bool AtArgumentExpression,
11439 bool IsSuper = false);
11440 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
11441 ArrayRef<IdentifierInfo *> SelIdents,
11442 bool AtArgumentExpression,
11443 ObjCInterfaceDecl *Super = nullptr);
11444 void CodeCompleteObjCForCollection(Scope *S,
11445 DeclGroupPtrTy IterationVar);
11446 void CodeCompleteObjCSelector(Scope *S,
11447 ArrayRef<IdentifierInfo *> SelIdents);
11448 void CodeCompleteObjCProtocolReferences(
11449 ArrayRef<IdentifierLocPair> Protocols);
11450 void CodeCompleteObjCProtocolDecl(Scope *S);
11451 void CodeCompleteObjCInterfaceDecl(Scope *S);
11452 void CodeCompleteObjCSuperclass(Scope *S,
11453 IdentifierInfo *ClassName,
11454 SourceLocation ClassNameLoc);
11455 void CodeCompleteObjCImplementationDecl(Scope *S);
11456 void CodeCompleteObjCInterfaceCategory(Scope *S,
11457 IdentifierInfo *ClassName,
11458 SourceLocation ClassNameLoc);
11459 void CodeCompleteObjCImplementationCategory(Scope *S,
11460 IdentifierInfo *ClassName,
11461 SourceLocation ClassNameLoc);
11462 void CodeCompleteObjCPropertyDefinition(Scope *S);
11463 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
11464 IdentifierInfo *PropertyName);
11465 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
11466 ParsedType ReturnType);
11467 void CodeCompleteObjCMethodDeclSelector(Scope *S,
11468 bool IsInstanceMethod,
11469 bool AtParameterName,
11470 ParsedType ReturnType,
11471 ArrayRef<IdentifierInfo *> SelIdents);
11472 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
11473 SourceLocation ClassNameLoc,
11474 bool IsBaseExprStatement);
11475 void CodeCompletePreprocessorDirective(bool InConditional);
11476 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
11477 void CodeCompletePreprocessorMacroName(bool IsDefinition);
11478 void CodeCompletePreprocessorExpression();
11479 void CodeCompletePreprocessorMacroArgument(Scope *S,
11480 IdentifierInfo *Macro,
11481 MacroInfo *MacroInfo,
11482 unsigned Argument);
11483 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
11484 void CodeCompleteNaturalLanguage();
11485 void CodeCompleteAvailabilityPlatformName();
11486 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
11487 CodeCompletionTUInfo &CCTUInfo,
11488 SmallVectorImpl<CodeCompletionResult> &Results);
11489 //@}
11490
11491 //===--------------------------------------------------------------------===//
11492 // Extra semantic analysis beyond the C type system
11493
11494public:
11495 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
11496 unsigned ByteNo) const;
11497
11498private:
11499 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11500 const ArraySubscriptExpr *ASE=nullptr,
11501 bool AllowOnePastEnd=true, bool IndexNegated=false);
11502 void CheckArrayAccess(const Expr *E);
11503 // Used to grab the relevant information from a FormatAttr and a
11504 // FunctionDeclaration.
11505 struct FormatStringInfo {
11506 unsigned FormatIdx;
11507 unsigned FirstDataArg;
11508 bool HasVAListArg;
11509 };
11510
11511 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
11512 FormatStringInfo *FSI);
11513 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
11514 const FunctionProtoType *Proto);
11515 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
11516 ArrayRef<const Expr *> Args);
11517 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
11518 const FunctionProtoType *Proto);
11519 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
11520 void CheckConstructorCall(FunctionDecl *FDecl,
11521 ArrayRef<const Expr *> Args,
11522 const FunctionProtoType *Proto,
11523 SourceLocation Loc);
11524
11525 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
11526 const Expr *ThisArg, ArrayRef<const Expr *> Args,
11527 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
11528 VariadicCallType CallType);
11529
11530 bool CheckObjCString(Expr *Arg);
11531 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
11532
11533 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
11534 unsigned BuiltinID, CallExpr *TheCall);
11535 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
11536
11537 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
11538 unsigned MaxWidth);
11539 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11540 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11541 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11542
11543 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11544 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11545 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11546 bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
11547 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
11548 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11549 bool CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
11550 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
11551 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11552 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
11553 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
11554 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11555 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11556
11557 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
11558 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
11559 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
11560 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
11561 bool SemaBuiltinVSX(CallExpr *TheCall);
11562 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
11563
11564public:
11565 // Used by C++ template instantiation.
11566 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
11567 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
11568 SourceLocation BuiltinLoc,
11569 SourceLocation RParenLoc);
11570
11571private:
11572 bool SemaBuiltinPrefetch(CallExpr *TheCall);
11573 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
11574 bool SemaBuiltinAssume(CallExpr *TheCall);
11575 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
11576 bool SemaBuiltinLongjmp(CallExpr *TheCall);
11577 bool SemaBuiltinSetjmp(CallExpr *TheCall);
11578 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
11579 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
11580 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
11581 AtomicExpr::AtomicOp Op);
11582 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
11583 bool IsDelete);
11584 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
11585 llvm::APSInt &Result);
11586 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
11587 int High, bool RangeIsError = true);
11588 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
11589 unsigned Multiple);
11590 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
11591 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum);
11592 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum);
11593 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
11594 int ArgNum, unsigned ExpectedFieldNum,
11595 bool AllowName);
11596 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
11597public:
11598 enum FormatStringType {
11599 FST_Scanf,
11600 FST_Printf,
11601 FST_NSString,
11602 FST_Strftime,
11603 FST_Strfmon,
11604 FST_Kprintf,
11605 FST_FreeBSDKPrintf,
11606 FST_OSTrace,
11607 FST_OSLog,
11608 FST_Unknown
11609 };
11610 static FormatStringType GetFormatStringType(const FormatAttr *Format);
11611
11612 bool FormatStringHasSArg(const StringLiteral *FExpr);
11613
11614 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
11615
11616private:
11617 bool CheckFormatArguments(const FormatAttr *Format,
11618 ArrayRef<const Expr *> Args,
11619 bool IsCXXMember,
11620 VariadicCallType CallType,
11621 SourceLocation Loc, SourceRange Range,
11622 llvm::SmallBitVector &CheckedVarArgs);
11623 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
11624 bool HasVAListArg, unsigned format_idx,
11625 unsigned firstDataArg, FormatStringType Type,
11626 VariadicCallType CallType,
11627 SourceLocation Loc, SourceRange range,
11628 llvm::SmallBitVector &CheckedVarArgs);
11629
11630 void CheckAbsoluteValueFunction(const CallExpr *Call,
11631 const FunctionDecl *FDecl);
11632
11633 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
11634
11635 void CheckMemaccessArguments(const CallExpr *Call,
11636 unsigned BId,
11637 IdentifierInfo *FnName);
11638
11639 void CheckStrlcpycatArguments(const CallExpr *Call,
11640 IdentifierInfo *FnName);
11641
11642 void CheckStrncatArguments(const CallExpr *Call,
11643 IdentifierInfo *FnName);
11644
11645 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11646 SourceLocation ReturnLoc,
11647 bool isObjCMethod = false,
11648 const AttrVec *Attrs = nullptr,
11649 const FunctionDecl *FD = nullptr);
11650
11651public:
11652 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
11653
11654private:
11655 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
11656 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
11657 void CheckForIntOverflow(Expr *E);
11658 void CheckUnsequencedOperations(const Expr *E);
11659
11660 /// Perform semantic checks on a completed expression. This will either
11661 /// be a full-expression or a default argument expression.
11662 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
11663 bool IsConstexpr = false);
11664
11665 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
11666 Expr *Init);
11667
11668 /// Check if there is a field shadowing.
11669 void CheckShadowInheritedFields(const SourceLocation &Loc,
11670 DeclarationName FieldName,
11671 const CXXRecordDecl *RD,
11672 bool DeclIsField = true);
11673
11674 /// Check if the given expression contains 'break' or 'continue'
11675 /// statement that produces control flow different from GCC.
11676 void CheckBreakContinueBinding(Expr *E);
11677
11678 /// Check whether receiver is mutable ObjC container which
11679 /// attempts to add itself into the container
11680 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
11681
11682 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
11683 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
11684 bool DeleteWasArrayForm);
11685public:
11686 /// Register a magic integral constant to be used as a type tag.
11687 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11688 uint64_t MagicValue, QualType Type,
11689 bool LayoutCompatible, bool MustBeNull);
11690
11691 struct TypeTagData {
11692 TypeTagData() {}
11693
11694 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
11695 Type(Type), LayoutCompatible(LayoutCompatible),
11696 MustBeNull(MustBeNull)
11697 {}
11698
11699 QualType Type;
11700
11701 /// If true, \c Type should be compared with other expression's types for
11702 /// layout-compatibility.
11703 unsigned LayoutCompatible : 1;
11704 unsigned MustBeNull : 1;
11705 };
11706
11707 /// A pair of ArgumentKind identifier and magic value. This uniquely
11708 /// identifies the magic value.
11709 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
11710
11711private:
11712 /// A map from magic value to type information.
11713 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
11714 TypeTagForDatatypeMagicValues;
11715
11716 /// Peform checks on a call of a function with argument_with_type_tag
11717 /// or pointer_with_type_tag attributes.
11718 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11719 const ArrayRef<const Expr *> ExprArgs,
11720 SourceLocation CallSiteLoc);
11721
11722 /// Check if we are taking the address of a packed field
11723 /// as this may be a problem if the pointer value is dereferenced.
11724 void CheckAddressOfPackedMember(Expr *rhs);
11725
11726 /// The parser's current scope.
11727 ///
11728 /// The parser maintains this state here.
11729 Scope *CurScope;
11730
11731 mutable IdentifierInfo *Ident_super;
11732 mutable IdentifierInfo *Ident___float128;
11733
11734 /// Nullability type specifiers.
11735 IdentifierInfo *Ident__Nonnull = nullptr;
11736 IdentifierInfo *Ident__Nullable = nullptr;
11737 IdentifierInfo *Ident__Null_unspecified = nullptr;
11738
11739 IdentifierInfo *Ident_NSError = nullptr;
11740
11741 /// The handler for the FileChanged preprocessor events.
11742 ///
11743 /// Used for diagnostics that implement custom semantic analysis for #include
11744 /// directives, like -Wpragma-pack.
11745 sema::SemaPPCallbacks *SemaPPCallbackHandler;
11746
11747protected:
11748 friend class Parser;
11749 friend class InitializationSequence;
11750 friend class ASTReader;
11751 friend class ASTDeclReader;
11752 friend class ASTWriter;
11753
11754public:
11755 /// Retrieve the keyword associated
11756 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
11757
11758 /// The struct behind the CFErrorRef pointer.
11759 RecordDecl *CFError = nullptr;
11760
11761 /// Retrieve the identifier "NSError".
11762 IdentifierInfo *getNSErrorIdent();
11763
11764 /// Retrieve the parser's current scope.
11765 ///
11766 /// This routine must only be used when it is certain that semantic analysis
11767 /// and the parser are in precisely the same context, which is not the case
11768 /// when, e.g., we are performing any kind of template instantiation.
11769 /// Therefore, the only safe places to use this scope are in the parser
11770 /// itself and in routines directly invoked from the parser and *never* from
11771 /// template substitution or instantiation.
11772 Scope *getCurScope() const { return CurScope; }
11773
11774 void incrementMSManglingNumber() const {
11775 return CurScope->incrementMSManglingNumber();
11776 }
11777
11778 IdentifierInfo *getSuperIdentifier() const;
11779 IdentifierInfo *getFloat128Identifier() const;
11780
11781 Decl *getObjCDeclContext() const;
11782
11783 DeclContext *getCurLexicalContext() const {
11784 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
11785 }
11786
11787 const DeclContext *getCurObjCLexicalContext() const {
11788 const DeclContext *DC = getCurLexicalContext();
11789 // A category implicitly has the attribute of the interface.
11790 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
11791 DC = CatD->getClassInterface();
11792 return DC;
11793 }
11794
11795 /// To be used for checking whether the arguments being passed to
11796 /// function exceeds the number of parameters expected for it.
11797 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
11798 bool PartialOverloading = false) {
11799 // We check whether we're just after a comma in code-completion.
11800 if (NumArgs > 0 && PartialOverloading)
11801 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
11802 return NumArgs > NumParams;
11803 }
11804
11805 // Emitting members of dllexported classes is delayed until the class
11806 // (including field initializers) is fully parsed.
11807 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
11808 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
11809
11810private:
11811 int ParsingClassDepth = 0;
11812
11813 class SavePendingParsedClassStateRAII {
11814 public:
11815 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
11816
11817 ~SavePendingParsedClassStateRAII() {
11818 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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 11819, __PRETTY_FUNCTION__))
11819 "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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 11819, __PRETTY_FUNCTION__))
;
11820 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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 11821, __PRETTY_FUNCTION__))
11821 "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-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/Sema.h"
, 11821, __PRETTY_FUNCTION__))
;
11822 swapSavedState();
11823 }
11824
11825 private:
11826 Sema &S;
11827 decltype(DelayedOverridingExceptionSpecChecks)
11828 SavedOverridingExceptionSpecChecks;
11829 decltype(DelayedEquivalentExceptionSpecChecks)
11830 SavedEquivalentExceptionSpecChecks;
11831
11832 void swapSavedState() {
11833 SavedOverridingExceptionSpecChecks.swap(
11834 S.DelayedOverridingExceptionSpecChecks);
11835 SavedEquivalentExceptionSpecChecks.swap(
11836 S.DelayedEquivalentExceptionSpecChecks);
11837 }
11838 };
11839
11840 /// Helper class that collects misaligned member designations and
11841 /// their location info for delayed diagnostics.
11842 struct MisalignedMember {
11843 Expr *E;
11844 RecordDecl *RD;
11845 ValueDecl *MD;
11846 CharUnits Alignment;
11847
11848 MisalignedMember() : E(), RD(), MD(), Alignment() {}
11849 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
11850 CharUnits Alignment)
11851 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
11852 explicit MisalignedMember(Expr *E)
11853 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
11854
11855 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
11856 };
11857 /// Small set of gathered accesses to potentially misaligned members
11858 /// due to the packed attribute.
11859 SmallVector<MisalignedMember, 4> MisalignedMembers;
11860
11861 /// Adds an expression to the set of gathered misaligned members.
11862 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11863 CharUnits Alignment);
11864
11865public:
11866 /// Diagnoses the current set of gathered accesses. This typically
11867 /// happens at full expression level. The set is cleared after emitting the
11868 /// diagnostics.
11869 void DiagnoseMisalignedMembers();
11870
11871 /// This function checks if the expression is in the sef of potentially
11872 /// misaligned members and it is converted to some pointer type T with lower
11873 /// or equal alignment requirements. If so it removes it. This is used when
11874 /// we do not want to diagnose such misaligned access (e.g. in conversions to
11875 /// void*).
11876 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
11877
11878 /// This function calls Action when it determines that E designates a
11879 /// misaligned member due to the packed attribute. This is used to emit
11880 /// local diagnostics like in reference binding.
11881 void RefersToMemberWithReducedAlignment(
11882 Expr *E,
11883 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11884 Action);
11885
11886 /// Describes the reason a calling convention specification was ignored, used
11887 /// for diagnostics.
11888 enum class CallingConventionIgnoredReason {
11889 ForThisTarget = 0,
11890 VariadicFunction,
11891 ConstructorDestructor,
11892 BuiltinFunction
11893 };
11894};
11895
11896/// RAII object that enters a new expression evaluation context.
11897class EnterExpressionEvaluationContext {
11898 Sema &Actions;
11899 bool Entered = true;
11900
11901public:
11902 EnterExpressionEvaluationContext(
11903 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
11904 Decl *LambdaContextDecl = nullptr,
11905 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
11906 Sema::ExpressionEvaluationContextRecord::EK_Other,
11907 bool ShouldEnter = true)
11908 : Actions(Actions), Entered(ShouldEnter) {
11909 if (Entered)
11910 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
11911 ExprContext);
11912 }
11913 EnterExpressionEvaluationContext(
11914 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
11915 Sema::ReuseLambdaContextDecl_t,
11916 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
11917 Sema::ExpressionEvaluationContextRecord::EK_Other)
11918 : Actions(Actions) {
11919 Actions.PushExpressionEvaluationContext(
11920 NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
11921 }
11922
11923 enum InitListTag { InitList };
11924 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
11925 bool ShouldEnter = true)
11926 : Actions(Actions), Entered(false) {
11927 // In C++11 onwards, narrowing checks are performed on the contents of
11928 // braced-init-lists, even when they occur within unevaluated operands.
11929 // Therefore we still need to instantiate constexpr functions used in such
11930 // a context.
11931 if (ShouldEnter && Actions.isUnevaluatedContext() &&
11932 Actions.getLangOpts().CPlusPlus11) {
11933 Actions.PushExpressionEvaluationContext(
11934 Sema::ExpressionEvaluationContext::UnevaluatedList);
11935 Entered = true;
11936 }
11937 }
11938
11939 ~EnterExpressionEvaluationContext() {
11940 if (Entered)
11941 Actions.PopExpressionEvaluationContext();
11942 }
11943};
11944
11945DeductionFailureInfo
11946MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
11947 sema::TemplateDeductionInfo &Info);
11948
11949/// Contains a late templated function.
11950/// Will be parsed at the end of the translation unit, used by Sema & Parser.
11951struct LateParsedTemplate {
11952 CachedTokens Toks;
11953 /// The template function declaration to be late parsed.
11954 Decl *D;
11955};
11956} // end namespace clang
11957
11958namespace llvm {
11959// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
11960// SourceLocation.
11961template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
11962 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
11963 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
11964
11965 static FunctionDeclAndLoc getEmptyKey() {
11966 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
11967 }
11968
11969 static FunctionDeclAndLoc getTombstoneKey() {
11970 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
11971 }
11972
11973 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
11974 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
11975 FDL.Loc.getRawEncoding());
11976 }
11977
11978 static bool isEqual(const FunctionDeclAndLoc &LHS,
11979 const FunctionDeclAndLoc &RHS) {
11980 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
11981 }
11982};
11983} // namespace llvm
11984
11985#endif