Bug Summary

File:tools/clang/lib/Sema/SemaOverload.cpp
Warning:line 636, column 5
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-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn337204/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-17-043059-5239-1 -x c++ /build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Overload.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/TypeOrdering.h"
22#include "clang/Basic/Diagnostic.h"
23#include "clang/Basic/DiagnosticOptions.h"
24#include "clang/Basic/PartialDiagnostic.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
31#include "llvm/ADT/DenseSet.h"
32#include "llvm/ADT/Optional.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/SmallPtrSet.h"
35#include "llvm/ADT/SmallString.h"
36#include <algorithm>
37#include <cstdlib>
38
39using namespace clang;
40using namespace sema;
41
42static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
43 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
44 return P->hasAttr<PassObjectSizeAttr>();
45 });
46}
47
48/// A convenience routine for creating a decayed reference to a function.
49static ExprResult
50CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
51 const Expr *Base, bool HadMultipleCandidates,
52 SourceLocation Loc = SourceLocation(),
53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
54 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55 return ExprError();
56 // If FoundDecl is different from Fn (such as if one is a template
57 // and the other a specialization), make sure DiagnoseUseOfDecl is
58 // called on both.
59 // FIXME: This would be more comprehensively addressed by modifying
60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61 // being used.
62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63 return ExprError();
64 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
65 S.ResolveExceptionSpec(Loc, FPT);
66 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
67 VK_LValue, Loc, LocInfo);
68 if (HadMultipleCandidates)
69 DRE->setHadMultipleCandidates(true);
70
71 S.MarkDeclRefReferenced(DRE, Base);
72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
73 CK_FunctionToPointerDecay);
74}
75
76static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
77 bool InOverloadResolution,
78 StandardConversionSequence &SCS,
79 bool CStyle,
80 bool AllowObjCWritebackConversion);
81
82static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83 QualType &ToType,
84 bool InOverloadResolution,
85 StandardConversionSequence &SCS,
86 bool CStyle);
87static OverloadingResult
88IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
89 UserDefinedConversionSequence& User,
90 OverloadCandidateSet& Conversions,
91 bool AllowExplicit,
92 bool AllowObjCConversionOnExplicit);
93
94
95static ImplicitConversionSequence::CompareKind
96CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareQualificationConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
105static ImplicitConversionSequence::CompareKind
106CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
107 const StandardConversionSequence& SCS1,
108 const StandardConversionSequence& SCS2);
109
110/// GetConversionRank - Retrieve the implicit conversion rank
111/// corresponding to the given implicit conversion kind.
112ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
113 static const ImplicitConversionRank
114 Rank[(int)ICK_Num_Conversion_Kinds] = {
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Promotion,
122 ICR_Promotion,
123 ICR_Promotion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_OCL_Scalar_Widening,
135 ICR_Complex_Real_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Writeback_Conversion,
139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
140 // it was omitted by the patch that added
141 // ICK_Zero_Event_Conversion
142 ICR_C_Conversion,
143 ICR_C_Conversion_Extension
144 };
145 return Rank[(int)Kind];
146}
147
148/// GetImplicitConversionName - Return the name of this kind of
149/// implicit conversion.
150static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
152 "No conversion",
153 "Lvalue-to-rvalue",
154 "Array-to-pointer",
155 "Function-to-pointer",
156 "Function pointer conversion",
157 "Qualification",
158 "Integral promotion",
159 "Floating point promotion",
160 "Complex promotion",
161 "Integral conversion",
162 "Floating conversion",
163 "Complex conversion",
164 "Floating-integral conversion",
165 "Pointer conversion",
166 "Pointer-to-member conversion",
167 "Boolean conversion",
168 "Compatible-types conversion",
169 "Derived-to-base conversion",
170 "Vector conversion",
171 "Vector splat",
172 "Complex-real conversion",
173 "Block Pointer conversion",
174 "Transparent Union Conversion",
175 "Writeback conversion",
176 "OpenCL Zero Event Conversion",
177 "C specific type conversion",
178 "Incompatible pointer conversion"
179 };
180 return Name[Kind];
181}
182
183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
189 DeprecatedStringLiteralToCharPtr = false;
190 QualificationIncludesObjCLifetime = false;
191 ReferenceBinding = false;
192 DirectBinding = false;
193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
197 ObjCLifetimeConversionBinding = false;
198 CopyConstructor = nullptr;
199}
200
201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
217/// used as part of the ranking of standard conversion sequences
218/// (C++ 13.3.3.2p4).
219bool StandardConversionSequence::isPointerConversionToBool() const {
220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
224 if (getToType(1)->isBooleanType() &&
225 (getFromType()->isPointerType() ||
226 getFromType()->isMemberPointerType() ||
227 getFromType()->isObjCObjectPointerType() ||
228 getFromType()->isBlockPointerType() ||
229 getFromType()->isNullPtrType() ||
230 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
231 return true;
232
233 return false;
234}
235
236/// isPointerConversionToVoidPointer - Determines whether this
237/// conversion is a conversion of a pointer to a void pointer. This is
238/// used as part of the ranking of standard conversion sequences (C++
239/// 13.3.3.2p4).
240bool
241StandardConversionSequence::
242isPointerConversionToVoidPointer(ASTContext& Context) const {
243 QualType FromType = getFromType();
244 QualType ToType = getToType(1);
245
246 // Note that FromType has not necessarily been transformed by the
247 // array-to-pointer implicit conversion, so check for its presence
248 // and redo the conversion to get a pointer.
249 if (First == ICK_Array_To_Pointer)
250 FromType = Context.getArrayDecayedType(FromType);
251
252 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
253 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
254 return ToPtrType->getPointeeType()->isVoidType();
255
256 return false;
257}
258
259/// Skip any implicit casts which could be either part of a narrowing conversion
260/// or after one in an implicit conversion.
261static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
262 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
263 switch (ICE->getCastKind()) {
264 case CK_NoOp:
265 case CK_IntegralCast:
266 case CK_IntegralToBoolean:
267 case CK_IntegralToFloating:
268 case CK_BooleanToSignedIntegral:
269 case CK_FloatingToIntegral:
270 case CK_FloatingToBoolean:
271 case CK_FloatingCast:
272 Converted = ICE->getSubExpr();
273 continue;
274
275 default:
276 return Converted;
277 }
278 }
279
280 return Converted;
281}
282
283/// Check if this standard conversion sequence represents a narrowing
284/// conversion, according to C++11 [dcl.init.list]p7.
285///
286/// \param Ctx The AST context.
287/// \param Converted The result of applying this standard conversion sequence.
288/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
289/// value of the expression prior to the narrowing conversion.
290/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
291/// type of the expression prior to the narrowing conversion.
292/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
293/// from floating point types to integral types should be ignored.
294NarrowingKind StandardConversionSequence::getNarrowingKind(
295 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
296 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
297 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")(static_cast <bool> (Ctx.getLangOpts().CPlusPlus &&
"narrowing check outside C++") ? void (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 297, __extension__ __PRETTY_FUNCTION__))
;
298
299 // C++11 [dcl.init.list]p7:
300 // A narrowing conversion is an implicit conversion ...
301 QualType FromType = getToType(0);
302 QualType ToType = getToType(1);
303
304 // A conversion to an enumeration type is narrowing if the conversion to
305 // the underlying type is narrowing. This only arises for expressions of
306 // the form 'Enum{init}'.
307 if (auto *ET = ToType->getAs<EnumType>())
308 ToType = ET->getDecl()->getIntegerType();
309
310 switch (Second) {
311 // 'bool' is an integral type; dispatch to the right place to handle it.
312 case ICK_Boolean_Conversion:
313 if (FromType->isRealFloatingType())
314 goto FloatingIntegralConversion;
315 if (FromType->isIntegralOrUnscopedEnumerationType())
316 goto IntegralConversion;
317 // Boolean conversions can be from pointers and pointers to members
318 // [conv.bool], and those aren't considered narrowing conversions.
319 return NK_Not_Narrowing;
320
321 // -- from a floating-point type to an integer type, or
322 //
323 // -- from an integer type or unscoped enumeration type to a floating-point
324 // type, except where the source is a constant expression and the actual
325 // value after conversion will fit into the target type and will produce
326 // the original value when converted back to the original type, or
327 case ICK_Floating_Integral:
328 FloatingIntegralConversion:
329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330 return NK_Type_Narrowing;
331 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
332 ToType->isRealFloatingType()) {
333 if (IgnoreFloatToIntegralConversion)
334 return NK_Not_Narrowing;
335 llvm::APSInt IntConstantValue;
336 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
337 assert(Initializer && "Unknown conversion expression")(static_cast <bool> (Initializer && "Unknown conversion expression"
) ? void (0) : __assert_fail ("Initializer && \"Unknown conversion expression\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 337, __extension__ __PRETTY_FUNCTION__))
;
338
339 // If it's value-dependent, we can't tell whether it's narrowing.
340 if (Initializer->isValueDependent())
341 return NK_Dependent_Narrowing;
342
343 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
344 // Convert the integer to the floating type.
345 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
346 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
347 llvm::APFloat::rmNearestTiesToEven);
348 // And back.
349 llvm::APSInt ConvertedValue = IntConstantValue;
350 bool ignored;
351 Result.convertToInteger(ConvertedValue,
352 llvm::APFloat::rmTowardZero, &ignored);
353 // If the resulting value is different, this was a narrowing conversion.
354 if (IntConstantValue != ConvertedValue) {
355 ConstantValue = APValue(IntConstantValue);
356 ConstantType = Initializer->getType();
357 return NK_Constant_Narrowing;
358 }
359 } else {
360 // Variables are always narrowings.
361 return NK_Variable_Narrowing;
362 }
363 }
364 return NK_Not_Narrowing;
365
366 // -- from long double to double or float, or from double to float, except
367 // where the source is a constant expression and the actual value after
368 // conversion is within the range of values that can be represented (even
369 // if it cannot be represented exactly), or
370 case ICK_Floating_Conversion:
371 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
372 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
373 // FromType is larger than ToType.
374 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
375
376 // If it's value-dependent, we can't tell whether it's narrowing.
377 if (Initializer->isValueDependent())
378 return NK_Dependent_Narrowing;
379
380 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
381 // Constant!
382 assert(ConstantValue.isFloat())(static_cast <bool> (ConstantValue.isFloat()) ? void (0
) : __assert_fail ("ConstantValue.isFloat()", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 382, __extension__ __PRETTY_FUNCTION__))
;
383 llvm::APFloat FloatVal = ConstantValue.getFloat();
384 // Convert the source value into the target type.
385 bool ignored;
386 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
387 Ctx.getFloatTypeSemantics(ToType),
388 llvm::APFloat::rmNearestTiesToEven, &ignored);
389 // If there was no overflow, the source value is within the range of
390 // values that can be represented.
391 if (ConvertStatus & llvm::APFloat::opOverflow) {
392 ConstantType = Initializer->getType();
393 return NK_Constant_Narrowing;
394 }
395 } else {
396 return NK_Variable_Narrowing;
397 }
398 }
399 return NK_Not_Narrowing;
400
401 // -- from an integer type or unscoped enumeration type to an integer type
402 // that cannot represent all the values of the original type, except where
403 // the source is a constant expression and the actual value after
404 // conversion will fit into the target type and will produce the original
405 // value when converted back to the original type.
406 case ICK_Integral_Conversion:
407 IntegralConversion: {
408 assert(FromType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (FromType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 408, __extension__ __PRETTY_FUNCTION__))
;
409 assert(ToType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (ToType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 409, __extension__ __PRETTY_FUNCTION__))
;
410 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
411 const unsigned FromWidth = Ctx.getIntWidth(FromType);
412 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
413 const unsigned ToWidth = Ctx.getIntWidth(ToType);
414
415 if (FromWidth > ToWidth ||
416 (FromWidth == ToWidth && FromSigned != ToSigned) ||
417 (FromSigned && !ToSigned)) {
418 // Not all values of FromType can be represented in ToType.
419 llvm::APSInt InitializerValue;
420 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
421
422 // If it's value-dependent, we can't tell whether it's narrowing.
423 if (Initializer->isValueDependent())
424 return NK_Dependent_Narrowing;
425
426 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
427 // Such conversions on variables are always narrowing.
428 return NK_Variable_Narrowing;
429 }
430 bool Narrowing = false;
431 if (FromWidth < ToWidth) {
432 // Negative -> unsigned is narrowing. Otherwise, more bits is never
433 // narrowing.
434 if (InitializerValue.isSigned() && InitializerValue.isNegative())
435 Narrowing = true;
436 } else {
437 // Add a bit to the InitializerValue so we don't have to worry about
438 // signed vs. unsigned comparisons.
439 InitializerValue = InitializerValue.extend(
440 InitializerValue.getBitWidth() + 1);
441 // Convert the initializer to and from the target width and signed-ness.
442 llvm::APSInt ConvertedValue = InitializerValue;
443 ConvertedValue = ConvertedValue.trunc(ToWidth);
444 ConvertedValue.setIsSigned(ToSigned);
445 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
446 ConvertedValue.setIsSigned(InitializerValue.isSigned());
447 // If the result is different, this was a narrowing conversion.
448 if (ConvertedValue != InitializerValue)
449 Narrowing = true;
450 }
451 if (Narrowing) {
452 ConstantType = Initializer->getType();
453 ConstantValue = APValue(InitializerValue);
454 return NK_Constant_Narrowing;
455 }
456 }
457 return NK_Not_Narrowing;
458 }
459
460 default:
461 // Other kinds of conversions are not narrowings.
462 return NK_Not_Narrowing;
463 }
464}
465
466/// dump - Print this standard conversion sequence to standard
467/// error. Useful for debugging overloading issues.
468LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void StandardConversionSequence::dump() const {
469 raw_ostream &OS = llvm::errs();
470 bool PrintedSomething = false;
471 if (First != ICK_Identity) {
472 OS << GetImplicitConversionName(First);
473 PrintedSomething = true;
474 }
475
476 if (Second != ICK_Identity) {
477 if (PrintedSomething) {
478 OS << " -> ";
479 }
480 OS << GetImplicitConversionName(Second);
481
482 if (CopyConstructor) {
483 OS << " (by copy constructor)";
484 } else if (DirectBinding) {
485 OS << " (direct reference binding)";
486 } else if (ReferenceBinding) {
487 OS << " (reference binding)";
488 }
489 PrintedSomething = true;
490 }
491
492 if (Third != ICK_Identity) {
493 if (PrintedSomething) {
494 OS << " -> ";
495 }
496 OS << GetImplicitConversionName(Third);
497 PrintedSomething = true;
498 }
499
500 if (!PrintedSomething) {
501 OS << "No conversions required";
502 }
503}
504
505/// dump - Print this user-defined conversion sequence to standard
506/// error. Useful for debugging overloading issues.
507void UserDefinedConversionSequence::dump() const {
508 raw_ostream &OS = llvm::errs();
509 if (Before.First || Before.Second || Before.Third) {
510 Before.dump();
511 OS << " -> ";
512 }
513 if (ConversionFunction)
514 OS << '\'' << *ConversionFunction << '\'';
515 else
516 OS << "aggregate initialization";
517 if (After.First || After.Second || After.Third) {
518 OS << " -> ";
519 After.dump();
520 }
521}
522
523/// dump - Print this implicit conversion sequence to standard
524/// error. Useful for debugging overloading issues.
525void ImplicitConversionSequence::dump() const {
526 raw_ostream &OS = llvm::errs();
527 if (isStdInitializerListElement())
528 OS << "Worst std::initializer_list element conversion: ";
529 switch (ConversionKind) {
530 case StandardConversion:
531 OS << "Standard conversion: ";
532 Standard.dump();
533 break;
534 case UserDefinedConversion:
535 OS << "User-defined conversion: ";
536 UserDefined.dump();
537 break;
538 case EllipsisConversion:
539 OS << "Ellipsis conversion";
540 break;
541 case AmbiguousConversion:
542 OS << "Ambiguous conversion";
543 break;
544 case BadConversion:
545 OS << "Bad conversion";
546 break;
547 }
548
549 OS << "\n";
550}
551
552void AmbiguousConversionSequence::construct() {
553 new (&conversions()) ConversionSet();
554}
555
556void AmbiguousConversionSequence::destruct() {
557 conversions().~ConversionSet();
558}
559
560void
561AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
562 FromTypePtr = O.FromTypePtr;
563 ToTypePtr = O.ToTypePtr;
564 new (&conversions()) ConversionSet(O.conversions());
565}
566
567namespace {
568 // Structure used by DeductionFailureInfo to store
569 // template argument information.
570 struct DFIArguments {
571 TemplateArgument FirstArg;
572 TemplateArgument SecondArg;
573 };
574 // Structure used by DeductionFailureInfo to store
575 // template parameter and template argument information.
576 struct DFIParamWithArguments : DFIArguments {
577 TemplateParameter Param;
578 };
579 // Structure used by DeductionFailureInfo to store template argument
580 // information and the index of the problematic call argument.
581 struct DFIDeducedMismatchArgs : DFIArguments {
582 TemplateArgumentList *TemplateArgs;
583 unsigned CallArgIndex;
584 };
585}
586
587/// Convert from Sema's representation of template deduction information
588/// to the form used in overload-candidate information.
589DeductionFailureInfo
590clang::MakeDeductionFailureInfo(ASTContext &Context,
591 Sema::TemplateDeductionResult TDK,
592 TemplateDeductionInfo &Info) {
593 DeductionFailureInfo Result;
594 Result.Result = static_cast<unsigned>(TDK);
595 Result.HasDiagnostic = false;
596 switch (TDK) {
7
Control jumps to 'case TDK_Inconsistent:' at line 632
597 case Sema::TDK_Invalid:
598 case Sema::TDK_InstantiationDepth:
599 case Sema::TDK_TooManyArguments:
600 case Sema::TDK_TooFewArguments:
601 case Sema::TDK_MiscellaneousDeductionFailure:
602 case Sema::TDK_CUDATargetMismatch:
603 Result.Data = nullptr;
604 break;
605
606 case Sema::TDK_Incomplete:
607 case Sema::TDK_InvalidExplicitArguments:
608 Result.Data = Info.Param.getOpaqueValue();
609 break;
610
611 case Sema::TDK_DeducedMismatch:
612 case Sema::TDK_DeducedMismatchNested: {
613 // FIXME: Should allocate from normal heap so that we can free this later.
614 auto *Saved = new (Context) DFIDeducedMismatchArgs;
615 Saved->FirstArg = Info.FirstArg;
616 Saved->SecondArg = Info.SecondArg;
617 Saved->TemplateArgs = Info.take();
618 Saved->CallArgIndex = Info.CallArgIndex;
619 Result.Data = Saved;
620 break;
621 }
622
623 case Sema::TDK_NonDeducedMismatch: {
624 // FIXME: Should allocate from normal heap so that we can free this later.
625 DFIArguments *Saved = new (Context) DFIArguments;
626 Saved->FirstArg = Info.FirstArg;
627 Saved->SecondArg = Info.SecondArg;
628 Result.Data = Saved;
629 break;
630 }
631
632 case Sema::TDK_Inconsistent:
633 case Sema::TDK_Underqualified: {
634 // FIXME: Should allocate from normal heap so that we can free this later.
635 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
8
'Saved' initialized to a null pointer value
636 Saved->Param = Info.Param;
9
Called C++ object pointer is null
637 Saved->FirstArg = Info.FirstArg;
638 Saved->SecondArg = Info.SecondArg;
639 Result.Data = Saved;
640 break;
641 }
642
643 case Sema::TDK_SubstitutionFailure:
644 Result.Data = Info.take();
645 if (Info.hasSFINAEDiagnostic()) {
646 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
647 SourceLocation(), PartialDiagnostic::NullDiagnostic());
648 Info.takeSFINAEDiagnostic(*Diag);
649 Result.HasDiagnostic = true;
650 }
651 break;
652
653 case Sema::TDK_Success:
654 case Sema::TDK_NonDependentConversionFailure:
655 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 655)
;
656 }
657
658 return Result;
659}
660
661void DeductionFailureInfo::Destroy() {
662 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
663 case Sema::TDK_Success:
664 case Sema::TDK_Invalid:
665 case Sema::TDK_InstantiationDepth:
666 case Sema::TDK_Incomplete:
667 case Sema::TDK_TooManyArguments:
668 case Sema::TDK_TooFewArguments:
669 case Sema::TDK_InvalidExplicitArguments:
670 case Sema::TDK_CUDATargetMismatch:
671 case Sema::TDK_NonDependentConversionFailure:
672 break;
673
674 case Sema::TDK_Inconsistent:
675 case Sema::TDK_Underqualified:
676 case Sema::TDK_DeducedMismatch:
677 case Sema::TDK_DeducedMismatchNested:
678 case Sema::TDK_NonDeducedMismatch:
679 // FIXME: Destroy the data?
680 Data = nullptr;
681 break;
682
683 case Sema::TDK_SubstitutionFailure:
684 // FIXME: Destroy the template argument list?
685 Data = nullptr;
686 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
687 Diag->~PartialDiagnosticAt();
688 HasDiagnostic = false;
689 }
690 break;
691
692 // Unhandled
693 case Sema::TDK_MiscellaneousDeductionFailure:
694 break;
695 }
696}
697
698PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
699 if (HasDiagnostic)
700 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
701 return nullptr;
702}
703
704TemplateParameter DeductionFailureInfo::getTemplateParameter() {
705 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
706 case Sema::TDK_Success:
707 case Sema::TDK_Invalid:
708 case Sema::TDK_InstantiationDepth:
709 case Sema::TDK_TooManyArguments:
710 case Sema::TDK_TooFewArguments:
711 case Sema::TDK_SubstitutionFailure:
712 case Sema::TDK_DeducedMismatch:
713 case Sema::TDK_DeducedMismatchNested:
714 case Sema::TDK_NonDeducedMismatch:
715 case Sema::TDK_CUDATargetMismatch:
716 case Sema::TDK_NonDependentConversionFailure:
717 return TemplateParameter();
718
719 case Sema::TDK_Incomplete:
720 case Sema::TDK_InvalidExplicitArguments:
721 return TemplateParameter::getFromOpaqueValue(Data);
722
723 case Sema::TDK_Inconsistent:
724 case Sema::TDK_Underqualified:
725 return static_cast<DFIParamWithArguments*>(Data)->Param;
726
727 // Unhandled
728 case Sema::TDK_MiscellaneousDeductionFailure:
729 break;
730 }
731
732 return TemplateParameter();
733}
734
735TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
736 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
737 case Sema::TDK_Success:
738 case Sema::TDK_Invalid:
739 case Sema::TDK_InstantiationDepth:
740 case Sema::TDK_TooManyArguments:
741 case Sema::TDK_TooFewArguments:
742 case Sema::TDK_Incomplete:
743 case Sema::TDK_InvalidExplicitArguments:
744 case Sema::TDK_Inconsistent:
745 case Sema::TDK_Underqualified:
746 case Sema::TDK_NonDeducedMismatch:
747 case Sema::TDK_CUDATargetMismatch:
748 case Sema::TDK_NonDependentConversionFailure:
749 return nullptr;
750
751 case Sema::TDK_DeducedMismatch:
752 case Sema::TDK_DeducedMismatchNested:
753 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
754
755 case Sema::TDK_SubstitutionFailure:
756 return static_cast<TemplateArgumentList*>(Data);
757
758 // Unhandled
759 case Sema::TDK_MiscellaneousDeductionFailure:
760 break;
761 }
762
763 return nullptr;
764}
765
766const TemplateArgument *DeductionFailureInfo::getFirstArg() {
767 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
768 case Sema::TDK_Success:
769 case Sema::TDK_Invalid:
770 case Sema::TDK_InstantiationDepth:
771 case Sema::TDK_Incomplete:
772 case Sema::TDK_TooManyArguments:
773 case Sema::TDK_TooFewArguments:
774 case Sema::TDK_InvalidExplicitArguments:
775 case Sema::TDK_SubstitutionFailure:
776 case Sema::TDK_CUDATargetMismatch:
777 case Sema::TDK_NonDependentConversionFailure:
778 return nullptr;
779
780 case Sema::TDK_Inconsistent:
781 case Sema::TDK_Underqualified:
782 case Sema::TDK_DeducedMismatch:
783 case Sema::TDK_DeducedMismatchNested:
784 case Sema::TDK_NonDeducedMismatch:
785 return &static_cast<DFIArguments*>(Data)->FirstArg;
786
787 // Unhandled
788 case Sema::TDK_MiscellaneousDeductionFailure:
789 break;
790 }
791
792 return nullptr;
793}
794
795const TemplateArgument *DeductionFailureInfo::getSecondArg() {
796 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
797 case Sema::TDK_Success:
798 case Sema::TDK_Invalid:
799 case Sema::TDK_InstantiationDepth:
800 case Sema::TDK_Incomplete:
801 case Sema::TDK_TooManyArguments:
802 case Sema::TDK_TooFewArguments:
803 case Sema::TDK_InvalidExplicitArguments:
804 case Sema::TDK_SubstitutionFailure:
805 case Sema::TDK_CUDATargetMismatch:
806 case Sema::TDK_NonDependentConversionFailure:
807 return nullptr;
808
809 case Sema::TDK_Inconsistent:
810 case Sema::TDK_Underqualified:
811 case Sema::TDK_DeducedMismatch:
812 case Sema::TDK_DeducedMismatchNested:
813 case Sema::TDK_NonDeducedMismatch:
814 return &static_cast<DFIArguments*>(Data)->SecondArg;
815
816 // Unhandled
817 case Sema::TDK_MiscellaneousDeductionFailure:
818 break;
819 }
820
821 return nullptr;
822}
823
824llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
825 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
826 case Sema::TDK_DeducedMismatch:
827 case Sema::TDK_DeducedMismatchNested:
828 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
829
830 default:
831 return llvm::None;
832 }
833}
834
835void OverloadCandidateSet::destroyCandidates() {
836 for (iterator i = begin(), e = end(); i != e; ++i) {
837 for (auto &C : i->Conversions)
838 C.~ImplicitConversionSequence();
839 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
840 i->DeductionFailure.Destroy();
841 }
842}
843
844void OverloadCandidateSet::clear(CandidateSetKind CSK) {
845 destroyCandidates();
846 SlabAllocator.Reset();
847 NumInlineBytesUsed = 0;
848 Candidates.clear();
849 Functions.clear();
850 Kind = CSK;
851}
852
853namespace {
854 class UnbridgedCastsSet {
855 struct Entry {
856 Expr **Addr;
857 Expr *Saved;
858 };
859 SmallVector<Entry, 2> Entries;
860
861 public:
862 void save(Sema &S, Expr *&E) {
863 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))(static_cast <bool> (E->hasPlaceholderType(BuiltinType
::ARCUnbridgedCast)) ? void (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 863, __extension__ __PRETTY_FUNCTION__))
;
864 Entry entry = { &E, E };
865 Entries.push_back(entry);
866 E = S.stripARCUnbridgedCast(E);
867 }
868
869 void restore() {
870 for (SmallVectorImpl<Entry>::iterator
871 i = Entries.begin(), e = Entries.end(); i != e; ++i)
872 *i->Addr = i->Saved;
873 }
874 };
875}
876
877/// checkPlaceholderForOverload - Do any interesting placeholder-like
878/// preprocessing on the given expression.
879///
880/// \param unbridgedCasts a collection to which to add unbridged casts;
881/// without this, they will be immediately diagnosed as errors
882///
883/// Return true on unrecoverable error.
884static bool
885checkPlaceholderForOverload(Sema &S, Expr *&E,
886 UnbridgedCastsSet *unbridgedCasts = nullptr) {
887 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
888 // We can't handle overloaded expressions here because overload
889 // resolution might reasonably tweak them.
890 if (placeholder->getKind() == BuiltinType::Overload) return false;
891
892 // If the context potentially accepts unbridged ARC casts, strip
893 // the unbridged cast and add it to the collection for later restoration.
894 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
895 unbridgedCasts) {
896 unbridgedCasts->save(S, E);
897 return false;
898 }
899
900 // Go ahead and check everything else.
901 ExprResult result = S.CheckPlaceholderExpr(E);
902 if (result.isInvalid())
903 return true;
904
905 E = result.get();
906 return false;
907 }
908
909 // Nothing to do.
910 return false;
911}
912
913/// checkArgPlaceholdersForOverload - Check a set of call operands for
914/// placeholders.
915static bool checkArgPlaceholdersForOverload(Sema &S,
916 MultiExprArg Args,
917 UnbridgedCastsSet &unbridged) {
918 for (unsigned i = 0, e = Args.size(); i != e; ++i)
919 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
920 return true;
921
922 return false;
923}
924
925/// Determine whether the given New declaration is an overload of the
926/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
927/// New and Old cannot be overloaded, e.g., if New has the same signature as
928/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
929/// functions (or function templates) at all. When it does return Ovl_Match or
930/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
931/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
932/// declaration.
933///
934/// Example: Given the following input:
935///
936/// void f(int, float); // #1
937/// void f(int, int); // #2
938/// int f(int, int); // #3
939///
940/// When we process #1, there is no previous declaration of "f", so IsOverload
941/// will not be used.
942///
943/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
944/// the parameter types, we see that #1 and #2 are overloaded (since they have
945/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
946/// unchanged.
947///
948/// When we process #3, Old is an overload set containing #1 and #2. We compare
949/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
950/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
951/// functions are not part of the signature), IsOverload returns Ovl_Match and
952/// MatchedDecl will be set to point to the FunctionDecl for #2.
953///
954/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
955/// by a using declaration. The rules for whether to hide shadow declarations
956/// ignore some properties which otherwise figure into a function template's
957/// signature.
958Sema::OverloadKind
959Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
960 NamedDecl *&Match, bool NewIsUsingDecl) {
961 for (LookupResult::iterator I = Old.begin(), E = Old.end();
962 I != E; ++I) {
963 NamedDecl *OldD = *I;
964
965 bool OldIsUsingDecl = false;
966 if (isa<UsingShadowDecl>(OldD)) {
967 OldIsUsingDecl = true;
968
969 // We can always introduce two using declarations into the same
970 // context, even if they have identical signatures.
971 if (NewIsUsingDecl) continue;
972
973 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
974 }
975
976 // A using-declaration does not conflict with another declaration
977 // if one of them is hidden.
978 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
979 continue;
980
981 // If either declaration was introduced by a using declaration,
982 // we'll need to use slightly different rules for matching.
983 // Essentially, these rules are the normal rules, except that
984 // function templates hide function templates with different
985 // return types or template parameter lists.
986 bool UseMemberUsingDeclRules =
987 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
988 !New->getFriendObjectKind();
989
990 if (FunctionDecl *OldF = OldD->getAsFunction()) {
991 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
992 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
993 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
994 continue;
995 }
996
997 if (!isa<FunctionTemplateDecl>(OldD) &&
998 !shouldLinkPossiblyHiddenDecl(*I, New))
999 continue;
1000
1001 Match = *I;
1002 return Ovl_Match;
1003 }
1004
1005 // Builtins that have custom typechecking or have a reference should
1006 // not be overloadable or redeclarable.
1007 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1008 Match = *I;
1009 return Ovl_NonFunction;
1010 }
1011 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1012 // We can overload with these, which can show up when doing
1013 // redeclaration checks for UsingDecls.
1014 assert(Old.getLookupKind() == LookupUsingDeclName)(static_cast <bool> (Old.getLookupKind() == LookupUsingDeclName
) ? void (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1014, __extension__ __PRETTY_FUNCTION__))
;
1015 } else if (isa<TagDecl>(OldD)) {
1016 // We can always overload with tags by hiding them.
1017 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1018 // Optimistically assume that an unresolved using decl will
1019 // overload; if it doesn't, we'll have to diagnose during
1020 // template instantiation.
1021 //
1022 // Exception: if the scope is dependent and this is not a class
1023 // member, the using declaration can only introduce an enumerator.
1024 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1025 Match = *I;
1026 return Ovl_NonFunction;
1027 }
1028 } else {
1029 // (C++ 13p1):
1030 // Only function declarations can be overloaded; object and type
1031 // declarations cannot be overloaded.
1032 Match = *I;
1033 return Ovl_NonFunction;
1034 }
1035 }
1036
1037 return Ovl_Overload;
1038}
1039
1040bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1041 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1042 // C++ [basic.start.main]p2: This function shall not be overloaded.
1043 if (New->isMain())
1044 return false;
1045
1046 // MSVCRT user defined entry points cannot be overloaded.
1047 if (New->isMSVCRTEntryPoint())
1048 return false;
1049
1050 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1051 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1052
1053 // C++ [temp.fct]p2:
1054 // A function template can be overloaded with other function templates
1055 // and with normal (non-template) functions.
1056 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1057 return true;
1058
1059 // Is the function New an overload of the function Old?
1060 QualType OldQType = Context.getCanonicalType(Old->getType());
1061 QualType NewQType = Context.getCanonicalType(New->getType());
1062
1063 // Compare the signatures (C++ 1.3.10) of the two functions to
1064 // determine whether they are overloads. If we find any mismatch
1065 // in the signature, they are overloads.
1066
1067 // If either of these functions is a K&R-style function (no
1068 // prototype), then we consider them to have matching signatures.
1069 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1070 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1071 return false;
1072
1073 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1074 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1075
1076 // The signature of a function includes the types of its
1077 // parameters (C++ 1.3.10), which includes the presence or absence
1078 // of the ellipsis; see C++ DR 357).
1079 if (OldQType != NewQType &&
1080 (OldType->getNumParams() != NewType->getNumParams() ||
1081 OldType->isVariadic() != NewType->isVariadic() ||
1082 !FunctionParamTypesAreEqual(OldType, NewType)))
1083 return true;
1084
1085 // C++ [temp.over.link]p4:
1086 // The signature of a function template consists of its function
1087 // signature, its return type and its template parameter list. The names
1088 // of the template parameters are significant only for establishing the
1089 // relationship between the template parameters and the rest of the
1090 // signature.
1091 //
1092 // We check the return type and template parameter lists for function
1093 // templates first; the remaining checks follow.
1094 //
1095 // However, we don't consider either of these when deciding whether
1096 // a member introduced by a shadow declaration is hidden.
1097 if (!UseMemberUsingDeclRules && NewTemplate &&
1098 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1099 OldTemplate->getTemplateParameters(),
1100 false, TPL_TemplateMatch) ||
1101 OldType->getReturnType() != NewType->getReturnType()))
1102 return true;
1103
1104 // If the function is a class member, its signature includes the
1105 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1106 //
1107 // As part of this, also check whether one of the member functions
1108 // is static, in which case they are not overloads (C++
1109 // 13.1p2). While not part of the definition of the signature,
1110 // this check is important to determine whether these functions
1111 // can be overloaded.
1112 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1113 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1114 if (OldMethod && NewMethod &&
1115 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1116 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1117 if (!UseMemberUsingDeclRules &&
1118 (OldMethod->getRefQualifier() == RQ_None ||
1119 NewMethod->getRefQualifier() == RQ_None)) {
1120 // C++0x [over.load]p2:
1121 // - Member function declarations with the same name and the same
1122 // parameter-type-list as well as member function template
1123 // declarations with the same name, the same parameter-type-list, and
1124 // the same template parameter lists cannot be overloaded if any of
1125 // them, but not all, have a ref-qualifier (8.3.5).
1126 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1127 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1128 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1129 }
1130 return true;
1131 }
1132
1133 // We may not have applied the implicit const for a constexpr member
1134 // function yet (because we haven't yet resolved whether this is a static
1135 // or non-static member function). Add it now, on the assumption that this
1136 // is a redeclaration of OldMethod.
1137 unsigned OldQuals = OldMethod->getTypeQualifiers();
1138 unsigned NewQuals = NewMethod->getTypeQualifiers();
1139 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1140 !isa<CXXConstructorDecl>(NewMethod))
1141 NewQuals |= Qualifiers::Const;
1142
1143 // We do not allow overloading based off of '__restrict'.
1144 OldQuals &= ~Qualifiers::Restrict;
1145 NewQuals &= ~Qualifiers::Restrict;
1146 if (OldQuals != NewQuals)
1147 return true;
1148 }
1149
1150 // Though pass_object_size is placed on parameters and takes an argument, we
1151 // consider it to be a function-level modifier for the sake of function
1152 // identity. Either the function has one or more parameters with
1153 // pass_object_size or it doesn't.
1154 if (functionHasPassObjectSizeParams(New) !=
1155 functionHasPassObjectSizeParams(Old))
1156 return true;
1157
1158 // enable_if attributes are an order-sensitive part of the signature.
1159 for (specific_attr_iterator<EnableIfAttr>
1160 NewI = New->specific_attr_begin<EnableIfAttr>(),
1161 NewE = New->specific_attr_end<EnableIfAttr>(),
1162 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1163 OldE = Old->specific_attr_end<EnableIfAttr>();
1164 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1165 if (NewI == NewE || OldI == OldE)
1166 return true;
1167 llvm::FoldingSetNodeID NewID, OldID;
1168 NewI->getCond()->Profile(NewID, Context, true);
1169 OldI->getCond()->Profile(OldID, Context, true);
1170 if (NewID != OldID)
1171 return true;
1172 }
1173
1174 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1175 // Don't allow overloading of destructors. (In theory we could, but it
1176 // would be a giant change to clang.)
1177 if (isa<CXXDestructorDecl>(New))
1178 return false;
1179
1180 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1181 OldTarget = IdentifyCUDATarget(Old);
1182 if (NewTarget == CFT_InvalidTarget)
1183 return false;
1184
1185 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.")(static_cast <bool> ((OldTarget != CFT_InvalidTarget) &&
"Unexpected invalid target.") ? void (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1185, __extension__ __PRETTY_FUNCTION__))
;
1186
1187 // Allow overloading of functions with same signature and different CUDA
1188 // target attributes.
1189 return NewTarget != OldTarget;
1190 }
1191
1192 // The signatures match; this is not an overload.
1193 return false;
1194}
1195
1196/// Checks availability of the function depending on the current
1197/// function context. Inside an unavailable function, unavailability is ignored.
1198///
1199/// \returns true if \arg FD is unavailable and current context is inside
1200/// an available function, false otherwise.
1201bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1202 if (!FD->isUnavailable())
1203 return false;
1204
1205 // Walk up the context of the caller.
1206 Decl *C = cast<Decl>(CurContext);
1207 do {
1208 if (C->isUnavailable())
1209 return false;
1210 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1211 return true;
1212}
1213
1214/// Tries a user-defined conversion from From to ToType.
1215///
1216/// Produces an implicit conversion sequence for when a standard conversion
1217/// is not an option. See TryImplicitConversion for more information.
1218static ImplicitConversionSequence
1219TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1220 bool SuppressUserConversions,
1221 bool AllowExplicit,
1222 bool InOverloadResolution,
1223 bool CStyle,
1224 bool AllowObjCWritebackConversion,
1225 bool AllowObjCConversionOnExplicit) {
1226 ImplicitConversionSequence ICS;
1227
1228 if (SuppressUserConversions) {
1229 // We're not in the case above, so there is no conversion that
1230 // we can perform.
1231 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1232 return ICS;
1233 }
1234
1235 // Attempt user-defined conversion.
1236 OverloadCandidateSet Conversions(From->getExprLoc(),
1237 OverloadCandidateSet::CSK_Normal);
1238 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1239 Conversions, AllowExplicit,
1240 AllowObjCConversionOnExplicit)) {
1241 case OR_Success:
1242 case OR_Deleted:
1243 ICS.setUserDefined();
1244 // C++ [over.ics.user]p4:
1245 // A conversion of an expression of class type to the same class
1246 // type is given Exact Match rank, and a conversion of an
1247 // expression of class type to a base class of that type is
1248 // given Conversion rank, in spite of the fact that a copy
1249 // constructor (i.e., a user-defined conversion function) is
1250 // called for those cases.
1251 if (CXXConstructorDecl *Constructor
1252 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1253 QualType FromCanon
1254 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1255 QualType ToCanon
1256 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1257 if (Constructor->isCopyConstructor() &&
1258 (FromCanon == ToCanon ||
1259 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1260 // Turn this into a "standard" conversion sequence, so that it
1261 // gets ranked with standard conversion sequences.
1262 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1263 ICS.setStandard();
1264 ICS.Standard.setAsIdentityConversion();
1265 ICS.Standard.setFromType(From->getType());
1266 ICS.Standard.setAllToTypes(ToType);
1267 ICS.Standard.CopyConstructor = Constructor;
1268 ICS.Standard.FoundCopyConstructor = Found;
1269 if (ToCanon != FromCanon)
1270 ICS.Standard.Second = ICK_Derived_To_Base;
1271 }
1272 }
1273 break;
1274
1275 case OR_Ambiguous:
1276 ICS.setAmbiguous();
1277 ICS.Ambiguous.setFromType(From->getType());
1278 ICS.Ambiguous.setToType(ToType);
1279 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1280 Cand != Conversions.end(); ++Cand)
1281 if (Cand->Viable)
1282 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1283 break;
1284
1285 // Fall through.
1286 case OR_No_Viable_Function:
1287 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1288 break;
1289 }
1290
1291 return ICS;
1292}
1293
1294/// TryImplicitConversion - Attempt to perform an implicit conversion
1295/// from the given expression (Expr) to the given type (ToType). This
1296/// function returns an implicit conversion sequence that can be used
1297/// to perform the initialization. Given
1298///
1299/// void f(float f);
1300/// void g(int i) { f(i); }
1301///
1302/// this routine would produce an implicit conversion sequence to
1303/// describe the initialization of f from i, which will be a standard
1304/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1305/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1306//
1307/// Note that this routine only determines how the conversion can be
1308/// performed; it does not actually perform the conversion. As such,
1309/// it will not produce any diagnostics if no conversion is available,
1310/// but will instead return an implicit conversion sequence of kind
1311/// "BadConversion".
1312///
1313/// If @p SuppressUserConversions, then user-defined conversions are
1314/// not permitted.
1315/// If @p AllowExplicit, then explicit user-defined conversions are
1316/// permitted.
1317///
1318/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1319/// writeback conversion, which allows __autoreleasing id* parameters to
1320/// be initialized with __strong id* or __weak id* arguments.
1321static ImplicitConversionSequence
1322TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1323 bool SuppressUserConversions,
1324 bool AllowExplicit,
1325 bool InOverloadResolution,
1326 bool CStyle,
1327 bool AllowObjCWritebackConversion,
1328 bool AllowObjCConversionOnExplicit) {
1329 ImplicitConversionSequence ICS;
1330 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1331 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1332 ICS.setStandard();
1333 return ICS;
1334 }
1335
1336 if (!S.getLangOpts().CPlusPlus) {
1337 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1338 return ICS;
1339 }
1340
1341 // C++ [over.ics.user]p4:
1342 // A conversion of an expression of class type to the same class
1343 // type is given Exact Match rank, and a conversion of an
1344 // expression of class type to a base class of that type is
1345 // given Conversion rank, in spite of the fact that a copy/move
1346 // constructor (i.e., a user-defined conversion function) is
1347 // called for those cases.
1348 QualType FromType = From->getType();
1349 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1350 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1351 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1352 ICS.setStandard();
1353 ICS.Standard.setAsIdentityConversion();
1354 ICS.Standard.setFromType(FromType);
1355 ICS.Standard.setAllToTypes(ToType);
1356
1357 // We don't actually check at this point whether there is a valid
1358 // copy/move constructor, since overloading just assumes that it
1359 // exists. When we actually perform initialization, we'll find the
1360 // appropriate constructor to copy the returned object, if needed.
1361 ICS.Standard.CopyConstructor = nullptr;
1362
1363 // Determine whether this is considered a derived-to-base conversion.
1364 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1365 ICS.Standard.Second = ICK_Derived_To_Base;
1366
1367 return ICS;
1368 }
1369
1370 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1371 AllowExplicit, InOverloadResolution, CStyle,
1372 AllowObjCWritebackConversion,
1373 AllowObjCConversionOnExplicit);
1374}
1375
1376ImplicitConversionSequence
1377Sema::TryImplicitConversion(Expr *From, QualType ToType,
1378 bool SuppressUserConversions,
1379 bool AllowExplicit,
1380 bool InOverloadResolution,
1381 bool CStyle,
1382 bool AllowObjCWritebackConversion) {
1383 return ::TryImplicitConversion(*this, From, ToType,
1384 SuppressUserConversions, AllowExplicit,
1385 InOverloadResolution, CStyle,
1386 AllowObjCWritebackConversion,
1387 /*AllowObjCConversionOnExplicit=*/false);
1388}
1389
1390/// PerformImplicitConversion - Perform an implicit conversion of the
1391/// expression From to the type ToType. Returns the
1392/// converted expression. Flavor is the kind of conversion we're
1393/// performing, used in the error message. If @p AllowExplicit,
1394/// explicit user-defined conversions are permitted.
1395ExprResult
1396Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1397 AssignmentAction Action, bool AllowExplicit) {
1398 ImplicitConversionSequence ICS;
1399 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1400}
1401
1402ExprResult
1403Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1404 AssignmentAction Action, bool AllowExplicit,
1405 ImplicitConversionSequence& ICS) {
1406 if (checkPlaceholderForOverload(*this, From))
1407 return ExprError();
1408
1409 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1410 bool AllowObjCWritebackConversion
1411 = getLangOpts().ObjCAutoRefCount &&
1412 (Action == AA_Passing || Action == AA_Sending);
1413 if (getLangOpts().ObjC1)
1414 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1415 ToType, From->getType(), From);
1416 ICS = ::TryImplicitConversion(*this, From, ToType,
1417 /*SuppressUserConversions=*/false,
1418 AllowExplicit,
1419 /*InOverloadResolution=*/false,
1420 /*CStyle=*/false,
1421 AllowObjCWritebackConversion,
1422 /*AllowObjCConversionOnExplicit=*/false);
1423 return PerformImplicitConversion(From, ToType, ICS, Action);
1424}
1425
1426/// Determine whether the conversion from FromType to ToType is a valid
1427/// conversion that strips "noexcept" or "noreturn" off the nested function
1428/// type.
1429bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1430 QualType &ResultTy) {
1431 if (Context.hasSameUnqualifiedType(FromType, ToType))
1432 return false;
1433
1434 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1435 // or F(t noexcept) -> F(t)
1436 // where F adds one of the following at most once:
1437 // - a pointer
1438 // - a member pointer
1439 // - a block pointer
1440 // Changes here need matching changes in FindCompositePointerType.
1441 CanQualType CanTo = Context.getCanonicalType(ToType);
1442 CanQualType CanFrom = Context.getCanonicalType(FromType);
1443 Type::TypeClass TyClass = CanTo->getTypeClass();
1444 if (TyClass != CanFrom->getTypeClass()) return false;
1445 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1446 if (TyClass == Type::Pointer) {
1447 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1448 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1449 } else if (TyClass == Type::BlockPointer) {
1450 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1451 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1452 } else if (TyClass == Type::MemberPointer) {
1453 auto ToMPT = CanTo.getAs<MemberPointerType>();
1454 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1455 // A function pointer conversion cannot change the class of the function.
1456 if (ToMPT->getClass() != FromMPT->getClass())
1457 return false;
1458 CanTo = ToMPT->getPointeeType();
1459 CanFrom = FromMPT->getPointeeType();
1460 } else {
1461 return false;
1462 }
1463
1464 TyClass = CanTo->getTypeClass();
1465 if (TyClass != CanFrom->getTypeClass()) return false;
1466 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1467 return false;
1468 }
1469
1470 const auto *FromFn = cast<FunctionType>(CanFrom);
1471 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1472
1473 const auto *ToFn = cast<FunctionType>(CanTo);
1474 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1475
1476 bool Changed = false;
1477
1478 // Drop 'noreturn' if not present in target type.
1479 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1480 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1481 Changed = true;
1482 }
1483
1484 // Drop 'noexcept' if not present in target type.
1485 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1486 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1487 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1488 FromFn = cast<FunctionType>(
1489 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1490 EST_None)
1491 .getTypePtr());
1492 Changed = true;
1493 }
1494
1495 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1496 // only if the ExtParameterInfo lists of the two function prototypes can be
1497 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1498 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1499 bool CanUseToFPT, CanUseFromFPT;
1500 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1501 CanUseFromFPT, NewParamInfos) &&
1502 CanUseToFPT && !CanUseFromFPT) {
1503 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1504 ExtInfo.ExtParameterInfos =
1505 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1506 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1507 FromFPT->getParamTypes(), ExtInfo);
1508 FromFn = QT->getAs<FunctionType>();
1509 Changed = true;
1510 }
1511 }
1512
1513 if (!Changed)
1514 return false;
1515
1516 assert(QualType(FromFn, 0).isCanonical())(static_cast <bool> (QualType(FromFn, 0).isCanonical())
? void (0) : __assert_fail ("QualType(FromFn, 0).isCanonical()"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1516, __extension__ __PRETTY_FUNCTION__))
;
1517 if (QualType(FromFn, 0) != CanTo) return false;
1518
1519 ResultTy = ToType;
1520 return true;
1521}
1522
1523/// Determine whether the conversion from FromType to ToType is a valid
1524/// vector conversion.
1525///
1526/// \param ICK Will be set to the vector conversion kind, if this is a vector
1527/// conversion.
1528static bool IsVectorConversion(Sema &S, QualType FromType,
1529 QualType ToType, ImplicitConversionKind &ICK) {
1530 // We need at least one of these types to be a vector type to have a vector
1531 // conversion.
1532 if (!ToType->isVectorType() && !FromType->isVectorType())
1533 return false;
1534
1535 // Identical types require no conversions.
1536 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1537 return false;
1538
1539 // There are no conversions between extended vector types, only identity.
1540 if (ToType->isExtVectorType()) {
1541 // There are no conversions between extended vector types other than the
1542 // identity conversion.
1543 if (FromType->isExtVectorType())
1544 return false;
1545
1546 // Vector splat from any arithmetic type to a vector.
1547 if (FromType->isArithmeticType()) {
1548 ICK = ICK_Vector_Splat;
1549 return true;
1550 }
1551 }
1552
1553 // We can perform the conversion between vector types in the following cases:
1554 // 1)vector types are equivalent AltiVec and GCC vector types
1555 // 2)lax vector conversions are permitted and the vector types are of the
1556 // same size
1557 if (ToType->isVectorType() && FromType->isVectorType()) {
1558 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1559 S.isLaxVectorConversion(FromType, ToType)) {
1560 ICK = ICK_Vector_Conversion;
1561 return true;
1562 }
1563 }
1564
1565 return false;
1566}
1567
1568static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1569 bool InOverloadResolution,
1570 StandardConversionSequence &SCS,
1571 bool CStyle);
1572
1573/// IsStandardConversion - Determines whether there is a standard
1574/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1575/// expression From to the type ToType. Standard conversion sequences
1576/// only consider non-class types; for conversions that involve class
1577/// types, use TryImplicitConversion. If a conversion exists, SCS will
1578/// contain the standard conversion sequence required to perform this
1579/// conversion and this routine will return true. Otherwise, this
1580/// routine will return false and the value of SCS is unspecified.
1581static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1582 bool InOverloadResolution,
1583 StandardConversionSequence &SCS,
1584 bool CStyle,
1585 bool AllowObjCWritebackConversion) {
1586 QualType FromType = From->getType();
1587
1588 // Standard conversions (C++ [conv])
1589 SCS.setAsIdentityConversion();
1590 SCS.IncompatibleObjC = false;
1591 SCS.setFromType(FromType);
1592 SCS.CopyConstructor = nullptr;
1593
1594 // There are no standard conversions for class types in C++, so
1595 // abort early. When overloading in C, however, we do permit them.
1596 if (S.getLangOpts().CPlusPlus &&
1597 (FromType->isRecordType() || ToType->isRecordType()))
1598 return false;
1599
1600 // The first conversion can be an lvalue-to-rvalue conversion,
1601 // array-to-pointer conversion, or function-to-pointer conversion
1602 // (C++ 4p1).
1603
1604 if (FromType == S.Context.OverloadTy) {
1605 DeclAccessPair AccessPair;
1606 if (FunctionDecl *Fn
1607 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1608 AccessPair)) {
1609 // We were able to resolve the address of the overloaded function,
1610 // so we can convert to the type of that function.
1611 FromType = Fn->getType();
1612 SCS.setFromType(FromType);
1613
1614 // we can sometimes resolve &foo<int> regardless of ToType, so check
1615 // if the type matches (identity) or we are converting to bool
1616 if (!S.Context.hasSameUnqualifiedType(
1617 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1618 QualType resultTy;
1619 // if the function type matches except for [[noreturn]], it's ok
1620 if (!S.IsFunctionConversion(FromType,
1621 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1622 // otherwise, only a boolean conversion is standard
1623 if (!ToType->isBooleanType())
1624 return false;
1625 }
1626
1627 // Check if the "from" expression is taking the address of an overloaded
1628 // function and recompute the FromType accordingly. Take advantage of the
1629 // fact that non-static member functions *must* have such an address-of
1630 // expression.
1631 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1632 if (Method && !Method->isStatic()) {
1633 assert(isa<UnaryOperator>(From->IgnoreParens()) &&(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1634, __extension__ __PRETTY_FUNCTION__))
1634 "Non-unary operator on non-static member address")(static_cast <bool> (isa<UnaryOperator>(From->
IgnoreParens()) && "Non-unary operator on non-static member address"
) ? void (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1634, __extension__ __PRETTY_FUNCTION__))
;
1635 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1637, __extension__ __PRETTY_FUNCTION__))
1636 == UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1637, __extension__ __PRETTY_FUNCTION__))
1637 "Non-address-of operator on non-static member address")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1637, __extension__ __PRETTY_FUNCTION__))
;
1638 const Type *ClassType
1639 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1640 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1641 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1642 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
1643 UO_AddrOf &&(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
1644 "Non-address-of operator for overloaded function expression")(static_cast <bool> (cast<UnaryOperator>(From->
IgnoreParens())->getOpcode() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? void (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
;
1645 FromType = S.Context.getPointerType(FromType);
1646 }
1647
1648 // Check that we've computed the proper type after overload resolution.
1649 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1650 // be calling it from within an NDEBUG block.
1651 assert(S.Context.hasSameType((static_cast <bool> (S.Context.hasSameType( FromType, S
.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType
())) ? void (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1653, __extension__ __PRETTY_FUNCTION__))
1652 FromType,(static_cast <bool> (S.Context.hasSameType( FromType, S
.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType
())) ? void (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1653, __extension__ __PRETTY_FUNCTION__))
1653 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))(static_cast <bool> (S.Context.hasSameType( FromType, S
.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType
())) ? void (0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 1653, __extension__ __PRETTY_FUNCTION__))
;
1654 } else {
1655 return false;
1656 }
1657 }
1658 // Lvalue-to-rvalue conversion (C++11 4.1):
1659 // A glvalue (3.10) of a non-function, non-array type T can
1660 // be converted to a prvalue.
1661 bool argIsLValue = From->isGLValue();
1662 if (argIsLValue &&
1663 !FromType->isFunctionType() && !FromType->isArrayType() &&
1664 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1665 SCS.First = ICK_Lvalue_To_Rvalue;
1666
1667 // C11 6.3.2.1p2:
1668 // ... if the lvalue has atomic type, the value has the non-atomic version
1669 // of the type of the lvalue ...
1670 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1671 FromType = Atomic->getValueType();
1672
1673 // If T is a non-class type, the type of the rvalue is the
1674 // cv-unqualified version of T. Otherwise, the type of the rvalue
1675 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1676 // just strip the qualifiers because they don't matter.
1677 FromType = FromType.getUnqualifiedType();
1678 } else if (FromType->isArrayType()) {
1679 // Array-to-pointer conversion (C++ 4.2)
1680 SCS.First = ICK_Array_To_Pointer;
1681
1682 // An lvalue or rvalue of type "array of N T" or "array of unknown
1683 // bound of T" can be converted to an rvalue of type "pointer to
1684 // T" (C++ 4.2p1).
1685 FromType = S.Context.getArrayDecayedType(FromType);
1686
1687 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1688 // This conversion is deprecated in C++03 (D.4)
1689 SCS.DeprecatedStringLiteralToCharPtr = true;
1690
1691 // For the purpose of ranking in overload resolution
1692 // (13.3.3.1.1), this conversion is considered an
1693 // array-to-pointer conversion followed by a qualification
1694 // conversion (4.4). (C++ 4.2p2)
1695 SCS.Second = ICK_Identity;
1696 SCS.Third = ICK_Qualification;
1697 SCS.QualificationIncludesObjCLifetime = false;
1698 SCS.setAllToTypes(FromType);
1699 return true;
1700 }
1701 } else if (FromType->isFunctionType() && argIsLValue) {
1702 // Function-to-pointer conversion (C++ 4.3).
1703 SCS.First = ICK_Function_To_Pointer;
1704
1705 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1706 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1707 if (!S.checkAddressOfFunctionIsAvailable(FD))
1708 return false;
1709
1710 // An lvalue of function type T can be converted to an rvalue of
1711 // type "pointer to T." The result is a pointer to the
1712 // function. (C++ 4.3p1).
1713 FromType = S.Context.getPointerType(FromType);
1714 } else {
1715 // We don't require any conversions for the first step.
1716 SCS.First = ICK_Identity;
1717 }
1718 SCS.setToType(0, FromType);
1719
1720 // The second conversion can be an integral promotion, floating
1721 // point promotion, integral conversion, floating point conversion,
1722 // floating-integral conversion, pointer conversion,
1723 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1724 // For overloading in C, this can also be a "compatible-type"
1725 // conversion.
1726 bool IncompatibleObjC = false;
1727 ImplicitConversionKind SecondICK = ICK_Identity;
1728 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1729 // The unqualified versions of the types are the same: there's no
1730 // conversion to do.
1731 SCS.Second = ICK_Identity;
1732 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1733 // Integral promotion (C++ 4.5).
1734 SCS.Second = ICK_Integral_Promotion;
1735 FromType = ToType.getUnqualifiedType();
1736 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1737 // Floating point promotion (C++ 4.6).
1738 SCS.Second = ICK_Floating_Promotion;
1739 FromType = ToType.getUnqualifiedType();
1740 } else if (S.IsComplexPromotion(FromType, ToType)) {
1741 // Complex promotion (Clang extension)
1742 SCS.Second = ICK_Complex_Promotion;
1743 FromType = ToType.getUnqualifiedType();
1744 } else if (ToType->isBooleanType() &&
1745 (FromType->isArithmeticType() ||
1746 FromType->isAnyPointerType() ||
1747 FromType->isBlockPointerType() ||
1748 FromType->isMemberPointerType() ||
1749 FromType->isNullPtrType())) {
1750 // Boolean conversions (C++ 4.12).
1751 SCS.Second = ICK_Boolean_Conversion;
1752 FromType = S.Context.BoolTy;
1753 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1754 ToType->isIntegralType(S.Context)) {
1755 // Integral conversions (C++ 4.7).
1756 SCS.Second = ICK_Integral_Conversion;
1757 FromType = ToType.getUnqualifiedType();
1758 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1759 // Complex conversions (C99 6.3.1.6)
1760 SCS.Second = ICK_Complex_Conversion;
1761 FromType = ToType.getUnqualifiedType();
1762 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1763 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1764 // Complex-real conversions (C99 6.3.1.7)
1765 SCS.Second = ICK_Complex_Real;
1766 FromType = ToType.getUnqualifiedType();
1767 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1768 // FIXME: disable conversions between long double and __float128 if
1769 // their representation is different until there is back end support
1770 // We of course allow this conversion if long double is really double.
1771 if (&S.Context.getFloatTypeSemantics(FromType) !=
1772 &S.Context.getFloatTypeSemantics(ToType)) {
1773 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1774 ToType == S.Context.LongDoubleTy) ||
1775 (FromType == S.Context.LongDoubleTy &&
1776 ToType == S.Context.Float128Ty));
1777 if (Float128AndLongDouble &&
1778 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1779 &llvm::APFloat::PPCDoubleDouble()))
1780 return false;
1781 }
1782 // Floating point conversions (C++ 4.8).
1783 SCS.Second = ICK_Floating_Conversion;
1784 FromType = ToType.getUnqualifiedType();
1785 } else if ((FromType->isRealFloatingType() &&
1786 ToType->isIntegralType(S.Context)) ||
1787 (FromType->isIntegralOrUnscopedEnumerationType() &&
1788 ToType->isRealFloatingType())) {
1789 // Floating-integral conversions (C++ 4.9).
1790 SCS.Second = ICK_Floating_Integral;
1791 FromType = ToType.getUnqualifiedType();
1792 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1793 SCS.Second = ICK_Block_Pointer_Conversion;
1794 } else if (AllowObjCWritebackConversion &&
1795 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1796 SCS.Second = ICK_Writeback_Conversion;
1797 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1798 FromType, IncompatibleObjC)) {
1799 // Pointer conversions (C++ 4.10).
1800 SCS.Second = ICK_Pointer_Conversion;
1801 SCS.IncompatibleObjC = IncompatibleObjC;
1802 FromType = FromType.getUnqualifiedType();
1803 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1804 InOverloadResolution, FromType)) {
1805 // Pointer to member conversions (4.11).
1806 SCS.Second = ICK_Pointer_Member;
1807 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1808 SCS.Second = SecondICK;
1809 FromType = ToType.getUnqualifiedType();
1810 } else if (!S.getLangOpts().CPlusPlus &&
1811 S.Context.typesAreCompatible(ToType, FromType)) {
1812 // Compatible conversions (Clang extension for C function overloading)
1813 SCS.Second = ICK_Compatible_Conversion;
1814 FromType = ToType.getUnqualifiedType();
1815 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1816 InOverloadResolution,
1817 SCS, CStyle)) {
1818 SCS.Second = ICK_TransparentUnionConversion;
1819 FromType = ToType;
1820 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1821 CStyle)) {
1822 // tryAtomicConversion has updated the standard conversion sequence
1823 // appropriately.
1824 return true;
1825 } else if (ToType->isEventT() &&
1826 From->isIntegerConstantExpr(S.getASTContext()) &&
1827 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1828 SCS.Second = ICK_Zero_Event_Conversion;
1829 FromType = ToType;
1830 } else if (ToType->isQueueT() &&
1831 From->isIntegerConstantExpr(S.getASTContext()) &&
1832 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1833 SCS.Second = ICK_Zero_Queue_Conversion;
1834 FromType = ToType;
1835 } else {
1836 // No second conversion required.
1837 SCS.Second = ICK_Identity;
1838 }
1839 SCS.setToType(1, FromType);
1840
1841 // The third conversion can be a function pointer conversion or a
1842 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1843 bool ObjCLifetimeConversion;
1844 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1845 // Function pointer conversions (removing 'noexcept') including removal of
1846 // 'noreturn' (Clang extension).
1847 SCS.Third = ICK_Function_Conversion;
1848 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1849 ObjCLifetimeConversion)) {
1850 SCS.Third = ICK_Qualification;
1851 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1852 FromType = ToType;
1853 } else {
1854 // No conversion required
1855 SCS.Third = ICK_Identity;
1856 }
1857
1858 // C++ [over.best.ics]p6:
1859 // [...] Any difference in top-level cv-qualification is
1860 // subsumed by the initialization itself and does not constitute
1861 // a conversion. [...]
1862 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1863 QualType CanonTo = S.Context.getCanonicalType(ToType);
1864 if (CanonFrom.getLocalUnqualifiedType()
1865 == CanonTo.getLocalUnqualifiedType() &&
1866 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1867 FromType = ToType;
1868 CanonFrom = CanonTo;
1869 }
1870
1871 SCS.setToType(2, FromType);
1872
1873 if (CanonFrom == CanonTo)
1874 return true;
1875
1876 // If we have not converted the argument type to the parameter type,
1877 // this is a bad conversion sequence, unless we're resolving an overload in C.
1878 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1879 return false;
1880
1881 ExprResult ER = ExprResult{From};
1882 Sema::AssignConvertType Conv =
1883 S.CheckSingleAssignmentConstraints(ToType, ER,
1884 /*Diagnose=*/false,
1885 /*DiagnoseCFAudited=*/false,
1886 /*ConvertRHS=*/false);
1887 ImplicitConversionKind SecondConv;
1888 switch (Conv) {
1889 case Sema::Compatible:
1890 SecondConv = ICK_C_Only_Conversion;
1891 break;
1892 // For our purposes, discarding qualifiers is just as bad as using an
1893 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1894 // qualifiers, as well.
1895 case Sema::CompatiblePointerDiscardsQualifiers:
1896 case Sema::IncompatiblePointer:
1897 case Sema::IncompatiblePointerSign:
1898 SecondConv = ICK_Incompatible_Pointer_Conversion;
1899 break;
1900 default:
1901 return false;
1902 }
1903
1904 // First can only be an lvalue conversion, so we pretend that this was the
1905 // second conversion. First should already be valid from earlier in the
1906 // function.
1907 SCS.Second = SecondConv;
1908 SCS.setToType(1, ToType);
1909
1910 // Third is Identity, because Second should rank us worse than any other
1911 // conversion. This could also be ICK_Qualification, but it's simpler to just
1912 // lump everything in with the second conversion, and we don't gain anything
1913 // from making this ICK_Qualification.
1914 SCS.Third = ICK_Identity;
1915 SCS.setToType(2, ToType);
1916 return true;
1917}
1918
1919static bool
1920IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1921 QualType &ToType,
1922 bool InOverloadResolution,
1923 StandardConversionSequence &SCS,
1924 bool CStyle) {
1925
1926 const RecordType *UT = ToType->getAsUnionType();
1927 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1928 return false;
1929 // The field to initialize within the transparent union.
1930 RecordDecl *UD = UT->getDecl();
1931 // It's compatible if the expression matches any of the fields.
1932 for (const auto *it : UD->fields()) {
1933 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1934 CStyle, /*ObjCWritebackConversion=*/false)) {
1935 ToType = it->getType();
1936 return true;
1937 }
1938 }
1939 return false;
1940}
1941
1942/// IsIntegralPromotion - Determines whether the conversion from the
1943/// expression From (whose potentially-adjusted type is FromType) to
1944/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1945/// sets PromotedType to the promoted type.
1946bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1947 const BuiltinType *To = ToType->getAs<BuiltinType>();
1948 // All integers are built-in.
1949 if (!To) {
1950 return false;
1951 }
1952
1953 // An rvalue of type char, signed char, unsigned char, short int, or
1954 // unsigned short int can be converted to an rvalue of type int if
1955 // int can represent all the values of the source type; otherwise,
1956 // the source rvalue can be converted to an rvalue of type unsigned
1957 // int (C++ 4.5p1).
1958 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1959 !FromType->isEnumeralType()) {
1960 if (// We can promote any signed, promotable integer type to an int
1961 (FromType->isSignedIntegerType() ||
1962 // We can promote any unsigned integer type whose size is
1963 // less than int to an int.
1964 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1965 return To->getKind() == BuiltinType::Int;
1966 }
1967
1968 return To->getKind() == BuiltinType::UInt;
1969 }
1970
1971 // C++11 [conv.prom]p3:
1972 // A prvalue of an unscoped enumeration type whose underlying type is not
1973 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1974 // following types that can represent all the values of the enumeration
1975 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1976 // unsigned int, long int, unsigned long int, long long int, or unsigned
1977 // long long int. If none of the types in that list can represent all the
1978 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1979 // type can be converted to an rvalue a prvalue of the extended integer type
1980 // with lowest integer conversion rank (4.13) greater than the rank of long
1981 // long in which all the values of the enumeration can be represented. If
1982 // there are two such extended types, the signed one is chosen.
1983 // C++11 [conv.prom]p4:
1984 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1985 // can be converted to a prvalue of its underlying type. Moreover, if
1986 // integral promotion can be applied to its underlying type, a prvalue of an
1987 // unscoped enumeration type whose underlying type is fixed can also be
1988 // converted to a prvalue of the promoted underlying type.
1989 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1990 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1991 // provided for a scoped enumeration.
1992 if (FromEnumType->getDecl()->isScoped())
1993 return false;
1994
1995 // We can perform an integral promotion to the underlying type of the enum,
1996 // even if that's not the promoted type. Note that the check for promoting
1997 // the underlying type is based on the type alone, and does not consider
1998 // the bitfield-ness of the actual source expression.
1999 if (FromEnumType->getDecl()->isFixed()) {
2000 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2001 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2002 IsIntegralPromotion(nullptr, Underlying, ToType);
2003 }
2004
2005 // We have already pre-calculated the promotion type, so this is trivial.
2006 if (ToType->isIntegerType() &&
2007 isCompleteType(From->getLocStart(), FromType))
2008 return Context.hasSameUnqualifiedType(
2009 ToType, FromEnumType->getDecl()->getPromotionType());
2010
2011 // C++ [conv.prom]p5:
2012 // If the bit-field has an enumerated type, it is treated as any other
2013 // value of that type for promotion purposes.
2014 //
2015 // ... so do not fall through into the bit-field checks below in C++.
2016 if (getLangOpts().CPlusPlus)
2017 return false;
2018 }
2019
2020 // C++0x [conv.prom]p2:
2021 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2022 // to an rvalue a prvalue of the first of the following types that can
2023 // represent all the values of its underlying type: int, unsigned int,
2024 // long int, unsigned long int, long long int, or unsigned long long int.
2025 // If none of the types in that list can represent all the values of its
2026 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2027 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2028 // type.
2029 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2030 ToType->isIntegerType()) {
2031 // Determine whether the type we're converting from is signed or
2032 // unsigned.
2033 bool FromIsSigned = FromType->isSignedIntegerType();
2034 uint64_t FromSize = Context.getTypeSize(FromType);
2035
2036 // The types we'll try to promote to, in the appropriate
2037 // order. Try each of these types.
2038 QualType PromoteTypes[6] = {
2039 Context.IntTy, Context.UnsignedIntTy,
2040 Context.LongTy, Context.UnsignedLongTy ,
2041 Context.LongLongTy, Context.UnsignedLongLongTy
2042 };
2043 for (int Idx = 0; Idx < 6; ++Idx) {
2044 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2045 if (FromSize < ToSize ||
2046 (FromSize == ToSize &&
2047 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2048 // We found the type that we can promote to. If this is the
2049 // type we wanted, we have a promotion. Otherwise, no
2050 // promotion.
2051 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2052 }
2053 }
2054 }
2055
2056 // An rvalue for an integral bit-field (9.6) can be converted to an
2057 // rvalue of type int if int can represent all the values of the
2058 // bit-field; otherwise, it can be converted to unsigned int if
2059 // unsigned int can represent all the values of the bit-field. If
2060 // the bit-field is larger yet, no integral promotion applies to
2061 // it. If the bit-field has an enumerated type, it is treated as any
2062 // other value of that type for promotion purposes (C++ 4.5p3).
2063 // FIXME: We should delay checking of bit-fields until we actually perform the
2064 // conversion.
2065 //
2066 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2067 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2068 // bit-fields and those whose underlying type is larger than int) for GCC
2069 // compatibility.
2070 if (From) {
2071 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2072 llvm::APSInt BitWidth;
2073 if (FromType->isIntegralType(Context) &&
2074 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2075 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2076 ToSize = Context.getTypeSize(ToType);
2077
2078 // Are we promoting to an int from a bitfield that fits in an int?
2079 if (BitWidth < ToSize ||
2080 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2081 return To->getKind() == BuiltinType::Int;
2082 }
2083
2084 // Are we promoting to an unsigned int from an unsigned bitfield
2085 // that fits into an unsigned int?
2086 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2087 return To->getKind() == BuiltinType::UInt;
2088 }
2089
2090 return false;
2091 }
2092 }
2093 }
2094
2095 // An rvalue of type bool can be converted to an rvalue of type int,
2096 // with false becoming zero and true becoming one (C++ 4.5p4).
2097 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2098 return true;
2099 }
2100
2101 return false;
2102}
2103
2104/// IsFloatingPointPromotion - Determines whether the conversion from
2105/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2106/// returns true and sets PromotedType to the promoted type.
2107bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2108 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2109 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2110 /// An rvalue of type float can be converted to an rvalue of type
2111 /// double. (C++ 4.6p1).
2112 if (FromBuiltin->getKind() == BuiltinType::Float &&
2113 ToBuiltin->getKind() == BuiltinType::Double)
2114 return true;
2115
2116 // C99 6.3.1.5p1:
2117 // When a float is promoted to double or long double, or a
2118 // double is promoted to long double [...].
2119 if (!getLangOpts().CPlusPlus &&
2120 (FromBuiltin->getKind() == BuiltinType::Float ||
2121 FromBuiltin->getKind() == BuiltinType::Double) &&
2122 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2123 ToBuiltin->getKind() == BuiltinType::Float128))
2124 return true;
2125
2126 // Half can be promoted to float.
2127 if (!getLangOpts().NativeHalfType &&
2128 FromBuiltin->getKind() == BuiltinType::Half &&
2129 ToBuiltin->getKind() == BuiltinType::Float)
2130 return true;
2131 }
2132
2133 return false;
2134}
2135
2136/// Determine if a conversion is a complex promotion.
2137///
2138/// A complex promotion is defined as a complex -> complex conversion
2139/// where the conversion between the underlying real types is a
2140/// floating-point or integral promotion.
2141bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2142 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2143 if (!FromComplex)
2144 return false;
2145
2146 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2147 if (!ToComplex)
2148 return false;
2149
2150 return IsFloatingPointPromotion(FromComplex->getElementType(),
2151 ToComplex->getElementType()) ||
2152 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2153 ToComplex->getElementType());
2154}
2155
2156/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2157/// the pointer type FromPtr to a pointer to type ToPointee, with the
2158/// same type qualifiers as FromPtr has on its pointee type. ToType,
2159/// if non-empty, will be a pointer to ToType that may or may not have
2160/// the right set of qualifiers on its pointee.
2161///
2162static QualType
2163BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2164 QualType ToPointee, QualType ToType,
2165 ASTContext &Context,
2166 bool StripObjCLifetime = false) {
2167 assert((FromPtr->getTypeClass() == Type::Pointer ||(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 2169, __extension__ __PRETTY_FUNCTION__))
2168 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 2169, __extension__ __PRETTY_FUNCTION__))
2169 "Invalid similarly-qualified pointer type")(static_cast <bool> ((FromPtr->getTypeClass() == Type
::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer
) && "Invalid similarly-qualified pointer type") ? void
(0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 2169, __extension__ __PRETTY_FUNCTION__))
;
2170
2171 /// Conversions to 'id' subsume cv-qualifier conversions.
2172 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2173 return ToType.getUnqualifiedType();
2174
2175 QualType CanonFromPointee
2176 = Context.getCanonicalType(FromPtr->getPointeeType());
2177 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2178 Qualifiers Quals = CanonFromPointee.getQualifiers();
2179
2180 if (StripObjCLifetime)
2181 Quals.removeObjCLifetime();
2182
2183 // Exact qualifier match -> return the pointer type we're converting to.
2184 if (CanonToPointee.getLocalQualifiers() == Quals) {
2185 // ToType is exactly what we need. Return it.
2186 if (!ToType.isNull())
2187 return ToType.getUnqualifiedType();
2188
2189 // Build a pointer to ToPointee. It has the right qualifiers
2190 // already.
2191 if (isa<ObjCObjectPointerType>(ToType))
2192 return Context.getObjCObjectPointerType(ToPointee);
2193 return Context.getPointerType(ToPointee);
2194 }
2195
2196 // Just build a canonical type that has the right qualifiers.
2197 QualType QualifiedCanonToPointee
2198 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2199
2200 if (isa<ObjCObjectPointerType>(ToType))
2201 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2202 return Context.getPointerType(QualifiedCanonToPointee);
2203}
2204
2205static bool isNullPointerConstantForConversion(Expr *Expr,
2206 bool InOverloadResolution,
2207 ASTContext &Context) {
2208 // Handle value-dependent integral null pointer constants correctly.
2209 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2210 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2211 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2212 return !InOverloadResolution;
2213
2214 return Expr->isNullPointerConstant(Context,
2215 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2216 : Expr::NPC_ValueDependentIsNull);
2217}
2218
2219/// IsPointerConversion - Determines whether the conversion of the
2220/// expression From, which has the (possibly adjusted) type FromType,
2221/// can be converted to the type ToType via a pointer conversion (C++
2222/// 4.10). If so, returns true and places the converted type (that
2223/// might differ from ToType in its cv-qualifiers at some level) into
2224/// ConvertedType.
2225///
2226/// This routine also supports conversions to and from block pointers
2227/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2228/// pointers to interfaces. FIXME: Once we've determined the
2229/// appropriate overloading rules for Objective-C, we may want to
2230/// split the Objective-C checks into a different routine; however,
2231/// GCC seems to consider all of these conversions to be pointer
2232/// conversions, so for now they live here. IncompatibleObjC will be
2233/// set if the conversion is an allowed Objective-C conversion that
2234/// should result in a warning.
2235bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2236 bool InOverloadResolution,
2237 QualType& ConvertedType,
2238 bool &IncompatibleObjC) {
2239 IncompatibleObjC = false;
2240 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2241 IncompatibleObjC))
2242 return true;
2243
2244 // Conversion from a null pointer constant to any Objective-C pointer type.
2245 if (ToType->isObjCObjectPointerType() &&
2246 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2247 ConvertedType = ToType;
2248 return true;
2249 }
2250
2251 // Blocks: Block pointers can be converted to void*.
2252 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2253 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2254 ConvertedType = ToType;
2255 return true;
2256 }
2257 // Blocks: A null pointer constant can be converted to a block
2258 // pointer type.
2259 if (ToType->isBlockPointerType() &&
2260 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2261 ConvertedType = ToType;
2262 return true;
2263 }
2264
2265 // If the left-hand-side is nullptr_t, the right side can be a null
2266 // pointer constant.
2267 if (ToType->isNullPtrType() &&
2268 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2269 ConvertedType = ToType;
2270 return true;
2271 }
2272
2273 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2274 if (!ToTypePtr)
2275 return false;
2276
2277 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2278 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2279 ConvertedType = ToType;
2280 return true;
2281 }
2282
2283 // Beyond this point, both types need to be pointers
2284 // , including objective-c pointers.
2285 QualType ToPointeeType = ToTypePtr->getPointeeType();
2286 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2287 !getLangOpts().ObjCAutoRefCount) {
2288 ConvertedType = BuildSimilarlyQualifiedPointerType(
2289 FromType->getAs<ObjCObjectPointerType>(),
2290 ToPointeeType,
2291 ToType, Context);
2292 return true;
2293 }
2294 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2295 if (!FromTypePtr)
2296 return false;
2297
2298 QualType FromPointeeType = FromTypePtr->getPointeeType();
2299
2300 // If the unqualified pointee types are the same, this can't be a
2301 // pointer conversion, so don't do all of the work below.
2302 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2303 return false;
2304
2305 // An rvalue of type "pointer to cv T," where T is an object type,
2306 // can be converted to an rvalue of type "pointer to cv void" (C++
2307 // 4.10p2).
2308 if (FromPointeeType->isIncompleteOrObjectType() &&
2309 ToPointeeType->isVoidType()) {
2310 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2311 ToPointeeType,
2312 ToType, Context,
2313 /*StripObjCLifetime=*/true);
2314 return true;
2315 }
2316
2317 // MSVC allows implicit function to void* type conversion.
2318 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2319 ToPointeeType->isVoidType()) {
2320 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2321 ToPointeeType,
2322 ToType, Context);
2323 return true;
2324 }
2325
2326 // When we're overloading in C, we allow a special kind of pointer
2327 // conversion for compatible-but-not-identical pointee types.
2328 if (!getLangOpts().CPlusPlus &&
2329 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2330 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2331 ToPointeeType,
2332 ToType, Context);
2333 return true;
2334 }
2335
2336 // C++ [conv.ptr]p3:
2337 //
2338 // An rvalue of type "pointer to cv D," where D is a class type,
2339 // can be converted to an rvalue of type "pointer to cv B," where
2340 // B is a base class (clause 10) of D. If B is an inaccessible
2341 // (clause 11) or ambiguous (10.2) base class of D, a program that
2342 // necessitates this conversion is ill-formed. The result of the
2343 // conversion is a pointer to the base class sub-object of the
2344 // derived class object. The null pointer value is converted to
2345 // the null pointer value of the destination type.
2346 //
2347 // Note that we do not check for ambiguity or inaccessibility
2348 // here. That is handled by CheckPointerConversion.
2349 if (getLangOpts().CPlusPlus &&
2350 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2351 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2352 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2353 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2354 ToPointeeType,
2355 ToType, Context);
2356 return true;
2357 }
2358
2359 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2360 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2361 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2362 ToPointeeType,
2363 ToType, Context);
2364 return true;
2365 }
2366
2367 return false;
2368}
2369
2370/// Adopt the given qualifiers for the given type.
2371static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2372 Qualifiers TQs = T.getQualifiers();
2373
2374 // Check whether qualifiers already match.
2375 if (TQs == Qs)
2376 return T;
2377
2378 if (Qs.compatiblyIncludes(TQs))
2379 return Context.getQualifiedType(T, Qs);
2380
2381 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2382}
2383
2384/// isObjCPointerConversion - Determines whether this is an
2385/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2386/// with the same arguments and return values.
2387bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2388 QualType& ConvertedType,
2389 bool &IncompatibleObjC) {
2390 if (!getLangOpts().ObjC1)
2391 return false;
2392
2393 // The set of qualifiers on the type we're converting from.
2394 Qualifiers FromQualifiers = FromType.getQualifiers();
2395
2396 // First, we handle all conversions on ObjC object pointer types.
2397 const ObjCObjectPointerType* ToObjCPtr =
2398 ToType->getAs<ObjCObjectPointerType>();
2399 const ObjCObjectPointerType *FromObjCPtr =
2400 FromType->getAs<ObjCObjectPointerType>();
2401
2402 if (ToObjCPtr && FromObjCPtr) {
2403 // If the pointee types are the same (ignoring qualifications),
2404 // then this is not a pointer conversion.
2405 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2406 FromObjCPtr->getPointeeType()))
2407 return false;
2408
2409 // Conversion between Objective-C pointers.
2410 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2411 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2412 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2413 if (getLangOpts().CPlusPlus && LHS && RHS &&
2414 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2415 FromObjCPtr->getPointeeType()))
2416 return false;
2417 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2418 ToObjCPtr->getPointeeType(),
2419 ToType, Context);
2420 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2421 return true;
2422 }
2423
2424 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2425 // Okay: this is some kind of implicit downcast of Objective-C
2426 // interfaces, which is permitted. However, we're going to
2427 // complain about it.
2428 IncompatibleObjC = true;
2429 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2430 ToObjCPtr->getPointeeType(),
2431 ToType, Context);
2432 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2433 return true;
2434 }
2435 }
2436 // Beyond this point, both types need to be C pointers or block pointers.
2437 QualType ToPointeeType;
2438 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2439 ToPointeeType = ToCPtr->getPointeeType();
2440 else if (const BlockPointerType *ToBlockPtr =
2441 ToType->getAs<BlockPointerType>()) {
2442 // Objective C++: We're able to convert from a pointer to any object
2443 // to a block pointer type.
2444 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2445 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2446 return true;
2447 }
2448 ToPointeeType = ToBlockPtr->getPointeeType();
2449 }
2450 else if (FromType->getAs<BlockPointerType>() &&
2451 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2452 // Objective C++: We're able to convert from a block pointer type to a
2453 // pointer to any object.
2454 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2455 return true;
2456 }
2457 else
2458 return false;
2459
2460 QualType FromPointeeType;
2461 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2462 FromPointeeType = FromCPtr->getPointeeType();
2463 else if (const BlockPointerType *FromBlockPtr =
2464 FromType->getAs<BlockPointerType>())
2465 FromPointeeType = FromBlockPtr->getPointeeType();
2466 else
2467 return false;
2468
2469 // If we have pointers to pointers, recursively check whether this
2470 // is an Objective-C conversion.
2471 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2472 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2473 IncompatibleObjC)) {
2474 // We always complain about this conversion.
2475 IncompatibleObjC = true;
2476 ConvertedType = Context.getPointerType(ConvertedType);
2477 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2478 return true;
2479 }
2480 // Allow conversion of pointee being objective-c pointer to another one;
2481 // as in I* to id.
2482 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2483 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2484 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2485 IncompatibleObjC)) {
2486
2487 ConvertedType = Context.getPointerType(ConvertedType);
2488 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2489 return true;
2490 }
2491
2492 // If we have pointers to functions or blocks, check whether the only
2493 // differences in the argument and result types are in Objective-C
2494 // pointer conversions. If so, we permit the conversion (but
2495 // complain about it).
2496 const FunctionProtoType *FromFunctionType
2497 = FromPointeeType->getAs<FunctionProtoType>();
2498 const FunctionProtoType *ToFunctionType
2499 = ToPointeeType->getAs<FunctionProtoType>();
2500 if (FromFunctionType && ToFunctionType) {
2501 // If the function types are exactly the same, this isn't an
2502 // Objective-C pointer conversion.
2503 if (Context.getCanonicalType(FromPointeeType)
2504 == Context.getCanonicalType(ToPointeeType))
2505 return false;
2506
2507 // Perform the quick checks that will tell us whether these
2508 // function types are obviously different.
2509 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2510 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2511 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2512 return false;
2513
2514 bool HasObjCConversion = false;
2515 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2516 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2517 // Okay, the types match exactly. Nothing to do.
2518 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2519 ToFunctionType->getReturnType(),
2520 ConvertedType, IncompatibleObjC)) {
2521 // Okay, we have an Objective-C pointer conversion.
2522 HasObjCConversion = true;
2523 } else {
2524 // Function types are too different. Abort.
2525 return false;
2526 }
2527
2528 // Check argument types.
2529 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2530 ArgIdx != NumArgs; ++ArgIdx) {
2531 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2532 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2533 if (Context.getCanonicalType(FromArgType)
2534 == Context.getCanonicalType(ToArgType)) {
2535 // Okay, the types match exactly. Nothing to do.
2536 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2537 ConvertedType, IncompatibleObjC)) {
2538 // Okay, we have an Objective-C pointer conversion.
2539 HasObjCConversion = true;
2540 } else {
2541 // Argument types are too different. Abort.
2542 return false;
2543 }
2544 }
2545
2546 if (HasObjCConversion) {
2547 // We had an Objective-C conversion. Allow this pointer
2548 // conversion, but complain about it.
2549 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2550 IncompatibleObjC = true;
2551 return true;
2552 }
2553 }
2554
2555 return false;
2556}
2557
2558/// Determine whether this is an Objective-C writeback conversion,
2559/// used for parameter passing when performing automatic reference counting.
2560///
2561/// \param FromType The type we're converting form.
2562///
2563/// \param ToType The type we're converting to.
2564///
2565/// \param ConvertedType The type that will be produced after applying
2566/// this conversion.
2567bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2568 QualType &ConvertedType) {
2569 if (!getLangOpts().ObjCAutoRefCount ||
2570 Context.hasSameUnqualifiedType(FromType, ToType))
2571 return false;
2572
2573 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2574 QualType ToPointee;
2575 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2576 ToPointee = ToPointer->getPointeeType();
2577 else
2578 return false;
2579
2580 Qualifiers ToQuals = ToPointee.getQualifiers();
2581 if (!ToPointee->isObjCLifetimeType() ||
2582 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2583 !ToQuals.withoutObjCLifetime().empty())
2584 return false;
2585
2586 // Argument must be a pointer to __strong to __weak.
2587 QualType FromPointee;
2588 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2589 FromPointee = FromPointer->getPointeeType();
2590 else
2591 return false;
2592
2593 Qualifiers FromQuals = FromPointee.getQualifiers();
2594 if (!FromPointee->isObjCLifetimeType() ||
2595 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2596 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2597 return false;
2598
2599 // Make sure that we have compatible qualifiers.
2600 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2601 if (!ToQuals.compatiblyIncludes(FromQuals))
2602 return false;
2603
2604 // Remove qualifiers from the pointee type we're converting from; they
2605 // aren't used in the compatibility check belong, and we'll be adding back
2606 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2607 FromPointee = FromPointee.getUnqualifiedType();
2608
2609 // The unqualified form of the pointee types must be compatible.
2610 ToPointee = ToPointee.getUnqualifiedType();
2611 bool IncompatibleObjC;
2612 if (Context.typesAreCompatible(FromPointee, ToPointee))
2613 FromPointee = ToPointee;
2614 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2615 IncompatibleObjC))
2616 return false;
2617
2618 /// Construct the type we're converting to, which is a pointer to
2619 /// __autoreleasing pointee.
2620 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2621 ConvertedType = Context.getPointerType(FromPointee);
2622 return true;
2623}
2624
2625bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2626 QualType& ConvertedType) {
2627 QualType ToPointeeType;
2628 if (const BlockPointerType *ToBlockPtr =
2629 ToType->getAs<BlockPointerType>())
2630 ToPointeeType = ToBlockPtr->getPointeeType();
2631 else
2632 return false;
2633
2634 QualType FromPointeeType;
2635 if (const BlockPointerType *FromBlockPtr =
2636 FromType->getAs<BlockPointerType>())
2637 FromPointeeType = FromBlockPtr->getPointeeType();
2638 else
2639 return false;
2640 // We have pointer to blocks, check whether the only
2641 // differences in the argument and result types are in Objective-C
2642 // pointer conversions. If so, we permit the conversion.
2643
2644 const FunctionProtoType *FromFunctionType
2645 = FromPointeeType->getAs<FunctionProtoType>();
2646 const FunctionProtoType *ToFunctionType
2647 = ToPointeeType->getAs<FunctionProtoType>();
2648
2649 if (!FromFunctionType || !ToFunctionType)
2650 return false;
2651
2652 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2653 return true;
2654
2655 // Perform the quick checks that will tell us whether these
2656 // function types are obviously different.
2657 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2658 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2659 return false;
2660
2661 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2662 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2663 if (FromEInfo != ToEInfo)
2664 return false;
2665
2666 bool IncompatibleObjC = false;
2667 if (Context.hasSameType(FromFunctionType->getReturnType(),
2668 ToFunctionType->getReturnType())) {
2669 // Okay, the types match exactly. Nothing to do.
2670 } else {
2671 QualType RHS = FromFunctionType->getReturnType();
2672 QualType LHS = ToFunctionType->getReturnType();
2673 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2674 !RHS.hasQualifiers() && LHS.hasQualifiers())
2675 LHS = LHS.getUnqualifiedType();
2676
2677 if (Context.hasSameType(RHS,LHS)) {
2678 // OK exact match.
2679 } else if (isObjCPointerConversion(RHS, LHS,
2680 ConvertedType, IncompatibleObjC)) {
2681 if (IncompatibleObjC)
2682 return false;
2683 // Okay, we have an Objective-C pointer conversion.
2684 }
2685 else
2686 return false;
2687 }
2688
2689 // Check argument types.
2690 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2691 ArgIdx != NumArgs; ++ArgIdx) {
2692 IncompatibleObjC = false;
2693 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2694 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2695 if (Context.hasSameType(FromArgType, ToArgType)) {
2696 // Okay, the types match exactly. Nothing to do.
2697 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2698 ConvertedType, IncompatibleObjC)) {
2699 if (IncompatibleObjC)
2700 return false;
2701 // Okay, we have an Objective-C pointer conversion.
2702 } else
2703 // Argument types are too different. Abort.
2704 return false;
2705 }
2706
2707 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2708 bool CanUseToFPT, CanUseFromFPT;
2709 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2710 CanUseToFPT, CanUseFromFPT,
2711 NewParamInfos))
2712 return false;
2713
2714 ConvertedType = ToType;
2715 return true;
2716}
2717
2718enum {
2719 ft_default,
2720 ft_different_class,
2721 ft_parameter_arity,
2722 ft_parameter_mismatch,
2723 ft_return_type,
2724 ft_qualifer_mismatch,
2725 ft_noexcept
2726};
2727
2728/// Attempts to get the FunctionProtoType from a Type. Handles
2729/// MemberFunctionPointers properly.
2730static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2731 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2732 return FPT;
2733
2734 if (auto *MPT = FromType->getAs<MemberPointerType>())
2735 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2736
2737 return nullptr;
2738}
2739
2740/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2741/// function types. Catches different number of parameter, mismatch in
2742/// parameter types, and different return types.
2743void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2744 QualType FromType, QualType ToType) {
2745 // If either type is not valid, include no extra info.
2746 if (FromType.isNull() || ToType.isNull()) {
2747 PDiag << ft_default;
2748 return;
2749 }
2750
2751 // Get the function type from the pointers.
2752 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2753 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2754 *ToMember = ToType->getAs<MemberPointerType>();
2755 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2756 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2757 << QualType(FromMember->getClass(), 0);
2758 return;
2759 }
2760 FromType = FromMember->getPointeeType();
2761 ToType = ToMember->getPointeeType();
2762 }
2763
2764 if (FromType->isPointerType())
2765 FromType = FromType->getPointeeType();
2766 if (ToType->isPointerType())
2767 ToType = ToType->getPointeeType();
2768
2769 // Remove references.
2770 FromType = FromType.getNonReferenceType();
2771 ToType = ToType.getNonReferenceType();
2772
2773 // Don't print extra info for non-specialized template functions.
2774 if (FromType->isInstantiationDependentType() &&
2775 !FromType->getAs<TemplateSpecializationType>()) {
2776 PDiag << ft_default;
2777 return;
2778 }
2779
2780 // No extra info for same types.
2781 if (Context.hasSameType(FromType, ToType)) {
2782 PDiag << ft_default;
2783 return;
2784 }
2785
2786 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2787 *ToFunction = tryGetFunctionProtoType(ToType);
2788
2789 // Both types need to be function types.
2790 if (!FromFunction || !ToFunction) {
2791 PDiag << ft_default;
2792 return;
2793 }
2794
2795 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2796 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2797 << FromFunction->getNumParams();
2798 return;
2799 }
2800
2801 // Handle different parameter types.
2802 unsigned ArgPos;
2803 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2804 PDiag << ft_parameter_mismatch << ArgPos + 1
2805 << ToFunction->getParamType(ArgPos)
2806 << FromFunction->getParamType(ArgPos);
2807 return;
2808 }
2809
2810 // Handle different return type.
2811 if (!Context.hasSameType(FromFunction->getReturnType(),
2812 ToFunction->getReturnType())) {
2813 PDiag << ft_return_type << ToFunction->getReturnType()
2814 << FromFunction->getReturnType();
2815 return;
2816 }
2817
2818 unsigned FromQuals = FromFunction->getTypeQuals(),
2819 ToQuals = ToFunction->getTypeQuals();
2820 if (FromQuals != ToQuals) {
2821 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2822 return;
2823 }
2824
2825 // Handle exception specification differences on canonical type (in C++17
2826 // onwards).
2827 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2828 ->isNothrow() !=
2829 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2830 ->isNothrow()) {
2831 PDiag << ft_noexcept;
2832 return;
2833 }
2834
2835 // Unable to find a difference, so add no extra info.
2836 PDiag << ft_default;
2837}
2838
2839/// FunctionParamTypesAreEqual - This routine checks two function proto types
2840/// for equality of their argument types. Caller has already checked that
2841/// they have same number of arguments. If the parameters are different,
2842/// ArgPos will have the parameter index of the first different parameter.
2843bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2844 const FunctionProtoType *NewType,
2845 unsigned *ArgPos) {
2846 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2847 N = NewType->param_type_begin(),
2848 E = OldType->param_type_end();
2849 O && (O != E); ++O, ++N) {
2850 if (!Context.hasSameType(O->getUnqualifiedType(),
2851 N->getUnqualifiedType())) {
2852 if (ArgPos)
2853 *ArgPos = O - OldType->param_type_begin();
2854 return false;
2855 }
2856 }
2857 return true;
2858}
2859
2860/// CheckPointerConversion - Check the pointer conversion from the
2861/// expression From to the type ToType. This routine checks for
2862/// ambiguous or inaccessible derived-to-base pointer
2863/// conversions for which IsPointerConversion has already returned
2864/// true. It returns true and produces a diagnostic if there was an
2865/// error, or returns false otherwise.
2866bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2867 CastKind &Kind,
2868 CXXCastPath& BasePath,
2869 bool IgnoreBaseAccess,
2870 bool Diagnose) {
2871 QualType FromType = From->getType();
2872 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2873
2874 Kind = CK_BitCast;
2875
2876 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2877 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2878 Expr::NPCK_ZeroExpression) {
2879 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2880 DiagRuntimeBehavior(From->getExprLoc(), From,
2881 PDiag(diag::warn_impcast_bool_to_null_pointer)
2882 << ToType << From->getSourceRange());
2883 else if (!isUnevaluatedContext())
2884 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2885 << ToType << From->getSourceRange();
2886 }
2887 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2888 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2889 QualType FromPointeeType = FromPtrType->getPointeeType(),
2890 ToPointeeType = ToPtrType->getPointeeType();
2891
2892 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2893 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2894 // We must have a derived-to-base conversion. Check an
2895 // ambiguous or inaccessible conversion.
2896 unsigned InaccessibleID = 0;
2897 unsigned AmbigiousID = 0;
2898 if (Diagnose) {
2899 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2900 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2901 }
2902 if (CheckDerivedToBaseConversion(
2903 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2904 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2905 &BasePath, IgnoreBaseAccess))
2906 return true;
2907
2908 // The conversion was successful.
2909 Kind = CK_DerivedToBase;
2910 }
2911
2912 if (Diagnose && !IsCStyleOrFunctionalCast &&
2913 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2914 assert(getLangOpts().MSVCCompat &&(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 2915, __extension__ __PRETTY_FUNCTION__))
2915 "this should only be possible with MSVCCompat!")(static_cast <bool> (getLangOpts().MSVCCompat &&
"this should only be possible with MSVCCompat!") ? void (0) :
__assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 2915, __extension__ __PRETTY_FUNCTION__))
;
2916 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2917 << From->getSourceRange();
2918 }
2919 }
2920 } else if (const ObjCObjectPointerType *ToPtrType =
2921 ToType->getAs<ObjCObjectPointerType>()) {
2922 if (const ObjCObjectPointerType *FromPtrType =
2923 FromType->getAs<ObjCObjectPointerType>()) {
2924 // Objective-C++ conversions are always okay.
2925 // FIXME: We should have a different class of conversions for the
2926 // Objective-C++ implicit conversions.
2927 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2928 return false;
2929 } else if (FromType->isBlockPointerType()) {
2930 Kind = CK_BlockPointerToObjCPointerCast;
2931 } else {
2932 Kind = CK_CPointerToObjCPointerCast;
2933 }
2934 } else if (ToType->isBlockPointerType()) {
2935 if (!FromType->isBlockPointerType())
2936 Kind = CK_AnyPointerToBlockPointerCast;
2937 }
2938
2939 // We shouldn't fall into this case unless it's valid for other
2940 // reasons.
2941 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2942 Kind = CK_NullToPointer;
2943
2944 return false;
2945}
2946
2947/// IsMemberPointerConversion - Determines whether the conversion of the
2948/// expression From, which has the (possibly adjusted) type FromType, can be
2949/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2950/// If so, returns true and places the converted type (that might differ from
2951/// ToType in its cv-qualifiers at some level) into ConvertedType.
2952bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2953 QualType ToType,
2954 bool InOverloadResolution,
2955 QualType &ConvertedType) {
2956 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2957 if (!ToTypePtr)
2958 return false;
2959
2960 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2961 if (From->isNullPointerConstant(Context,
2962 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2963 : Expr::NPC_ValueDependentIsNull)) {
2964 ConvertedType = ToType;
2965 return true;
2966 }
2967
2968 // Otherwise, both types have to be member pointers.
2969 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2970 if (!FromTypePtr)
2971 return false;
2972
2973 // A pointer to member of B can be converted to a pointer to member of D,
2974 // where D is derived from B (C++ 4.11p2).
2975 QualType FromClass(FromTypePtr->getClass(), 0);
2976 QualType ToClass(ToTypePtr->getClass(), 0);
2977
2978 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2979 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2980 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2981 ToClass.getTypePtr());
2982 return true;
2983 }
2984
2985 return false;
2986}
2987
2988/// CheckMemberPointerConversion - Check the member pointer conversion from the
2989/// expression From to the type ToType. This routine checks for ambiguous or
2990/// virtual or inaccessible base-to-derived member pointer conversions
2991/// for which IsMemberPointerConversion has already returned true. It returns
2992/// true and produces a diagnostic if there was an error, or returns false
2993/// otherwise.
2994bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2995 CastKind &Kind,
2996 CXXCastPath &BasePath,
2997 bool IgnoreBaseAccess) {
2998 QualType FromType = From->getType();
2999 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3000 if (!FromPtrType) {
3001 // This must be a null pointer to member pointer conversion
3002 assert(From->isNullPointerConstant(Context,(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3004, __extension__ __PRETTY_FUNCTION__))
3003 Expr::NPC_ValueDependentIsNull) &&(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3004, __extension__ __PRETTY_FUNCTION__))
3004 "Expr must be null pointer constant!")(static_cast <bool> (From->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull) && "Expr must be null pointer constant!"
) ? void (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3004, __extension__ __PRETTY_FUNCTION__))
;
3005 Kind = CK_NullToMemberPointer;
3006 return false;
3007 }
3008
3009 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3010 assert(ToPtrType && "No member pointer cast has a target type "(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3011, __extension__ __PRETTY_FUNCTION__))
3011 "that is not a member pointer.")(static_cast <bool> (ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? void (0) : __assert_fail (
"ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3011, __extension__ __PRETTY_FUNCTION__))
;
3012
3013 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3014 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3015
3016 // FIXME: What about dependent types?
3017 assert(FromClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (FromClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3017, __extension__ __PRETTY_FUNCTION__))
;
3018 assert(ToClass->isRecordType() && "Pointer into non-class.")(static_cast <bool> (ToClass->isRecordType() &&
"Pointer into non-class.") ? void (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
;
3019
3020 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3021 /*DetectVirtual=*/true);
3022 bool DerivationOkay =
3023 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3024 assert(DerivationOkay &&(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3025, __extension__ __PRETTY_FUNCTION__))
3025 "Should not have been called if derivation isn't OK.")(static_cast <bool> (DerivationOkay && "Should not have been called if derivation isn't OK."
) ? void (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3025, __extension__ __PRETTY_FUNCTION__))
;
3026 (void)DerivationOkay;
3027
3028 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3029 getUnqualifiedType())) {
3030 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3031 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3032 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3033 return true;
3034 }
3035
3036 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3037 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3038 << FromClass << ToClass << QualType(VBase, 0)
3039 << From->getSourceRange();
3040 return true;
3041 }
3042
3043 if (!IgnoreBaseAccess)
3044 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3045 Paths.front(),
3046 diag::err_downcast_from_inaccessible_base);
3047
3048 // Must be a base to derived member conversion.
3049 BuildBasePathArray(Paths, BasePath);
3050 Kind = CK_BaseToDerivedMemberPointer;
3051 return false;
3052}
3053
3054/// Determine whether the lifetime conversion between the two given
3055/// qualifiers sets is nontrivial.
3056static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3057 Qualifiers ToQuals) {
3058 // Converting anything to const __unsafe_unretained is trivial.
3059 if (ToQuals.hasConst() &&
3060 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3061 return false;
3062
3063 return true;
3064}
3065
3066/// IsQualificationConversion - Determines whether the conversion from
3067/// an rvalue of type FromType to ToType is a qualification conversion
3068/// (C++ 4.4).
3069///
3070/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3071/// when the qualification conversion involves a change in the Objective-C
3072/// object lifetime.
3073bool
3074Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3075 bool CStyle, bool &ObjCLifetimeConversion) {
3076 FromType = Context.getCanonicalType(FromType);
3077 ToType = Context.getCanonicalType(ToType);
3078 ObjCLifetimeConversion = false;
3079
3080 // If FromType and ToType are the same type, this is not a
3081 // qualification conversion.
3082 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3083 return false;
3084
3085 // (C++ 4.4p4):
3086 // A conversion can add cv-qualifiers at levels other than the first
3087 // in multi-level pointers, subject to the following rules: [...]
3088 bool PreviousToQualsIncludeConst = true;
3089 bool UnwrappedAnyPointer = false;
3090 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3091 // Within each iteration of the loop, we check the qualifiers to
3092 // determine if this still looks like a qualification
3093 // conversion. Then, if all is well, we unwrap one more level of
3094 // pointers or pointers-to-members and do it all again
3095 // until there are no more pointers or pointers-to-members left to
3096 // unwrap.
3097 UnwrappedAnyPointer = true;
3098
3099 Qualifiers FromQuals = FromType.getQualifiers();
3100 Qualifiers ToQuals = ToType.getQualifiers();
3101
3102 // Ignore __unaligned qualifier if this type is void.
3103 if (ToType.getUnqualifiedType()->isVoidType())
3104 FromQuals.removeUnaligned();
3105
3106 // Objective-C ARC:
3107 // Check Objective-C lifetime conversions.
3108 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3109 UnwrappedAnyPointer) {
3110 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3111 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3112 ObjCLifetimeConversion = true;
3113 FromQuals.removeObjCLifetime();
3114 ToQuals.removeObjCLifetime();
3115 } else {
3116 // Qualification conversions cannot cast between different
3117 // Objective-C lifetime qualifiers.
3118 return false;
3119 }
3120 }
3121
3122 // Allow addition/removal of GC attributes but not changing GC attributes.
3123 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3124 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3125 FromQuals.removeObjCGCAttr();
3126 ToQuals.removeObjCGCAttr();
3127 }
3128
3129 // -- for every j > 0, if const is in cv 1,j then const is in cv
3130 // 2,j, and similarly for volatile.
3131 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3132 return false;
3133
3134 // -- if the cv 1,j and cv 2,j are different, then const is in
3135 // every cv for 0 < k < j.
3136 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3137 && !PreviousToQualsIncludeConst)
3138 return false;
3139
3140 // Keep track of whether all prior cv-qualifiers in the "to" type
3141 // include const.
3142 PreviousToQualsIncludeConst
3143 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3144 }
3145
3146 // We are left with FromType and ToType being the pointee types
3147 // after unwrapping the original FromType and ToType the same number
3148 // of types. If we unwrapped any pointers, and if FromType and
3149 // ToType have the same unqualified type (since we checked
3150 // qualifiers above), then this is a qualification conversion.
3151 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3152}
3153
3154/// - Determine whether this is a conversion from a scalar type to an
3155/// atomic type.
3156///
3157/// If successful, updates \c SCS's second and third steps in the conversion
3158/// sequence to finish the conversion.
3159static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3160 bool InOverloadResolution,
3161 StandardConversionSequence &SCS,
3162 bool CStyle) {
3163 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3164 if (!ToAtomic)
3165 return false;
3166
3167 StandardConversionSequence InnerSCS;
3168 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3169 InOverloadResolution, InnerSCS,
3170 CStyle, /*AllowObjCWritebackConversion=*/false))
3171 return false;
3172
3173 SCS.Second = InnerSCS.Second;
3174 SCS.setToType(1, InnerSCS.getToType(1));
3175 SCS.Third = InnerSCS.Third;
3176 SCS.QualificationIncludesObjCLifetime
3177 = InnerSCS.QualificationIncludesObjCLifetime;
3178 SCS.setToType(2, InnerSCS.getToType(2));
3179 return true;
3180}
3181
3182static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3183 CXXConstructorDecl *Constructor,
3184 QualType Type) {
3185 const FunctionProtoType *CtorType =
3186 Constructor->getType()->getAs<FunctionProtoType>();
3187 if (CtorType->getNumParams() > 0) {
3188 QualType FirstArg = CtorType->getParamType(0);
3189 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3190 return true;
3191 }
3192 return false;
3193}
3194
3195static OverloadingResult
3196IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3197 CXXRecordDecl *To,
3198 UserDefinedConversionSequence &User,
3199 OverloadCandidateSet &CandidateSet,
3200 bool AllowExplicit) {
3201 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3202 for (auto *D : S.LookupConstructors(To)) {
3203 auto Info = getConstructorInfo(D);
3204 if (!Info)
3205 continue;
3206
3207 bool Usable = !Info.Constructor->isInvalidDecl() &&
3208 S.isInitListConstructor(Info.Constructor) &&
3209 (AllowExplicit || !Info.Constructor->isExplicit());
3210 if (Usable) {
3211 // If the first argument is (a reference to) the target type,
3212 // suppress conversions.
3213 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3214 S.Context, Info.Constructor, ToType);
3215 if (Info.ConstructorTmpl)
3216 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3217 /*ExplicitArgs*/ nullptr, From,
3218 CandidateSet, SuppressUserConversions);
3219 else
3220 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3221 CandidateSet, SuppressUserConversions);
3222 }
3223 }
3224
3225 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3226
3227 OverloadCandidateSet::iterator Best;
3228 switch (auto Result =
3229 CandidateSet.BestViableFunction(S, From->getLocStart(),
3230 Best)) {
3231 case OR_Deleted:
3232 case OR_Success: {
3233 // Record the standard conversion we used and the conversion function.
3234 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3235 QualType ThisType = Constructor->getThisType(S.Context);
3236 // Initializer lists don't have conversions as such.
3237 User.Before.setAsIdentityConversion();
3238 User.HadMultipleCandidates = HadMultipleCandidates;
3239 User.ConversionFunction = Constructor;
3240 User.FoundConversionFunction = Best->FoundDecl;
3241 User.After.setAsIdentityConversion();
3242 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3243 User.After.setAllToTypes(ToType);
3244 return Result;
3245 }
3246
3247 case OR_No_Viable_Function:
3248 return OR_No_Viable_Function;
3249 case OR_Ambiguous:
3250 return OR_Ambiguous;
3251 }
3252
3253 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3253)
;
3254}
3255
3256/// Determines whether there is a user-defined conversion sequence
3257/// (C++ [over.ics.user]) that converts expression From to the type
3258/// ToType. If such a conversion exists, User will contain the
3259/// user-defined conversion sequence that performs such a conversion
3260/// and this routine will return true. Otherwise, this routine returns
3261/// false and User is unspecified.
3262///
3263/// \param AllowExplicit true if the conversion should consider C++0x
3264/// "explicit" conversion functions as well as non-explicit conversion
3265/// functions (C++0x [class.conv.fct]p2).
3266///
3267/// \param AllowObjCConversionOnExplicit true if the conversion should
3268/// allow an extra Objective-C pointer conversion on uses of explicit
3269/// constructors. Requires \c AllowExplicit to also be set.
3270static OverloadingResult
3271IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3272 UserDefinedConversionSequence &User,
3273 OverloadCandidateSet &CandidateSet,
3274 bool AllowExplicit,
3275 bool AllowObjCConversionOnExplicit) {
3276 assert(AllowExplicit || !AllowObjCConversionOnExplicit)(static_cast <bool> (AllowExplicit || !AllowObjCConversionOnExplicit
) ? void (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3276, __extension__ __PRETTY_FUNCTION__))
;
3277 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3278
3279 // Whether we will only visit constructors.
3280 bool ConstructorsOnly = false;
3281
3282 // If the type we are conversion to is a class type, enumerate its
3283 // constructors.
3284 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3285 // C++ [over.match.ctor]p1:
3286 // When objects of class type are direct-initialized (8.5), or
3287 // copy-initialized from an expression of the same or a
3288 // derived class type (8.5), overload resolution selects the
3289 // constructor. [...] For copy-initialization, the candidate
3290 // functions are all the converting constructors (12.3.1) of
3291 // that class. The argument list is the expression-list within
3292 // the parentheses of the initializer.
3293 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3294 (From->getType()->getAs<RecordType>() &&
3295 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3296 ConstructorsOnly = true;
3297
3298 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3299 // We're not going to find any constructors.
3300 } else if (CXXRecordDecl *ToRecordDecl
3301 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3302
3303 Expr **Args = &From;
3304 unsigned NumArgs = 1;
3305 bool ListInitializing = false;
3306 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3307 // But first, see if there is an init-list-constructor that will work.
3308 OverloadingResult Result = IsInitializerListConstructorConversion(
3309 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3310 if (Result != OR_No_Viable_Function)
3311 return Result;
3312 // Never mind.
3313 CandidateSet.clear(
3314 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3315
3316 // If we're list-initializing, we pass the individual elements as
3317 // arguments, not the entire list.
3318 Args = InitList->getInits();
3319 NumArgs = InitList->getNumInits();
3320 ListInitializing = true;
3321 }
3322
3323 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3324 auto Info = getConstructorInfo(D);
3325 if (!Info)
3326 continue;
3327
3328 bool Usable = !Info.Constructor->isInvalidDecl();
3329 if (ListInitializing)
3330 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3331 else
3332 Usable = Usable &&
3333 Info.Constructor->isConvertingConstructor(AllowExplicit);
3334 if (Usable) {
3335 bool SuppressUserConversions = !ConstructorsOnly;
3336 if (SuppressUserConversions && ListInitializing) {
3337 SuppressUserConversions = false;
3338 if (NumArgs == 1) {
3339 // If the first argument is (a reference to) the target type,
3340 // suppress conversions.
3341 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3342 S.Context, Info.Constructor, ToType);
3343 }
3344 }
3345 if (Info.ConstructorTmpl)
3346 S.AddTemplateOverloadCandidate(
3347 Info.ConstructorTmpl, Info.FoundDecl,
3348 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3349 CandidateSet, SuppressUserConversions);
3350 else
3351 // Allow one user-defined conversion when user specifies a
3352 // From->ToType conversion via an static cast (c-style, etc).
3353 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3354 llvm::makeArrayRef(Args, NumArgs),
3355 CandidateSet, SuppressUserConversions);
3356 }
3357 }
3358 }
3359 }
3360
3361 // Enumerate conversion functions, if we're allowed to.
3362 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3363 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3364 // No conversion functions from incomplete types.
3365 } else if (const RecordType *FromRecordType
3366 = From->getType()->getAs<RecordType>()) {
3367 if (CXXRecordDecl *FromRecordDecl
3368 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3369 // Add all of the conversion functions as candidates.
3370 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3371 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3372 DeclAccessPair FoundDecl = I.getPair();
3373 NamedDecl *D = FoundDecl.getDecl();
3374 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3375 if (isa<UsingShadowDecl>(D))
3376 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3377
3378 CXXConversionDecl *Conv;
3379 FunctionTemplateDecl *ConvTemplate;
3380 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3381 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3382 else
3383 Conv = cast<CXXConversionDecl>(D);
3384
3385 if (AllowExplicit || !Conv->isExplicit()) {
3386 if (ConvTemplate)
3387 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3388 ActingContext, From, ToType,
3389 CandidateSet,
3390 AllowObjCConversionOnExplicit);
3391 else
3392 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3393 From, ToType, CandidateSet,
3394 AllowObjCConversionOnExplicit);
3395 }
3396 }
3397 }
3398 }
3399
3400 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3401
3402 OverloadCandidateSet::iterator Best;
3403 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3404 Best)) {
3405 case OR_Success:
3406 case OR_Deleted:
3407 // Record the standard conversion we used and the conversion function.
3408 if (CXXConstructorDecl *Constructor
3409 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3410 // C++ [over.ics.user]p1:
3411 // If the user-defined conversion is specified by a
3412 // constructor (12.3.1), the initial standard conversion
3413 // sequence converts the source type to the type required by
3414 // the argument of the constructor.
3415 //
3416 QualType ThisType = Constructor->getThisType(S.Context);
3417 if (isa<InitListExpr>(From)) {
3418 // Initializer lists don't have conversions as such.
3419 User.Before.setAsIdentityConversion();
3420 } else {
3421 if (Best->Conversions[0].isEllipsis())
3422 User.EllipsisConversion = true;
3423 else {
3424 User.Before = Best->Conversions[0].Standard;
3425 User.EllipsisConversion = false;
3426 }
3427 }
3428 User.HadMultipleCandidates = HadMultipleCandidates;
3429 User.ConversionFunction = Constructor;
3430 User.FoundConversionFunction = Best->FoundDecl;
3431 User.After.setAsIdentityConversion();
3432 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3433 User.After.setAllToTypes(ToType);
3434 return Result;
3435 }
3436 if (CXXConversionDecl *Conversion
3437 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3438 // C++ [over.ics.user]p1:
3439 //
3440 // [...] If the user-defined conversion is specified by a
3441 // conversion function (12.3.2), the initial standard
3442 // conversion sequence converts the source type to the
3443 // implicit object parameter of the conversion function.
3444 User.Before = Best->Conversions[0].Standard;
3445 User.HadMultipleCandidates = HadMultipleCandidates;
3446 User.ConversionFunction = Conversion;
3447 User.FoundConversionFunction = Best->FoundDecl;
3448 User.EllipsisConversion = false;
3449
3450 // C++ [over.ics.user]p2:
3451 // The second standard conversion sequence converts the
3452 // result of the user-defined conversion to the target type
3453 // for the sequence. Since an implicit conversion sequence
3454 // is an initialization, the special rules for
3455 // initialization by user-defined conversion apply when
3456 // selecting the best user-defined conversion for a
3457 // user-defined conversion sequence (see 13.3.3 and
3458 // 13.3.3.1).
3459 User.After = Best->FinalConversion;
3460 return Result;
3461 }
3462 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3462)
;
3463
3464 case OR_No_Viable_Function:
3465 return OR_No_Viable_Function;
3466
3467 case OR_Ambiguous:
3468 return OR_Ambiguous;
3469 }
3470
3471 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 3471)
;
3472}
3473
3474bool
3475Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3476 ImplicitConversionSequence ICS;
3477 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3478 OverloadCandidateSet::CSK_Normal);
3479 OverloadingResult OvResult =
3480 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3481 CandidateSet, false, false);
3482 if (OvResult == OR_Ambiguous)
3483 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3484 << From->getType() << ToType << From->getSourceRange();
3485 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3486 if (!RequireCompleteType(From->getLocStart(), ToType,
3487 diag::err_typecheck_nonviable_condition_incomplete,
3488 From->getType(), From->getSourceRange()))
3489 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3490 << false << From->getType() << From->getSourceRange() << ToType;
3491 } else
3492 return false;
3493 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3494 return true;
3495}
3496
3497/// Compare the user-defined conversion functions or constructors
3498/// of two user-defined conversion sequences to determine whether any ordering
3499/// is possible.
3500static ImplicitConversionSequence::CompareKind
3501compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3502 FunctionDecl *Function2) {
3503 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3504 return ImplicitConversionSequence::Indistinguishable;
3505
3506 // Objective-C++:
3507 // If both conversion functions are implicitly-declared conversions from
3508 // a lambda closure type to a function pointer and a block pointer,
3509 // respectively, always prefer the conversion to a function pointer,
3510 // because the function pointer is more lightweight and is more likely
3511 // to keep code working.
3512 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3513 if (!Conv1)
3514 return ImplicitConversionSequence::Indistinguishable;
3515
3516 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3517 if (!Conv2)
3518 return ImplicitConversionSequence::Indistinguishable;
3519
3520 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3521 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3522 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3523 if (Block1 != Block2)
3524 return Block1 ? ImplicitConversionSequence::Worse
3525 : ImplicitConversionSequence::Better;
3526 }
3527
3528 return ImplicitConversionSequence::Indistinguishable;
3529}
3530
3531static bool hasDeprecatedStringLiteralToCharPtrConversion(
3532 const ImplicitConversionSequence &ICS) {
3533 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3534 (ICS.isUserDefined() &&
3535 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3536}
3537
3538/// CompareImplicitConversionSequences - Compare two implicit
3539/// conversion sequences to determine whether one is better than the
3540/// other or if they are indistinguishable (C++ 13.3.3.2).
3541static ImplicitConversionSequence::CompareKind
3542CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3543 const ImplicitConversionSequence& ICS1,
3544 const ImplicitConversionSequence& ICS2)
3545{
3546 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3547 // conversion sequences (as defined in 13.3.3.1)
3548 // -- a standard conversion sequence (13.3.3.1.1) is a better
3549 // conversion sequence than a user-defined conversion sequence or
3550 // an ellipsis conversion sequence, and
3551 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3552 // conversion sequence than an ellipsis conversion sequence
3553 // (13.3.3.1.3).
3554 //
3555 // C++0x [over.best.ics]p10:
3556 // For the purpose of ranking implicit conversion sequences as
3557 // described in 13.3.3.2, the ambiguous conversion sequence is
3558 // treated as a user-defined sequence that is indistinguishable
3559 // from any other user-defined conversion sequence.
3560
3561 // String literal to 'char *' conversion has been deprecated in C++03. It has
3562 // been removed from C++11. We still accept this conversion, if it happens at
3563 // the best viable function. Otherwise, this conversion is considered worse
3564 // than ellipsis conversion. Consider this as an extension; this is not in the
3565 // standard. For example:
3566 //
3567 // int &f(...); // #1
3568 // void f(char*); // #2
3569 // void g() { int &r = f("foo"); }
3570 //
3571 // In C++03, we pick #2 as the best viable function.
3572 // In C++11, we pick #1 as the best viable function, because ellipsis
3573 // conversion is better than string-literal to char* conversion (since there
3574 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3575 // convert arguments, #2 would be the best viable function in C++11.
3576 // If the best viable function has this conversion, a warning will be issued
3577 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3578
3579 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3580 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3581 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3582 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3583 ? ImplicitConversionSequence::Worse
3584 : ImplicitConversionSequence::Better;
3585
3586 if (ICS1.getKindRank() < ICS2.getKindRank())
3587 return ImplicitConversionSequence::Better;
3588 if (ICS2.getKindRank() < ICS1.getKindRank())
3589 return ImplicitConversionSequence::Worse;
3590
3591 // The following checks require both conversion sequences to be of
3592 // the same kind.
3593 if (ICS1.getKind() != ICS2.getKind())
3594 return ImplicitConversionSequence::Indistinguishable;
3595
3596 ImplicitConversionSequence::CompareKind Result =
3597 ImplicitConversionSequence::Indistinguishable;
3598
3599 // Two implicit conversion sequences of the same form are
3600 // indistinguishable conversion sequences unless one of the
3601 // following rules apply: (C++ 13.3.3.2p3):
3602
3603 // List-initialization sequence L1 is a better conversion sequence than
3604 // list-initialization sequence L2 if:
3605 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3606 // if not that,
3607 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3608 // and N1 is smaller than N2.,
3609 // even if one of the other rules in this paragraph would otherwise apply.
3610 if (!ICS1.isBad()) {
3611 if (ICS1.isStdInitializerListElement() &&
3612 !ICS2.isStdInitializerListElement())
3613 return ImplicitConversionSequence::Better;
3614 if (!ICS1.isStdInitializerListElement() &&
3615 ICS2.isStdInitializerListElement())
3616 return ImplicitConversionSequence::Worse;
3617 }
3618
3619 if (ICS1.isStandard())
3620 // Standard conversion sequence S1 is a better conversion sequence than
3621 // standard conversion sequence S2 if [...]
3622 Result = CompareStandardConversionSequences(S, Loc,
3623 ICS1.Standard, ICS2.Standard);
3624 else if (ICS1.isUserDefined()) {
3625 // User-defined conversion sequence U1 is a better conversion
3626 // sequence than another user-defined conversion sequence U2 if
3627 // they contain the same user-defined conversion function or
3628 // constructor and if the second standard conversion sequence of
3629 // U1 is better than the second standard conversion sequence of
3630 // U2 (C++ 13.3.3.2p3).
3631 if (ICS1.UserDefined.ConversionFunction ==
3632 ICS2.UserDefined.ConversionFunction)
3633 Result = CompareStandardConversionSequences(S, Loc,
3634 ICS1.UserDefined.After,
3635 ICS2.UserDefined.After);
3636 else
3637 Result = compareConversionFunctions(S,
3638 ICS1.UserDefined.ConversionFunction,
3639 ICS2.UserDefined.ConversionFunction);
3640 }
3641
3642 return Result;
3643}
3644
3645// Per 13.3.3.2p3, compare the given standard conversion sequences to
3646// determine if one is a proper subset of the other.
3647static ImplicitConversionSequence::CompareKind
3648compareStandardConversionSubsets(ASTContext &Context,
3649 const StandardConversionSequence& SCS1,
3650 const StandardConversionSequence& SCS2) {
3651 ImplicitConversionSequence::CompareKind Result
3652 = ImplicitConversionSequence::Indistinguishable;
3653
3654 // the identity conversion sequence is considered to be a subsequence of
3655 // any non-identity conversion sequence
3656 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3657 return ImplicitConversionSequence::Better;
3658 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3659 return ImplicitConversionSequence::Worse;
3660
3661 if (SCS1.Second != SCS2.Second) {
3662 if (SCS1.Second == ICK_Identity)
3663 Result = ImplicitConversionSequence::Better;
3664 else if (SCS2.Second == ICK_Identity)
3665 Result = ImplicitConversionSequence::Worse;
3666 else
3667 return ImplicitConversionSequence::Indistinguishable;
3668 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3669 return ImplicitConversionSequence::Indistinguishable;
3670
3671 if (SCS1.Third == SCS2.Third) {
3672 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3673 : ImplicitConversionSequence::Indistinguishable;
3674 }
3675
3676 if (SCS1.Third == ICK_Identity)
3677 return Result == ImplicitConversionSequence::Worse
3678 ? ImplicitConversionSequence::Indistinguishable
3679 : ImplicitConversionSequence::Better;
3680
3681 if (SCS2.Third == ICK_Identity)
3682 return Result == ImplicitConversionSequence::Better
3683 ? ImplicitConversionSequence::Indistinguishable
3684 : ImplicitConversionSequence::Worse;
3685
3686 return ImplicitConversionSequence::Indistinguishable;
3687}
3688
3689/// Determine whether one of the given reference bindings is better
3690/// than the other based on what kind of bindings they are.
3691static bool
3692isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3693 const StandardConversionSequence &SCS2) {
3694 // C++0x [over.ics.rank]p3b4:
3695 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3696 // implicit object parameter of a non-static member function declared
3697 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3698 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3699 // lvalue reference to a function lvalue and S2 binds an rvalue
3700 // reference*.
3701 //
3702 // FIXME: Rvalue references. We're going rogue with the above edits,
3703 // because the semantics in the current C++0x working paper (N3225 at the
3704 // time of this writing) break the standard definition of std::forward
3705 // and std::reference_wrapper when dealing with references to functions.
3706 // Proposed wording changes submitted to CWG for consideration.
3707 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3708 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3709 return false;
3710
3711 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3712 SCS2.IsLvalueReference) ||
3713 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3714 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3715}
3716
3717/// CompareStandardConversionSequences - Compare two standard
3718/// conversion sequences to determine whether one is better than the
3719/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3720static ImplicitConversionSequence::CompareKind
3721CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3722 const StandardConversionSequence& SCS1,
3723 const StandardConversionSequence& SCS2)
3724{
3725 // Standard conversion sequence S1 is a better conversion sequence
3726 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3727
3728 // -- S1 is a proper subsequence of S2 (comparing the conversion
3729 // sequences in the canonical form defined by 13.3.3.1.1,
3730 // excluding any Lvalue Transformation; the identity conversion
3731 // sequence is considered to be a subsequence of any
3732 // non-identity conversion sequence) or, if not that,
3733 if (ImplicitConversionSequence::CompareKind CK
3734 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3735 return CK;
3736
3737 // -- the rank of S1 is better than the rank of S2 (by the rules
3738 // defined below), or, if not that,
3739 ImplicitConversionRank Rank1 = SCS1.getRank();
3740 ImplicitConversionRank Rank2 = SCS2.getRank();
3741 if (Rank1 < Rank2)
3742 return ImplicitConversionSequence::Better;
3743 else if (Rank2 < Rank1)
3744 return ImplicitConversionSequence::Worse;
3745
3746 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3747 // are indistinguishable unless one of the following rules
3748 // applies:
3749
3750 // A conversion that is not a conversion of a pointer, or
3751 // pointer to member, to bool is better than another conversion
3752 // that is such a conversion.
3753 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3754 return SCS2.isPointerConversionToBool()
3755 ? ImplicitConversionSequence::Better
3756 : ImplicitConversionSequence::Worse;
3757
3758 // C++ [over.ics.rank]p4b2:
3759 //
3760 // If class B is derived directly or indirectly from class A,
3761 // conversion of B* to A* is better than conversion of B* to
3762 // void*, and conversion of A* to void* is better than conversion
3763 // of B* to void*.
3764 bool SCS1ConvertsToVoid
3765 = SCS1.isPointerConversionToVoidPointer(S.Context);
3766 bool SCS2ConvertsToVoid
3767 = SCS2.isPointerConversionToVoidPointer(S.Context);
3768 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3769 // Exactly one of the conversion sequences is a conversion to
3770 // a void pointer; it's the worse conversion.
3771 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3772 : ImplicitConversionSequence::Worse;
3773 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3774 // Neither conversion sequence converts to a void pointer; compare
3775 // their derived-to-base conversions.
3776 if (ImplicitConversionSequence::CompareKind DerivedCK
3777 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3778 return DerivedCK;
3779 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3780 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3781 // Both conversion sequences are conversions to void
3782 // pointers. Compare the source types to determine if there's an
3783 // inheritance relationship in their sources.
3784 QualType FromType1 = SCS1.getFromType();
3785 QualType FromType2 = SCS2.getFromType();
3786
3787 // Adjust the types we're converting from via the array-to-pointer
3788 // conversion, if we need to.
3789 if (SCS1.First == ICK_Array_To_Pointer)
3790 FromType1 = S.Context.getArrayDecayedType(FromType1);
3791 if (SCS2.First == ICK_Array_To_Pointer)
3792 FromType2 = S.Context.getArrayDecayedType(FromType2);
3793
3794 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3795 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3796
3797 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3798 return ImplicitConversionSequence::Better;
3799 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3800 return ImplicitConversionSequence::Worse;
3801
3802 // Objective-C++: If one interface is more specific than the
3803 // other, it is the better one.
3804 const ObjCObjectPointerType* FromObjCPtr1
3805 = FromType1->getAs<ObjCObjectPointerType>();
3806 const ObjCObjectPointerType* FromObjCPtr2
3807 = FromType2->getAs<ObjCObjectPointerType>();
3808 if (FromObjCPtr1 && FromObjCPtr2) {
3809 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3810 FromObjCPtr2);
3811 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3812 FromObjCPtr1);
3813 if (AssignLeft != AssignRight) {
3814 return AssignLeft? ImplicitConversionSequence::Better
3815 : ImplicitConversionSequence::Worse;
3816 }
3817 }
3818 }
3819
3820 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3821 // bullet 3).
3822 if (ImplicitConversionSequence::CompareKind QualCK
3823 = CompareQualificationConversions(S, SCS1, SCS2))
3824 return QualCK;
3825
3826 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3827 // Check for a better reference binding based on the kind of bindings.
3828 if (isBetterReferenceBindingKind(SCS1, SCS2))
3829 return ImplicitConversionSequence::Better;
3830 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3831 return ImplicitConversionSequence::Worse;
3832
3833 // C++ [over.ics.rank]p3b4:
3834 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3835 // which the references refer are the same type except for
3836 // top-level cv-qualifiers, and the type to which the reference
3837 // initialized by S2 refers is more cv-qualified than the type
3838 // to which the reference initialized by S1 refers.
3839 QualType T1 = SCS1.getToType(2);
3840 QualType T2 = SCS2.getToType(2);
3841 T1 = S.Context.getCanonicalType(T1);
3842 T2 = S.Context.getCanonicalType(T2);
3843 Qualifiers T1Quals, T2Quals;
3844 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3845 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3846 if (UnqualT1 == UnqualT2) {
3847 // Objective-C++ ARC: If the references refer to objects with different
3848 // lifetimes, prefer bindings that don't change lifetime.
3849 if (SCS1.ObjCLifetimeConversionBinding !=
3850 SCS2.ObjCLifetimeConversionBinding) {
3851 return SCS1.ObjCLifetimeConversionBinding
3852 ? ImplicitConversionSequence::Worse
3853 : ImplicitConversionSequence::Better;
3854 }
3855
3856 // If the type is an array type, promote the element qualifiers to the
3857 // type for comparison.
3858 if (isa<ArrayType>(T1) && T1Quals)
3859 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3860 if (isa<ArrayType>(T2) && T2Quals)
3861 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3862 if (T2.isMoreQualifiedThan(T1))
3863 return ImplicitConversionSequence::Better;
3864 else if (T1.isMoreQualifiedThan(T2))
3865 return ImplicitConversionSequence::Worse;
3866 }
3867 }
3868
3869 // In Microsoft mode, prefer an integral conversion to a
3870 // floating-to-integral conversion if the integral conversion
3871 // is between types of the same size.
3872 // For example:
3873 // void f(float);
3874 // void f(int);
3875 // int main {
3876 // long a;
3877 // f(a);
3878 // }
3879 // Here, MSVC will call f(int) instead of generating a compile error
3880 // as clang will do in standard mode.
3881 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3882 SCS2.Second == ICK_Floating_Integral &&
3883 S.Context.getTypeSize(SCS1.getFromType()) ==
3884 S.Context.getTypeSize(SCS1.getToType(2)))
3885 return ImplicitConversionSequence::Better;
3886
3887 return ImplicitConversionSequence::Indistinguishable;
3888}
3889
3890/// CompareQualificationConversions - Compares two standard conversion
3891/// sequences to determine whether they can be ranked based on their
3892/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3893static ImplicitConversionSequence::CompareKind
3894CompareQualificationConversions(Sema &S,
3895 const StandardConversionSequence& SCS1,
3896 const StandardConversionSequence& SCS2) {
3897 // C++ 13.3.3.2p3:
3898 // -- S1 and S2 differ only in their qualification conversion and
3899 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3900 // cv-qualification signature of type T1 is a proper subset of
3901 // the cv-qualification signature of type T2, and S1 is not the
3902 // deprecated string literal array-to-pointer conversion (4.2).
3903 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3904 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3905 return ImplicitConversionSequence::Indistinguishable;
3906
3907 // FIXME: the example in the standard doesn't use a qualification
3908 // conversion (!)
3909 QualType T1 = SCS1.getToType(2);
3910 QualType T2 = SCS2.getToType(2);
3911 T1 = S.Context.getCanonicalType(T1);
3912 T2 = S.Context.getCanonicalType(T2);
3913 Qualifiers T1Quals, T2Quals;
3914 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3915 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3916
3917 // If the types are the same, we won't learn anything by unwrapped
3918 // them.
3919 if (UnqualT1 == UnqualT2)
3920 return ImplicitConversionSequence::Indistinguishable;
3921
3922 // If the type is an array type, promote the element qualifiers to the type
3923 // for comparison.
3924 if (isa<ArrayType>(T1) && T1Quals)
3925 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3926 if (isa<ArrayType>(T2) && T2Quals)
3927 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3928
3929 ImplicitConversionSequence::CompareKind Result
3930 = ImplicitConversionSequence::Indistinguishable;
3931
3932 // Objective-C++ ARC:
3933 // Prefer qualification conversions not involving a change in lifetime
3934 // to qualification conversions that do not change lifetime.
3935 if (SCS1.QualificationIncludesObjCLifetime !=
3936 SCS2.QualificationIncludesObjCLifetime) {
3937 Result = SCS1.QualificationIncludesObjCLifetime
3938 ? ImplicitConversionSequence::Worse
3939 : ImplicitConversionSequence::Better;
3940 }
3941
3942 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
3943 // Within each iteration of the loop, we check the qualifiers to
3944 // determine if this still looks like a qualification
3945 // conversion. Then, if all is well, we unwrap one more level of
3946 // pointers or pointers-to-members and do it all again
3947 // until there are no more pointers or pointers-to-members left
3948 // to unwrap. This essentially mimics what
3949 // IsQualificationConversion does, but here we're checking for a
3950 // strict subset of qualifiers.
3951 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3952 // The qualifiers are the same, so this doesn't tell us anything
3953 // about how the sequences rank.
3954 ;
3955 else if (T2.isMoreQualifiedThan(T1)) {
3956 // T1 has fewer qualifiers, so it could be the better sequence.
3957 if (Result == ImplicitConversionSequence::Worse)
3958 // Neither has qualifiers that are a subset of the other's
3959 // qualifiers.
3960 return ImplicitConversionSequence::Indistinguishable;
3961
3962 Result = ImplicitConversionSequence::Better;
3963 } else if (T1.isMoreQualifiedThan(T2)) {
3964 // T2 has fewer qualifiers, so it could be the better sequence.
3965 if (Result == ImplicitConversionSequence::Better)
3966 // Neither has qualifiers that are a subset of the other's
3967 // qualifiers.
3968 return ImplicitConversionSequence::Indistinguishable;
3969
3970 Result = ImplicitConversionSequence::Worse;
3971 } else {
3972 // Qualifiers are disjoint.
3973 return ImplicitConversionSequence::Indistinguishable;
3974 }
3975
3976 // If the types after this point are equivalent, we're done.
3977 if (S.Context.hasSameUnqualifiedType(T1, T2))
3978 break;
3979 }
3980
3981 // Check that the winning standard conversion sequence isn't using
3982 // the deprecated string literal array to pointer conversion.
3983 switch (Result) {
3984 case ImplicitConversionSequence::Better:
3985 if (SCS1.DeprecatedStringLiteralToCharPtr)
3986 Result = ImplicitConversionSequence::Indistinguishable;
3987 break;
3988
3989 case ImplicitConversionSequence::Indistinguishable:
3990 break;
3991
3992 case ImplicitConversionSequence::Worse:
3993 if (SCS2.DeprecatedStringLiteralToCharPtr)
3994 Result = ImplicitConversionSequence::Indistinguishable;
3995 break;
3996 }
3997
3998 return Result;
3999}
4000
4001/// CompareDerivedToBaseConversions - Compares two standard conversion
4002/// sequences to determine whether they can be ranked based on their
4003/// various kinds of derived-to-base conversions (C++
4004/// [over.ics.rank]p4b3). As part of these checks, we also look at
4005/// conversions between Objective-C interface types.
4006static ImplicitConversionSequence::CompareKind
4007CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4008 const StandardConversionSequence& SCS1,
4009 const StandardConversionSequence& SCS2) {
4010 QualType FromType1 = SCS1.getFromType();
4011 QualType ToType1 = SCS1.getToType(1);
4012 QualType FromType2 = SCS2.getFromType();
4013 QualType ToType2 = SCS2.getToType(1);
4014
4015 // Adjust the types we're converting from via the array-to-pointer
4016 // conversion, if we need to.
4017 if (SCS1.First == ICK_Array_To_Pointer)
4018 FromType1 = S.Context.getArrayDecayedType(FromType1);
4019 if (SCS2.First == ICK_Array_To_Pointer)
4020 FromType2 = S.Context.getArrayDecayedType(FromType2);
4021
4022 // Canonicalize all of the types.
4023 FromType1 = S.Context.getCanonicalType(FromType1);
4024 ToType1 = S.Context.getCanonicalType(ToType1);
4025 FromType2 = S.Context.getCanonicalType(FromType2);
4026 ToType2 = S.Context.getCanonicalType(ToType2);
4027
4028 // C++ [over.ics.rank]p4b3:
4029 //
4030 // If class B is derived directly or indirectly from class A and
4031 // class C is derived directly or indirectly from B,
4032 //
4033 // Compare based on pointer conversions.
4034 if (SCS1.Second == ICK_Pointer_Conversion &&
4035 SCS2.Second == ICK_Pointer_Conversion &&
4036 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4037 FromType1->isPointerType() && FromType2->isPointerType() &&
4038 ToType1->isPointerType() && ToType2->isPointerType()) {
4039 QualType FromPointee1
4040 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4041 QualType ToPointee1
4042 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4043 QualType FromPointee2
4044 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4045 QualType ToPointee2
4046 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4047
4048 // -- conversion of C* to B* is better than conversion of C* to A*,
4049 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4050 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4051 return ImplicitConversionSequence::Better;
4052 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4053 return ImplicitConversionSequence::Worse;
4054 }
4055
4056 // -- conversion of B* to A* is better than conversion of C* to A*,
4057 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4058 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4059 return ImplicitConversionSequence::Better;
4060 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4061 return ImplicitConversionSequence::Worse;
4062 }
4063 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4064 SCS2.Second == ICK_Pointer_Conversion) {
4065 const ObjCObjectPointerType *FromPtr1
4066 = FromType1->getAs<ObjCObjectPointerType>();
4067 const ObjCObjectPointerType *FromPtr2
4068 = FromType2->getAs<ObjCObjectPointerType>();
4069 const ObjCObjectPointerType *ToPtr1
4070 = ToType1->getAs<ObjCObjectPointerType>();
4071 const ObjCObjectPointerType *ToPtr2
4072 = ToType2->getAs<ObjCObjectPointerType>();
4073
4074 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4075 // Apply the same conversion ranking rules for Objective-C pointer types
4076 // that we do for C++ pointers to class types. However, we employ the
4077 // Objective-C pseudo-subtyping relationship used for assignment of
4078 // Objective-C pointer types.
4079 bool FromAssignLeft
4080 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4081 bool FromAssignRight
4082 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4083 bool ToAssignLeft
4084 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4085 bool ToAssignRight
4086 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4087
4088 // A conversion to an a non-id object pointer type or qualified 'id'
4089 // type is better than a conversion to 'id'.
4090 if (ToPtr1->isObjCIdType() &&
4091 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4092 return ImplicitConversionSequence::Worse;
4093 if (ToPtr2->isObjCIdType() &&
4094 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4095 return ImplicitConversionSequence::Better;
4096
4097 // A conversion to a non-id object pointer type is better than a
4098 // conversion to a qualified 'id' type
4099 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4100 return ImplicitConversionSequence::Worse;
4101 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4102 return ImplicitConversionSequence::Better;
4103
4104 // A conversion to an a non-Class object pointer type or qualified 'Class'
4105 // type is better than a conversion to 'Class'.
4106 if (ToPtr1->isObjCClassType() &&
4107 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4108 return ImplicitConversionSequence::Worse;
4109 if (ToPtr2->isObjCClassType() &&
4110 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4111 return ImplicitConversionSequence::Better;
4112
4113 // A conversion to a non-Class object pointer type is better than a
4114 // conversion to a qualified 'Class' type.
4115 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4116 return ImplicitConversionSequence::Worse;
4117 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4118 return ImplicitConversionSequence::Better;
4119
4120 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4121 if (S.Context.hasSameType(FromType1, FromType2) &&
4122 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4123 (ToAssignLeft != ToAssignRight)) {
4124 if (FromPtr1->isSpecialized()) {
4125 // "conversion of B<A> * to B * is better than conversion of B * to
4126 // C *.
4127 bool IsFirstSame =
4128 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4129 bool IsSecondSame =
4130 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4131 if (IsFirstSame) {
4132 if (!IsSecondSame)
4133 return ImplicitConversionSequence::Better;
4134 } else if (IsSecondSame)
4135 return ImplicitConversionSequence::Worse;
4136 }
4137 return ToAssignLeft? ImplicitConversionSequence::Worse
4138 : ImplicitConversionSequence::Better;
4139 }
4140
4141 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4142 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4143 (FromAssignLeft != FromAssignRight))
4144 return FromAssignLeft? ImplicitConversionSequence::Better
4145 : ImplicitConversionSequence::Worse;
4146 }
4147 }
4148
4149 // Ranking of member-pointer types.
4150 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4151 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4152 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4153 const MemberPointerType * FromMemPointer1 =
4154 FromType1->getAs<MemberPointerType>();
4155 const MemberPointerType * ToMemPointer1 =
4156 ToType1->getAs<MemberPointerType>();
4157 const MemberPointerType * FromMemPointer2 =
4158 FromType2->getAs<MemberPointerType>();
4159 const MemberPointerType * ToMemPointer2 =
4160 ToType2->getAs<MemberPointerType>();
4161 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4162 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4163 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4164 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4165 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4166 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4167 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4168 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4169 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4170 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4171 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4172 return ImplicitConversionSequence::Worse;
4173 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4174 return ImplicitConversionSequence::Better;
4175 }
4176 // conversion of B::* to C::* is better than conversion of A::* to C::*
4177 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4178 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4179 return ImplicitConversionSequence::Better;
4180 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4181 return ImplicitConversionSequence::Worse;
4182 }
4183 }
4184
4185 if (SCS1.Second == ICK_Derived_To_Base) {
4186 // -- conversion of C to B is better than conversion of C to A,
4187 // -- binding of an expression of type C to a reference of type
4188 // B& is better than binding an expression of type C to a
4189 // reference of type A&,
4190 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4191 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4192 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4193 return ImplicitConversionSequence::Better;
4194 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4195 return ImplicitConversionSequence::Worse;
4196 }
4197
4198 // -- conversion of B to A is better than conversion of C to A.
4199 // -- binding of an expression of type B to a reference of type
4200 // A& is better than binding an expression of type C to a
4201 // reference of type A&,
4202 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4203 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4204 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4205 return ImplicitConversionSequence::Better;
4206 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4207 return ImplicitConversionSequence::Worse;
4208 }
4209 }
4210
4211 return ImplicitConversionSequence::Indistinguishable;
4212}
4213
4214/// Determine whether the given type is valid, e.g., it is not an invalid
4215/// C++ class.
4216static bool isTypeValid(QualType T) {
4217 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4218 return !Record->isInvalidDecl();
4219
4220 return true;
4221}
4222
4223/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4224/// determine whether they are reference-related,
4225/// reference-compatible, reference-compatible with added
4226/// qualification, or incompatible, for use in C++ initialization by
4227/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4228/// type, and the first type (T1) is the pointee type of the reference
4229/// type being initialized.
4230Sema::ReferenceCompareResult
4231Sema::CompareReferenceRelationship(SourceLocation Loc,
4232 QualType OrigT1, QualType OrigT2,
4233 bool &DerivedToBase,
4234 bool &ObjCConversion,
4235 bool &ObjCLifetimeConversion) {
4236 assert(!OrigT1->isReferenceType() &&(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4237, __extension__ __PRETTY_FUNCTION__))
4237 "T1 must be the pointee type of the reference type")(static_cast <bool> (!OrigT1->isReferenceType() &&
"T1 must be the pointee type of the reference type") ? void (
0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4237, __extension__ __PRETTY_FUNCTION__))
;
4238 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")(static_cast <bool> (!OrigT2->isReferenceType() &&
"T2 cannot be a reference type") ? void (0) : __assert_fail (
"!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4238, __extension__ __PRETTY_FUNCTION__))
;
4239
4240 QualType T1 = Context.getCanonicalType(OrigT1);
4241 QualType T2 = Context.getCanonicalType(OrigT2);
4242 Qualifiers T1Quals, T2Quals;
4243 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4244 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4245
4246 // C++ [dcl.init.ref]p4:
4247 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4248 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4249 // T1 is a base class of T2.
4250 DerivedToBase = false;
4251 ObjCConversion = false;
4252 ObjCLifetimeConversion = false;
4253 QualType ConvertedT2;
4254 if (UnqualT1 == UnqualT2) {
4255 // Nothing to do.
4256 } else if (isCompleteType(Loc, OrigT2) &&
4257 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4258 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4259 DerivedToBase = true;
4260 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4261 UnqualT2->isObjCObjectOrInterfaceType() &&
4262 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4263 ObjCConversion = true;
4264 else if (UnqualT2->isFunctionType() &&
4265 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4266 // C++1z [dcl.init.ref]p4:
4267 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4268 // function" and T1 is "function"
4269 //
4270 // We extend this to also apply to 'noreturn', so allow any function
4271 // conversion between function types.
4272 return Ref_Compatible;
4273 else
4274 return Ref_Incompatible;
4275
4276 // At this point, we know that T1 and T2 are reference-related (at
4277 // least).
4278
4279 // If the type is an array type, promote the element qualifiers to the type
4280 // for comparison.
4281 if (isa<ArrayType>(T1) && T1Quals)
4282 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4283 if (isa<ArrayType>(T2) && T2Quals)
4284 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4285
4286 // C++ [dcl.init.ref]p4:
4287 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4288 // reference-related to T2 and cv1 is the same cv-qualification
4289 // as, or greater cv-qualification than, cv2. For purposes of
4290 // overload resolution, cases for which cv1 is greater
4291 // cv-qualification than cv2 are identified as
4292 // reference-compatible with added qualification (see 13.3.3.2).
4293 //
4294 // Note that we also require equivalence of Objective-C GC and address-space
4295 // qualifiers when performing these computations, so that e.g., an int in
4296 // address space 1 is not reference-compatible with an int in address
4297 // space 2.
4298 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4299 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4300 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4301 ObjCLifetimeConversion = true;
4302
4303 T1Quals.removeObjCLifetime();
4304 T2Quals.removeObjCLifetime();
4305 }
4306
4307 // MS compiler ignores __unaligned qualifier for references; do the same.
4308 T1Quals.removeUnaligned();
4309 T2Quals.removeUnaligned();
4310
4311 if (T1Quals.compatiblyIncludes(T2Quals))
4312 return Ref_Compatible;
4313 else
4314 return Ref_Related;
4315}
4316
4317/// Look for a user-defined conversion to a value reference-compatible
4318/// with DeclType. Return true if something definite is found.
4319static bool
4320FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4321 QualType DeclType, SourceLocation DeclLoc,
4322 Expr *Init, QualType T2, bool AllowRvalues,
4323 bool AllowExplicit) {
4324 assert(T2->isRecordType() && "Can only find conversions of record types.")(static_cast <bool> (T2->isRecordType() && "Can only find conversions of record types."
) ? void (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4324, __extension__ __PRETTY_FUNCTION__))
;
4325 CXXRecordDecl *T2RecordDecl
4326 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4327
4328 OverloadCandidateSet CandidateSet(
4329 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4330 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4331 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4332 NamedDecl *D = *I;
4333 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4334 if (isa<UsingShadowDecl>(D))
4335 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4336
4337 FunctionTemplateDecl *ConvTemplate
4338 = dyn_cast<FunctionTemplateDecl>(D);
4339 CXXConversionDecl *Conv;
4340 if (ConvTemplate)
4341 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4342 else
4343 Conv = cast<CXXConversionDecl>(D);
4344
4345 // If this is an explicit conversion, and we're not allowed to consider
4346 // explicit conversions, skip it.
4347 if (!AllowExplicit && Conv->isExplicit())
4348 continue;
4349
4350 if (AllowRvalues) {
4351 bool DerivedToBase = false;
4352 bool ObjCConversion = false;
4353 bool ObjCLifetimeConversion = false;
4354
4355 // If we are initializing an rvalue reference, don't permit conversion
4356 // functions that return lvalues.
4357 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4358 const ReferenceType *RefType
4359 = Conv->getConversionType()->getAs<LValueReferenceType>();
4360 if (RefType && !RefType->getPointeeType()->isFunctionType())
4361 continue;
4362 }
4363
4364 if (!ConvTemplate &&
4365 S.CompareReferenceRelationship(
4366 DeclLoc,
4367 Conv->getConversionType().getNonReferenceType()
4368 .getUnqualifiedType(),
4369 DeclType.getNonReferenceType().getUnqualifiedType(),
4370 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4371 Sema::Ref_Incompatible)
4372 continue;
4373 } else {
4374 // If the conversion function doesn't return a reference type,
4375 // it can't be considered for this conversion. An rvalue reference
4376 // is only acceptable if its referencee is a function type.
4377
4378 const ReferenceType *RefType =
4379 Conv->getConversionType()->getAs<ReferenceType>();
4380 if (!RefType ||
4381 (!RefType->isLValueReferenceType() &&
4382 !RefType->getPointeeType()->isFunctionType()))
4383 continue;
4384 }
4385
4386 if (ConvTemplate)
4387 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4388 Init, DeclType, CandidateSet,
4389 /*AllowObjCConversionOnExplicit=*/false);
4390 else
4391 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4392 DeclType, CandidateSet,
4393 /*AllowObjCConversionOnExplicit=*/false);
4394 }
4395
4396 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4397
4398 OverloadCandidateSet::iterator Best;
4399 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4400 case OR_Success:
4401 // C++ [over.ics.ref]p1:
4402 //
4403 // [...] If the parameter binds directly to the result of
4404 // applying a conversion function to the argument
4405 // expression, the implicit conversion sequence is a
4406 // user-defined conversion sequence (13.3.3.1.2), with the
4407 // second standard conversion sequence either an identity
4408 // conversion or, if the conversion function returns an
4409 // entity of a type that is a derived class of the parameter
4410 // type, a derived-to-base Conversion.
4411 if (!Best->FinalConversion.DirectBinding)
4412 return false;
4413
4414 ICS.setUserDefined();
4415 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4416 ICS.UserDefined.After = Best->FinalConversion;
4417 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4418 ICS.UserDefined.ConversionFunction = Best->Function;
4419 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4420 ICS.UserDefined.EllipsisConversion = false;
4421 assert(ICS.UserDefined.After.ReferenceBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4423, __extension__ __PRETTY_FUNCTION__))
4422 ICS.UserDefined.After.DirectBinding &&(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4423, __extension__ __PRETTY_FUNCTION__))
4423 "Expected a direct reference binding!")(static_cast <bool> (ICS.UserDefined.After.ReferenceBinding
&& ICS.UserDefined.After.DirectBinding && "Expected a direct reference binding!"
) ? void (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4423, __extension__ __PRETTY_FUNCTION__))
;
4424 return true;
4425
4426 case OR_Ambiguous:
4427 ICS.setAmbiguous();
4428 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4429 Cand != CandidateSet.end(); ++Cand)
4430 if (Cand->Viable)
4431 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4432 return true;
4433
4434 case OR_No_Viable_Function:
4435 case OR_Deleted:
4436 // There was no suitable conversion, or we found a deleted
4437 // conversion; continue with other checks.
4438 return false;
4439 }
4440
4441 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4441)
;
4442}
4443
4444/// Compute an implicit conversion sequence for reference
4445/// initialization.
4446static ImplicitConversionSequence
4447TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4448 SourceLocation DeclLoc,
4449 bool SuppressUserConversions,
4450 bool AllowExplicit) {
4451 assert(DeclType->isReferenceType() && "Reference init needs a reference")(static_cast <bool> (DeclType->isReferenceType() &&
"Reference init needs a reference") ? void (0) : __assert_fail
("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4451, __extension__ __PRETTY_FUNCTION__))
;
4452
4453 // Most paths end in a failed conversion.
4454 ImplicitConversionSequence ICS;
4455 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4456
4457 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4458 QualType T2 = Init->getType();
4459
4460 // If the initializer is the address of an overloaded function, try
4461 // to resolve the overloaded function. If all goes well, T2 is the
4462 // type of the resulting function.
4463 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4464 DeclAccessPair Found;
4465 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4466 false, Found))
4467 T2 = Fn->getType();
4468 }
4469
4470 // Compute some basic properties of the types and the initializer.
4471 bool isRValRef = DeclType->isRValueReferenceType();
4472 bool DerivedToBase = false;
4473 bool ObjCConversion = false;
4474 bool ObjCLifetimeConversion = false;
4475 Expr::Classification InitCategory = Init->Classify(S.Context);
4476 Sema::ReferenceCompareResult RefRelationship
4477 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4478 ObjCConversion, ObjCLifetimeConversion);
4479
4480
4481 // C++0x [dcl.init.ref]p5:
4482 // A reference to type "cv1 T1" is initialized by an expression
4483 // of type "cv2 T2" as follows:
4484
4485 // -- If reference is an lvalue reference and the initializer expression
4486 if (!isRValRef) {
4487 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4488 // reference-compatible with "cv2 T2," or
4489 //
4490 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4491 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4492 // C++ [over.ics.ref]p1:
4493 // When a parameter of reference type binds directly (8.5.3)
4494 // to an argument expression, the implicit conversion sequence
4495 // is the identity conversion, unless the argument expression
4496 // has a type that is a derived class of the parameter type,
4497 // in which case the implicit conversion sequence is a
4498 // derived-to-base Conversion (13.3.3.1).
4499 ICS.setStandard();
4500 ICS.Standard.First = ICK_Identity;
4501 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4502 : ObjCConversion? ICK_Compatible_Conversion
4503 : ICK_Identity;
4504 ICS.Standard.Third = ICK_Identity;
4505 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4506 ICS.Standard.setToType(0, T2);
4507 ICS.Standard.setToType(1, T1);
4508 ICS.Standard.setToType(2, T1);
4509 ICS.Standard.ReferenceBinding = true;
4510 ICS.Standard.DirectBinding = true;
4511 ICS.Standard.IsLvalueReference = !isRValRef;
4512 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4513 ICS.Standard.BindsToRvalue = false;
4514 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4515 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4516 ICS.Standard.CopyConstructor = nullptr;
4517 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4518
4519 // Nothing more to do: the inaccessibility/ambiguity check for
4520 // derived-to-base conversions is suppressed when we're
4521 // computing the implicit conversion sequence (C++
4522 // [over.best.ics]p2).
4523 return ICS;
4524 }
4525
4526 // -- has a class type (i.e., T2 is a class type), where T1 is
4527 // not reference-related to T2, and can be implicitly
4528 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4529 // is reference-compatible with "cv3 T3" 92) (this
4530 // conversion is selected by enumerating the applicable
4531 // conversion functions (13.3.1.6) and choosing the best
4532 // one through overload resolution (13.3)),
4533 if (!SuppressUserConversions && T2->isRecordType() &&
4534 S.isCompleteType(DeclLoc, T2) &&
4535 RefRelationship == Sema::Ref_Incompatible) {
4536 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4537 Init, T2, /*AllowRvalues=*/false,
4538 AllowExplicit))
4539 return ICS;
4540 }
4541 }
4542
4543 // -- Otherwise, the reference shall be an lvalue reference to a
4544 // non-volatile const type (i.e., cv1 shall be const), or the reference
4545 // shall be an rvalue reference.
4546 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4547 return ICS;
4548
4549 // -- If the initializer expression
4550 //
4551 // -- is an xvalue, class prvalue, array prvalue or function
4552 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4553 if (RefRelationship == Sema::Ref_Compatible &&
4554 (InitCategory.isXValue() ||
4555 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4556 (InitCategory.isLValue() && T2->isFunctionType()))) {
4557 ICS.setStandard();
4558 ICS.Standard.First = ICK_Identity;
4559 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4560 : ObjCConversion? ICK_Compatible_Conversion
4561 : ICK_Identity;
4562 ICS.Standard.Third = ICK_Identity;
4563 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4564 ICS.Standard.setToType(0, T2);
4565 ICS.Standard.setToType(1, T1);
4566 ICS.Standard.setToType(2, T1);
4567 ICS.Standard.ReferenceBinding = true;
4568 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4569 // binding unless we're binding to a class prvalue.
4570 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4571 // allow the use of rvalue references in C++98/03 for the benefit of
4572 // standard library implementors; therefore, we need the xvalue check here.
4573 ICS.Standard.DirectBinding =
4574 S.getLangOpts().CPlusPlus11 ||
4575 !(InitCategory.isPRValue() || T2->isRecordType());
4576 ICS.Standard.IsLvalueReference = !isRValRef;
4577 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4578 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4579 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4580 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4581 ICS.Standard.CopyConstructor = nullptr;
4582 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4583 return ICS;
4584 }
4585
4586 // -- has a class type (i.e., T2 is a class type), where T1 is not
4587 // reference-related to T2, and can be implicitly converted to
4588 // an xvalue, class prvalue, or function lvalue of type
4589 // "cv3 T3", where "cv1 T1" is reference-compatible with
4590 // "cv3 T3",
4591 //
4592 // then the reference is bound to the value of the initializer
4593 // expression in the first case and to the result of the conversion
4594 // in the second case (or, in either case, to an appropriate base
4595 // class subobject).
4596 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4597 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4598 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4599 Init, T2, /*AllowRvalues=*/true,
4600 AllowExplicit)) {
4601 // In the second case, if the reference is an rvalue reference
4602 // and the second standard conversion sequence of the
4603 // user-defined conversion sequence includes an lvalue-to-rvalue
4604 // conversion, the program is ill-formed.
4605 if (ICS.isUserDefined() && isRValRef &&
4606 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4607 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4608
4609 return ICS;
4610 }
4611
4612 // A temporary of function type cannot be created; don't even try.
4613 if (T1->isFunctionType())
4614 return ICS;
4615
4616 // -- Otherwise, a temporary of type "cv1 T1" is created and
4617 // initialized from the initializer expression using the
4618 // rules for a non-reference copy initialization (8.5). The
4619 // reference is then bound to the temporary. If T1 is
4620 // reference-related to T2, cv1 must be the same
4621 // cv-qualification as, or greater cv-qualification than,
4622 // cv2; otherwise, the program is ill-formed.
4623 if (RefRelationship == Sema::Ref_Related) {
4624 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4625 // we would be reference-compatible or reference-compatible with
4626 // added qualification. But that wasn't the case, so the reference
4627 // initialization fails.
4628 //
4629 // Note that we only want to check address spaces and cvr-qualifiers here.
4630 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4631 Qualifiers T1Quals = T1.getQualifiers();
4632 Qualifiers T2Quals = T2.getQualifiers();
4633 T1Quals.removeObjCGCAttr();
4634 T1Quals.removeObjCLifetime();
4635 T2Quals.removeObjCGCAttr();
4636 T2Quals.removeObjCLifetime();
4637 // MS compiler ignores __unaligned qualifier for references; do the same.
4638 T1Quals.removeUnaligned();
4639 T2Quals.removeUnaligned();
4640 if (!T1Quals.compatiblyIncludes(T2Quals))
4641 return ICS;
4642 }
4643
4644 // If at least one of the types is a class type, the types are not
4645 // related, and we aren't allowed any user conversions, the
4646 // reference binding fails. This case is important for breaking
4647 // recursion, since TryImplicitConversion below will attempt to
4648 // create a temporary through the use of a copy constructor.
4649 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4650 (T1->isRecordType() || T2->isRecordType()))
4651 return ICS;
4652
4653 // If T1 is reference-related to T2 and the reference is an rvalue
4654 // reference, the initializer expression shall not be an lvalue.
4655 if (RefRelationship >= Sema::Ref_Related &&
4656 isRValRef && Init->Classify(S.Context).isLValue())
4657 return ICS;
4658
4659 // C++ [over.ics.ref]p2:
4660 // When a parameter of reference type is not bound directly to
4661 // an argument expression, the conversion sequence is the one
4662 // required to convert the argument expression to the
4663 // underlying type of the reference according to
4664 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4665 // to copy-initializing a temporary of the underlying type with
4666 // the argument expression. Any difference in top-level
4667 // cv-qualification is subsumed by the initialization itself
4668 // and does not constitute a conversion.
4669 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4670 /*AllowExplicit=*/false,
4671 /*InOverloadResolution=*/false,
4672 /*CStyle=*/false,
4673 /*AllowObjCWritebackConversion=*/false,
4674 /*AllowObjCConversionOnExplicit=*/false);
4675
4676 // Of course, that's still a reference binding.
4677 if (ICS.isStandard()) {
4678 ICS.Standard.ReferenceBinding = true;
4679 ICS.Standard.IsLvalueReference = !isRValRef;
4680 ICS.Standard.BindsToFunctionLvalue = false;
4681 ICS.Standard.BindsToRvalue = true;
4682 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4683 ICS.Standard.ObjCLifetimeConversionBinding = false;
4684 } else if (ICS.isUserDefined()) {
4685 const ReferenceType *LValRefType =
4686 ICS.UserDefined.ConversionFunction->getReturnType()
4687 ->getAs<LValueReferenceType>();
4688
4689 // C++ [over.ics.ref]p3:
4690 // Except for an implicit object parameter, for which see 13.3.1, a
4691 // standard conversion sequence cannot be formed if it requires [...]
4692 // binding an rvalue reference to an lvalue other than a function
4693 // lvalue.
4694 // Note that the function case is not possible here.
4695 if (DeclType->isRValueReferenceType() && LValRefType) {
4696 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4697 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4698 // reference to an rvalue!
4699 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4700 return ICS;
4701 }
4702
4703 ICS.UserDefined.After.ReferenceBinding = true;
4704 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4705 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4706 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4707 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4708 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4709 }
4710
4711 return ICS;
4712}
4713
4714static ImplicitConversionSequence
4715TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4716 bool SuppressUserConversions,
4717 bool InOverloadResolution,
4718 bool AllowObjCWritebackConversion,
4719 bool AllowExplicit = false);
4720
4721/// TryListConversion - Try to copy-initialize a value of type ToType from the
4722/// initializer list From.
4723static ImplicitConversionSequence
4724TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4725 bool SuppressUserConversions,
4726 bool InOverloadResolution,
4727 bool AllowObjCWritebackConversion) {
4728 // C++11 [over.ics.list]p1:
4729 // When an argument is an initializer list, it is not an expression and
4730 // special rules apply for converting it to a parameter type.
4731
4732 ImplicitConversionSequence Result;
4733 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4734
4735 // We need a complete type for what follows. Incomplete types can never be
4736 // initialized from init lists.
4737 if (!S.isCompleteType(From->getLocStart(), ToType))
4738 return Result;
4739
4740 // Per DR1467:
4741 // If the parameter type is a class X and the initializer list has a single
4742 // element of type cv U, where U is X or a class derived from X, the
4743 // implicit conversion sequence is the one required to convert the element
4744 // to the parameter type.
4745 //
4746 // Otherwise, if the parameter type is a character array [... ]
4747 // and the initializer list has a single element that is an
4748 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4749 // implicit conversion sequence is the identity conversion.
4750 if (From->getNumInits() == 1) {
4751 if (ToType->isRecordType()) {
4752 QualType InitType = From->getInit(0)->getType();
4753 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4754 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4755 return TryCopyInitialization(S, From->getInit(0), ToType,
4756 SuppressUserConversions,
4757 InOverloadResolution,
4758 AllowObjCWritebackConversion);
4759 }
4760 // FIXME: Check the other conditions here: array of character type,
4761 // initializer is a string literal.
4762 if (ToType->isArrayType()) {
4763 InitializedEntity Entity =
4764 InitializedEntity::InitializeParameter(S.Context, ToType,
4765 /*Consumed=*/false);
4766 if (S.CanPerformCopyInitialization(Entity, From)) {
4767 Result.setStandard();
4768 Result.Standard.setAsIdentityConversion();
4769 Result.Standard.setFromType(ToType);
4770 Result.Standard.setAllToTypes(ToType);
4771 return Result;
4772 }
4773 }
4774 }
4775
4776 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4777 // C++11 [over.ics.list]p2:
4778 // If the parameter type is std::initializer_list<X> or "array of X" and
4779 // all the elements can be implicitly converted to X, the implicit
4780 // conversion sequence is the worst conversion necessary to convert an
4781 // element of the list to X.
4782 //
4783 // C++14 [over.ics.list]p3:
4784 // Otherwise, if the parameter type is "array of N X", if the initializer
4785 // list has exactly N elements or if it has fewer than N elements and X is
4786 // default-constructible, and if all the elements of the initializer list
4787 // can be implicitly converted to X, the implicit conversion sequence is
4788 // the worst conversion necessary to convert an element of the list to X.
4789 //
4790 // FIXME: We're missing a lot of these checks.
4791 bool toStdInitializerList = false;
4792 QualType X;
4793 if (ToType->isArrayType())
4794 X = S.Context.getAsArrayType(ToType)->getElementType();
4795 else
4796 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4797 if (!X.isNull()) {
4798 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4799 Expr *Init = From->getInit(i);
4800 ImplicitConversionSequence ICS =
4801 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4802 InOverloadResolution,
4803 AllowObjCWritebackConversion);
4804 // If a single element isn't convertible, fail.
4805 if (ICS.isBad()) {
4806 Result = ICS;
4807 break;
4808 }
4809 // Otherwise, look for the worst conversion.
4810 if (Result.isBad() ||
4811 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4812 Result) ==
4813 ImplicitConversionSequence::Worse)
4814 Result = ICS;
4815 }
4816
4817 // For an empty list, we won't have computed any conversion sequence.
4818 // Introduce the identity conversion sequence.
4819 if (From->getNumInits() == 0) {
4820 Result.setStandard();
4821 Result.Standard.setAsIdentityConversion();
4822 Result.Standard.setFromType(ToType);
4823 Result.Standard.setAllToTypes(ToType);
4824 }
4825
4826 Result.setStdInitializerListElement(toStdInitializerList);
4827 return Result;
4828 }
4829
4830 // C++14 [over.ics.list]p4:
4831 // C++11 [over.ics.list]p3:
4832 // Otherwise, if the parameter is a non-aggregate class X and overload
4833 // resolution chooses a single best constructor [...] the implicit
4834 // conversion sequence is a user-defined conversion sequence. If multiple
4835 // constructors are viable but none is better than the others, the
4836 // implicit conversion sequence is a user-defined conversion sequence.
4837 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4838 // This function can deal with initializer lists.
4839 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4840 /*AllowExplicit=*/false,
4841 InOverloadResolution, /*CStyle=*/false,
4842 AllowObjCWritebackConversion,
4843 /*AllowObjCConversionOnExplicit=*/false);
4844 }
4845
4846 // C++14 [over.ics.list]p5:
4847 // C++11 [over.ics.list]p4:
4848 // Otherwise, if the parameter has an aggregate type which can be
4849 // initialized from the initializer list [...] the implicit conversion
4850 // sequence is a user-defined conversion sequence.
4851 if (ToType->isAggregateType()) {
4852 // Type is an aggregate, argument is an init list. At this point it comes
4853 // down to checking whether the initialization works.
4854 // FIXME: Find out whether this parameter is consumed or not.
4855 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4856 // need to call into the initialization code here; overload resolution
4857 // should not be doing that.
4858 InitializedEntity Entity =
4859 InitializedEntity::InitializeParameter(S.Context, ToType,
4860 /*Consumed=*/false);
4861 if (S.CanPerformCopyInitialization(Entity, From)) {
4862 Result.setUserDefined();
4863 Result.UserDefined.Before.setAsIdentityConversion();
4864 // Initializer lists don't have a type.
4865 Result.UserDefined.Before.setFromType(QualType());
4866 Result.UserDefined.Before.setAllToTypes(QualType());
4867
4868 Result.UserDefined.After.setAsIdentityConversion();
4869 Result.UserDefined.After.setFromType(ToType);
4870 Result.UserDefined.After.setAllToTypes(ToType);
4871 Result.UserDefined.ConversionFunction = nullptr;
4872 }
4873 return Result;
4874 }
4875
4876 // C++14 [over.ics.list]p6:
4877 // C++11 [over.ics.list]p5:
4878 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4879 if (ToType->isReferenceType()) {
4880 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4881 // mention initializer lists in any way. So we go by what list-
4882 // initialization would do and try to extrapolate from that.
4883
4884 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4885
4886 // If the initializer list has a single element that is reference-related
4887 // to the parameter type, we initialize the reference from that.
4888 if (From->getNumInits() == 1) {
4889 Expr *Init = From->getInit(0);
4890
4891 QualType T2 = Init->getType();
4892
4893 // If the initializer is the address of an overloaded function, try
4894 // to resolve the overloaded function. If all goes well, T2 is the
4895 // type of the resulting function.
4896 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4897 DeclAccessPair Found;
4898 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4899 Init, ToType, false, Found))
4900 T2 = Fn->getType();
4901 }
4902
4903 // Compute some basic properties of the types and the initializer.
4904 bool dummy1 = false;
4905 bool dummy2 = false;
4906 bool dummy3 = false;
4907 Sema::ReferenceCompareResult RefRelationship
4908 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4909 dummy2, dummy3);
4910
4911 if (RefRelationship >= Sema::Ref_Related) {
4912 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4913 SuppressUserConversions,
4914 /*AllowExplicit=*/false);
4915 }
4916 }
4917
4918 // Otherwise, we bind the reference to a temporary created from the
4919 // initializer list.
4920 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4921 InOverloadResolution,
4922 AllowObjCWritebackConversion);
4923 if (Result.isFailure())
4924 return Result;
4925 assert(!Result.isEllipsis() &&(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4926, __extension__ __PRETTY_FUNCTION__))
4926 "Sub-initialization cannot result in ellipsis conversion.")(static_cast <bool> (!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? void (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 4926, __extension__ __PRETTY_FUNCTION__))
;
4927
4928 // Can we even bind to a temporary?
4929 if (ToType->isRValueReferenceType() ||
4930 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4931 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4932 Result.UserDefined.After;
4933 SCS.ReferenceBinding = true;
4934 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4935 SCS.BindsToRvalue = true;
4936 SCS.BindsToFunctionLvalue = false;
4937 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4938 SCS.ObjCLifetimeConversionBinding = false;
4939 } else
4940 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4941 From, ToType);
4942 return Result;
4943 }
4944
4945 // C++14 [over.ics.list]p7:
4946 // C++11 [over.ics.list]p6:
4947 // Otherwise, if the parameter type is not a class:
4948 if (!ToType->isRecordType()) {
4949 // - if the initializer list has one element that is not itself an
4950 // initializer list, the implicit conversion sequence is the one
4951 // required to convert the element to the parameter type.
4952 unsigned NumInits = From->getNumInits();
4953 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4954 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4955 SuppressUserConversions,
4956 InOverloadResolution,
4957 AllowObjCWritebackConversion);
4958 // - if the initializer list has no elements, the implicit conversion
4959 // sequence is the identity conversion.
4960 else if (NumInits == 0) {
4961 Result.setStandard();
4962 Result.Standard.setAsIdentityConversion();
4963 Result.Standard.setFromType(ToType);
4964 Result.Standard.setAllToTypes(ToType);
4965 }
4966 return Result;
4967 }
4968
4969 // C++14 [over.ics.list]p8:
4970 // C++11 [over.ics.list]p7:
4971 // In all cases other than those enumerated above, no conversion is possible
4972 return Result;
4973}
4974
4975/// TryCopyInitialization - Try to copy-initialize a value of type
4976/// ToType from the expression From. Return the implicit conversion
4977/// sequence required to pass this argument, which may be a bad
4978/// conversion sequence (meaning that the argument cannot be passed to
4979/// a parameter of this type). If @p SuppressUserConversions, then we
4980/// do not permit any user-defined conversion sequences.
4981static ImplicitConversionSequence
4982TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4983 bool SuppressUserConversions,
4984 bool InOverloadResolution,
4985 bool AllowObjCWritebackConversion,
4986 bool AllowExplicit) {
4987 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4988 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4989 InOverloadResolution,AllowObjCWritebackConversion);
4990
4991 if (ToType->isReferenceType())
4992 return TryReferenceInit(S, From, ToType,
4993 /*FIXME:*/From->getLocStart(),
4994 SuppressUserConversions,
4995 AllowExplicit);
4996
4997 return TryImplicitConversion(S, From, ToType,
4998 SuppressUserConversions,
4999 /*AllowExplicit=*/false,
5000 InOverloadResolution,
5001 /*CStyle=*/false,
5002 AllowObjCWritebackConversion,
5003 /*AllowObjCConversionOnExplicit=*/false);
5004}
5005
5006static bool TryCopyInitialization(const CanQualType FromQTy,
5007 const CanQualType ToQTy,
5008 Sema &S,
5009 SourceLocation Loc,
5010 ExprValueKind FromVK) {
5011 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5012 ImplicitConversionSequence ICS =
5013 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5014
5015 return !ICS.isBad();
5016}
5017
5018/// TryObjectArgumentInitialization - Try to initialize the object
5019/// parameter of the given member function (@c Method) from the
5020/// expression @p From.
5021static ImplicitConversionSequence
5022TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5023 Expr::Classification FromClassification,
5024 CXXMethodDecl *Method,
5025 CXXRecordDecl *ActingContext) {
5026 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5027 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5028 // const volatile object.
5029 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5030 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5031 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
5032
5033 // Set up the conversion sequence as a "bad" conversion, to allow us
5034 // to exit early.
5035 ImplicitConversionSequence ICS;
5036
5037 // We need to have an object of class type.
5038 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5039 FromType = PT->getPointeeType();
5040
5041 // When we had a pointer, it's implicitly dereferenced, so we
5042 // better have an lvalue.
5043 assert(FromClassification.isLValue())(static_cast <bool> (FromClassification.isLValue()) ? void
(0) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5043, __extension__ __PRETTY_FUNCTION__))
;
5044 }
5045
5046 assert(FromType->isRecordType())(static_cast <bool> (FromType->isRecordType()) ? void
(0) : __assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5046, __extension__ __PRETTY_FUNCTION__))
;
5047
5048 // C++0x [over.match.funcs]p4:
5049 // For non-static member functions, the type of the implicit object
5050 // parameter is
5051 //
5052 // - "lvalue reference to cv X" for functions declared without a
5053 // ref-qualifier or with the & ref-qualifier
5054 // - "rvalue reference to cv X" for functions declared with the &&
5055 // ref-qualifier
5056 //
5057 // where X is the class of which the function is a member and cv is the
5058 // cv-qualification on the member function declaration.
5059 //
5060 // However, when finding an implicit conversion sequence for the argument, we
5061 // are not allowed to perform user-defined conversions
5062 // (C++ [over.match.funcs]p5). We perform a simplified version of
5063 // reference binding here, that allows class rvalues to bind to
5064 // non-constant references.
5065
5066 // First check the qualifiers.
5067 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5068 if (ImplicitParamType.getCVRQualifiers()
5069 != FromTypeCanon.getLocalCVRQualifiers() &&
5070 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5071 ICS.setBad(BadConversionSequence::bad_qualifiers,
5072 FromType, ImplicitParamType);
5073 return ICS;
5074 }
5075
5076 // Check that we have either the same type or a derived type. It
5077 // affects the conversion rank.
5078 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5079 ImplicitConversionKind SecondKind;
5080 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5081 SecondKind = ICK_Identity;
5082 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5083 SecondKind = ICK_Derived_To_Base;
5084 else {
5085 ICS.setBad(BadConversionSequence::unrelated_class,
5086 FromType, ImplicitParamType);
5087 return ICS;
5088 }
5089
5090 // Check the ref-qualifier.
5091 switch (Method->getRefQualifier()) {
5092 case RQ_None:
5093 // Do nothing; we don't care about lvalueness or rvalueness.
5094 break;
5095
5096 case RQ_LValue:
5097 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5098 // non-const lvalue reference cannot bind to an rvalue
5099 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5100 ImplicitParamType);
5101 return ICS;
5102 }
5103 break;
5104
5105 case RQ_RValue:
5106 if (!FromClassification.isRValue()) {
5107 // rvalue reference cannot bind to an lvalue
5108 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5109 ImplicitParamType);
5110 return ICS;
5111 }
5112 break;
5113 }
5114
5115 // Success. Mark this as a reference binding.
5116 ICS.setStandard();
5117 ICS.Standard.setAsIdentityConversion();
5118 ICS.Standard.Second = SecondKind;
5119 ICS.Standard.setFromType(FromType);
5120 ICS.Standard.setAllToTypes(ImplicitParamType);
5121 ICS.Standard.ReferenceBinding = true;
5122 ICS.Standard.DirectBinding = true;
5123 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5124 ICS.Standard.BindsToFunctionLvalue = false;
5125 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5126 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5127 = (Method->getRefQualifier() == RQ_None);
5128 return ICS;
5129}
5130
5131/// PerformObjectArgumentInitialization - Perform initialization of
5132/// the implicit object parameter for the given Method with the given
5133/// expression.
5134ExprResult
5135Sema::PerformObjectArgumentInitialization(Expr *From,
5136 NestedNameSpecifier *Qualifier,
5137 NamedDecl *FoundDecl,
5138 CXXMethodDecl *Method) {
5139 QualType FromRecordType, DestType;
5140 QualType ImplicitParamRecordType =
5141 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5142
5143 Expr::Classification FromClassification;
5144 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5145 FromRecordType = PT->getPointeeType();
5146 DestType = Method->getThisType(Context);
5147 FromClassification = Expr::Classification::makeSimpleLValue();
5148 } else {
5149 FromRecordType = From->getType();
5150 DestType = ImplicitParamRecordType;
5151 FromClassification = From->Classify(Context);
5152 }
5153
5154 // Note that we always use the true parent context when performing
5155 // the actual argument initialization.
5156 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5157 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5158 Method->getParent());
5159 if (ICS.isBad()) {
5160 switch (ICS.Bad.Kind) {
5161 case BadConversionSequence::bad_qualifiers: {
5162 Qualifiers FromQs = FromRecordType.getQualifiers();
5163 Qualifiers ToQs = DestType.getQualifiers();
5164 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5165 if (CVR) {
5166 Diag(From->getLocStart(),
5167 diag::err_member_function_call_bad_cvr)
5168 << Method->getDeclName() << FromRecordType << (CVR - 1)
5169 << From->getSourceRange();
5170 Diag(Method->getLocation(), diag::note_previous_decl)
5171 << Method->getDeclName();
5172 return ExprError();
5173 }
5174 break;
5175 }
5176
5177 case BadConversionSequence::lvalue_ref_to_rvalue:
5178 case BadConversionSequence::rvalue_ref_to_lvalue: {
5179 bool IsRValueQualified =
5180 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5181 Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5182 << Method->getDeclName() << FromClassification.isRValue()
5183 << IsRValueQualified;
5184 Diag(Method->getLocation(), diag::note_previous_decl)
5185 << Method->getDeclName();
5186 return ExprError();
5187 }
5188
5189 case BadConversionSequence::no_conversion:
5190 case BadConversionSequence::unrelated_class:
5191 break;
5192 }
5193
5194 return Diag(From->getLocStart(),
5195 diag::err_member_function_call_bad_type)
5196 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5197 }
5198
5199 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5200 ExprResult FromRes =
5201 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5202 if (FromRes.isInvalid())
5203 return ExprError();
5204 From = FromRes.get();
5205 }
5206
5207 if (!Context.hasSameType(From->getType(), DestType))
5208 From = ImpCastExprToType(From, DestType, CK_NoOp,
5209 From->getValueKind()).get();
5210 return From;
5211}
5212
5213/// TryContextuallyConvertToBool - Attempt to contextually convert the
5214/// expression From to bool (C++0x [conv]p3).
5215static ImplicitConversionSequence
5216TryContextuallyConvertToBool(Sema &S, Expr *From) {
5217 return TryImplicitConversion(S, From, S.Context.BoolTy,
5218 /*SuppressUserConversions=*/false,
5219 /*AllowExplicit=*/true,
5220 /*InOverloadResolution=*/false,
5221 /*CStyle=*/false,
5222 /*AllowObjCWritebackConversion=*/false,
5223 /*AllowObjCConversionOnExplicit=*/false);
5224}
5225
5226/// PerformContextuallyConvertToBool - Perform a contextual conversion
5227/// of the expression From to bool (C++0x [conv]p3).
5228ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5229 if (checkPlaceholderForOverload(*this, From))
5230 return ExprError();
5231
5232 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5233 if (!ICS.isBad())
5234 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5235
5236 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5237 return Diag(From->getLocStart(),
5238 diag::err_typecheck_bool_condition)
5239 << From->getType() << From->getSourceRange();
5240 return ExprError();
5241}
5242
5243/// Check that the specified conversion is permitted in a converted constant
5244/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5245/// is acceptable.
5246static bool CheckConvertedConstantConversions(Sema &S,
5247 StandardConversionSequence &SCS) {
5248 // Since we know that the target type is an integral or unscoped enumeration
5249 // type, most conversion kinds are impossible. All possible First and Third
5250 // conversions are fine.
5251 switch (SCS.Second) {
5252 case ICK_Identity:
5253 case ICK_Function_Conversion:
5254 case ICK_Integral_Promotion:
5255 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5256 case ICK_Zero_Queue_Conversion:
5257 return true;
5258
5259 case ICK_Boolean_Conversion:
5260 // Conversion from an integral or unscoped enumeration type to bool is
5261 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5262 // conversion, so we allow it in a converted constant expression.
5263 //
5264 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5265 // a lot of popular code. We should at least add a warning for this
5266 // (non-conforming) extension.
5267 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5268 SCS.getToType(2)->isBooleanType();
5269
5270 case ICK_Pointer_Conversion:
5271 case ICK_Pointer_Member:
5272 // C++1z: null pointer conversions and null member pointer conversions are
5273 // only permitted if the source type is std::nullptr_t.
5274 return SCS.getFromType()->isNullPtrType();
5275
5276 case ICK_Floating_Promotion:
5277 case ICK_Complex_Promotion:
5278 case ICK_Floating_Conversion:
5279 case ICK_Complex_Conversion:
5280 case ICK_Floating_Integral:
5281 case ICK_Compatible_Conversion:
5282 case ICK_Derived_To_Base:
5283 case ICK_Vector_Conversion:
5284 case ICK_Vector_Splat:
5285 case ICK_Complex_Real:
5286 case ICK_Block_Pointer_Conversion:
5287 case ICK_TransparentUnionConversion:
5288 case ICK_Writeback_Conversion:
5289 case ICK_Zero_Event_Conversion:
5290 case ICK_C_Only_Conversion:
5291 case ICK_Incompatible_Pointer_Conversion:
5292 return false;
5293
5294 case ICK_Lvalue_To_Rvalue:
5295 case ICK_Array_To_Pointer:
5296 case ICK_Function_To_Pointer:
5297 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5297)
;
5298
5299 case ICK_Qualification:
5300 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5300)
;
5301
5302 case ICK_Num_Conversion_Kinds:
5303 break;
5304 }
5305
5306 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5306)
;
5307}
5308
5309/// CheckConvertedConstantExpression - Check that the expression From is a
5310/// converted constant expression of type T, perform the conversion and produce
5311/// the converted expression, per C++11 [expr.const]p3.
5312static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5313 QualType T, APValue &Value,
5314 Sema::CCEKind CCE,
5315 bool RequireInt) {
5316 assert(S.getLangOpts().CPlusPlus11 &&(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5317, __extension__ __PRETTY_FUNCTION__))
5317 "converted constant expression outside C++11")(static_cast <bool> (S.getLangOpts().CPlusPlus11 &&
"converted constant expression outside C++11") ? void (0) : __assert_fail
("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5317, __extension__ __PRETTY_FUNCTION__))
;
5318
5319 if (checkPlaceholderForOverload(S, From))
5320 return ExprError();
5321
5322 // C++1z [expr.const]p3:
5323 // A converted constant expression of type T is an expression,
5324 // implicitly converted to type T, where the converted
5325 // expression is a constant expression and the implicit conversion
5326 // sequence contains only [... list of conversions ...].
5327 // C++1z [stmt.if]p2:
5328 // If the if statement is of the form if constexpr, the value of the
5329 // condition shall be a contextually converted constant expression of type
5330 // bool.
5331 ImplicitConversionSequence ICS =
5332 CCE == Sema::CCEK_ConstexprIf
5333 ? TryContextuallyConvertToBool(S, From)
5334 : TryCopyInitialization(S, From, T,
5335 /*SuppressUserConversions=*/false,
5336 /*InOverloadResolution=*/false,
5337 /*AllowObjcWritebackConversion=*/false,
5338 /*AllowExplicit=*/false);
5339 StandardConversionSequence *SCS = nullptr;
5340 switch (ICS.getKind()) {
5341 case ImplicitConversionSequence::StandardConversion:
5342 SCS = &ICS.Standard;
5343 break;
5344 case ImplicitConversionSequence::UserDefinedConversion:
5345 // We are converting to a non-class type, so the Before sequence
5346 // must be trivial.
5347 SCS = &ICS.UserDefined.After;
5348 break;
5349 case ImplicitConversionSequence::AmbiguousConversion:
5350 case ImplicitConversionSequence::BadConversion:
5351 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5352 return S.Diag(From->getLocStart(),
5353 diag::err_typecheck_converted_constant_expression)
5354 << From->getType() << From->getSourceRange() << T;
5355 return ExprError();
5356
5357 case ImplicitConversionSequence::EllipsisConversion:
5358 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5358)
;
5359 }
5360
5361 // Check that we would only use permitted conversions.
5362 if (!CheckConvertedConstantConversions(S, *SCS)) {
5363 return S.Diag(From->getLocStart(),
5364 diag::err_typecheck_converted_constant_expression_disallowed)
5365 << From->getType() << From->getSourceRange() << T;
5366 }
5367 // [...] and where the reference binding (if any) binds directly.
5368 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5369 return S.Diag(From->getLocStart(),
5370 diag::err_typecheck_converted_constant_expression_indirect)
5371 << From->getType() << From->getSourceRange() << T;
5372 }
5373
5374 ExprResult Result =
5375 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5376 if (Result.isInvalid())
5377 return Result;
5378
5379 // Check for a narrowing implicit conversion.
5380 APValue PreNarrowingValue;
5381 QualType PreNarrowingType;
5382 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5383 PreNarrowingType)) {
5384 case NK_Dependent_Narrowing:
5385 // Implicit conversion to a narrower type, but the expression is
5386 // value-dependent so we can't tell whether it's actually narrowing.
5387 case NK_Variable_Narrowing:
5388 // Implicit conversion to a narrower type, and the value is not a constant
5389 // expression. We'll diagnose this in a moment.
5390 case NK_Not_Narrowing:
5391 break;
5392
5393 case NK_Constant_Narrowing:
5394 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5395 << CCE << /*Constant*/1
5396 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5397 break;
5398
5399 case NK_Type_Narrowing:
5400 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5401 << CCE << /*Constant*/0 << From->getType() << T;
5402 break;
5403 }
5404
5405 if (Result.get()->isValueDependent()) {
5406 Value = APValue();
5407 return Result;
5408 }
5409
5410 // Check the expression is a constant expression.
5411 SmallVector<PartialDiagnosticAt, 8> Notes;
5412 Expr::EvalResult Eval;
5413 Eval.Diag = &Notes;
5414 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5415 ? Expr::EvaluateForMangling
5416 : Expr::EvaluateForCodeGen;
5417
5418 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5419 (RequireInt && !Eval.Val.isInt())) {
5420 // The expression can't be folded, so we can't keep it at this position in
5421 // the AST.
5422 Result = ExprError();
5423 } else {
5424 Value = Eval.Val;
5425
5426 if (Notes.empty()) {
5427 // It's a constant expression.
5428 return Result;
5429 }
5430 }
5431
5432 // It's not a constant expression. Produce an appropriate diagnostic.
5433 if (Notes.size() == 1 &&
5434 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5435 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5436 else {
5437 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5438 << CCE << From->getSourceRange();
5439 for (unsigned I = 0; I < Notes.size(); ++I)
5440 S.Diag(Notes[I].first, Notes[I].second);
5441 }
5442 return ExprError();
5443}
5444
5445ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5446 APValue &Value, CCEKind CCE) {
5447 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5448}
5449
5450ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5451 llvm::APSInt &Value,
5452 CCEKind CCE) {
5453 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")(static_cast <bool> (T->isIntegralOrEnumerationType(
) && "unexpected converted const type") ? void (0) : __assert_fail
("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5453, __extension__ __PRETTY_FUNCTION__))
;
5454
5455 APValue V;
5456 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5457 if (!R.isInvalid() && !R.get()->isValueDependent())
5458 Value = V.getInt();
5459 return R;
5460}
5461
5462
5463/// dropPointerConversions - If the given standard conversion sequence
5464/// involves any pointer conversions, remove them. This may change
5465/// the result type of the conversion sequence.
5466static void dropPointerConversion(StandardConversionSequence &SCS) {
5467 if (SCS.Second == ICK_Pointer_Conversion) {
5468 SCS.Second = ICK_Identity;
5469 SCS.Third = ICK_Identity;
5470 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5471 }
5472}
5473
5474/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5475/// convert the expression From to an Objective-C pointer type.
5476static ImplicitConversionSequence
5477TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5478 // Do an implicit conversion to 'id'.
5479 QualType Ty = S.Context.getObjCIdType();
5480 ImplicitConversionSequence ICS
5481 = TryImplicitConversion(S, From, Ty,
5482 // FIXME: Are these flags correct?
5483 /*SuppressUserConversions=*/false,
5484 /*AllowExplicit=*/true,
5485 /*InOverloadResolution=*/false,
5486 /*CStyle=*/false,
5487 /*AllowObjCWritebackConversion=*/false,
5488 /*AllowObjCConversionOnExplicit=*/true);
5489
5490 // Strip off any final conversions to 'id'.
5491 switch (ICS.getKind()) {
5492 case ImplicitConversionSequence::BadConversion:
5493 case ImplicitConversionSequence::AmbiguousConversion:
5494 case ImplicitConversionSequence::EllipsisConversion:
5495 break;
5496
5497 case ImplicitConversionSequence::UserDefinedConversion:
5498 dropPointerConversion(ICS.UserDefined.After);
5499 break;
5500
5501 case ImplicitConversionSequence::StandardConversion:
5502 dropPointerConversion(ICS.Standard);
5503 break;
5504 }
5505
5506 return ICS;
5507}
5508
5509/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5510/// conversion of the expression From to an Objective-C pointer type.
5511/// Returns a valid but null ExprResult if no conversion sequence exists.
5512ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5513 if (checkPlaceholderForOverload(*this, From))
5514 return ExprError();
5515
5516 QualType Ty = Context.getObjCIdType();
5517 ImplicitConversionSequence ICS =
5518 TryContextuallyConvertToObjCPointer(*this, From);
5519 if (!ICS.isBad())
5520 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5521 return ExprResult();
5522}
5523
5524/// Determine whether the provided type is an integral type, or an enumeration
5525/// type of a permitted flavor.
5526bool Sema::ICEConvertDiagnoser::match(QualType T) {
5527 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5528 : T->isIntegralOrUnscopedEnumerationType();
5529}
5530
5531static ExprResult
5532diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5533 Sema::ContextualImplicitConverter &Converter,
5534 QualType T, UnresolvedSetImpl &ViableConversions) {
5535
5536 if (Converter.Suppress)
5537 return ExprError();
5538
5539 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5540 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5541 CXXConversionDecl *Conv =
5542 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5543 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5544 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5545 }
5546 return From;
5547}
5548
5549static bool
5550diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5551 Sema::ContextualImplicitConverter &Converter,
5552 QualType T, bool HadMultipleCandidates,
5553 UnresolvedSetImpl &ExplicitConversions) {
5554 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5555 DeclAccessPair Found = ExplicitConversions[0];
5556 CXXConversionDecl *Conversion =
5557 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5558
5559 // The user probably meant to invoke the given explicit
5560 // conversion; use it.
5561 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5562 std::string TypeStr;
5563 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5564
5565 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5566 << FixItHint::CreateInsertion(From->getLocStart(),
5567 "static_cast<" + TypeStr + ">(")
5568 << FixItHint::CreateInsertion(
5569 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5570 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5571
5572 // If we aren't in a SFINAE context, build a call to the
5573 // explicit conversion function.
5574 if (SemaRef.isSFINAEContext())
5575 return true;
5576
5577 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5578 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5579 HadMultipleCandidates);
5580 if (Result.isInvalid())
5581 return true;
5582 // Record usage of conversion in an implicit cast.
5583 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5584 CK_UserDefinedConversion, Result.get(),
5585 nullptr, Result.get()->getValueKind());
5586 }
5587 return false;
5588}
5589
5590static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5591 Sema::ContextualImplicitConverter &Converter,
5592 QualType T, bool HadMultipleCandidates,
5593 DeclAccessPair &Found) {
5594 CXXConversionDecl *Conversion =
5595 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5596 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5597
5598 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5599 if (!Converter.SuppressConversion) {
5600 if (SemaRef.isSFINAEContext())
5601 return true;
5602
5603 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5604 << From->getSourceRange();
5605 }
5606
5607 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5608 HadMultipleCandidates);
5609 if (Result.isInvalid())
5610 return true;
5611 // Record usage of conversion in an implicit cast.
5612 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5613 CK_UserDefinedConversion, Result.get(),
5614 nullptr, Result.get()->getValueKind());
5615 return false;
5616}
5617
5618static ExprResult finishContextualImplicitConversion(
5619 Sema &SemaRef, SourceLocation Loc, Expr *From,
5620 Sema::ContextualImplicitConverter &Converter) {
5621 if (!Converter.match(From->getType()) && !Converter.Suppress)
5622 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5623 << From->getSourceRange();
5624
5625 return SemaRef.DefaultLvalueConversion(From);
5626}
5627
5628static void
5629collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5630 UnresolvedSetImpl &ViableConversions,
5631 OverloadCandidateSet &CandidateSet) {
5632 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5633 DeclAccessPair FoundDecl = ViableConversions[I];
5634 NamedDecl *D = FoundDecl.getDecl();
5635 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5636 if (isa<UsingShadowDecl>(D))
5637 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5638
5639 CXXConversionDecl *Conv;
5640 FunctionTemplateDecl *ConvTemplate;
5641 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5642 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5643 else
5644 Conv = cast<CXXConversionDecl>(D);
5645
5646 if (ConvTemplate)
5647 SemaRef.AddTemplateConversionCandidate(
5648 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5649 /*AllowObjCConversionOnExplicit=*/false);
5650 else
5651 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5652 ToType, CandidateSet,
5653 /*AllowObjCConversionOnExplicit=*/false);
5654 }
5655}
5656
5657/// Attempt to convert the given expression to a type which is accepted
5658/// by the given converter.
5659///
5660/// This routine will attempt to convert an expression of class type to a
5661/// type accepted by the specified converter. In C++11 and before, the class
5662/// must have a single non-explicit conversion function converting to a matching
5663/// type. In C++1y, there can be multiple such conversion functions, but only
5664/// one target type.
5665///
5666/// \param Loc The source location of the construct that requires the
5667/// conversion.
5668///
5669/// \param From The expression we're converting from.
5670///
5671/// \param Converter Used to control and diagnose the conversion process.
5672///
5673/// \returns The expression, converted to an integral or enumeration type if
5674/// successful.
5675ExprResult Sema::PerformContextualImplicitConversion(
5676 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5677 // We can't perform any more checking for type-dependent expressions.
5678 if (From->isTypeDependent())
5679 return From;
5680
5681 // Process placeholders immediately.
5682 if (From->hasPlaceholderType()) {
5683 ExprResult result = CheckPlaceholderExpr(From);
5684 if (result.isInvalid())
5685 return result;
5686 From = result.get();
5687 }
5688
5689 // If the expression already has a matching type, we're golden.
5690 QualType T = From->getType();
5691 if (Converter.match(T))
5692 return DefaultLvalueConversion(From);
5693
5694 // FIXME: Check for missing '()' if T is a function type?
5695
5696 // We can only perform contextual implicit conversions on objects of class
5697 // type.
5698 const RecordType *RecordTy = T->getAs<RecordType>();
5699 if (!RecordTy || !getLangOpts().CPlusPlus) {
5700 if (!Converter.Suppress)
5701 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5702 return From;
5703 }
5704
5705 // We must have a complete class type.
5706 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5707 ContextualImplicitConverter &Converter;
5708 Expr *From;
5709
5710 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5711 : Converter(Converter), From(From) {}
5712
5713 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5714 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5715 }
5716 } IncompleteDiagnoser(Converter, From);
5717
5718 if (Converter.Suppress ? !isCompleteType(Loc, T)
5719 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5720 return From;
5721
5722 // Look for a conversion to an integral or enumeration type.
5723 UnresolvedSet<4>
5724 ViableConversions; // These are *potentially* viable in C++1y.
5725 UnresolvedSet<4> ExplicitConversions;
5726 const auto &Conversions =
5727 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5728
5729 bool HadMultipleCandidates =
5730 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5731
5732 // To check that there is only one target type, in C++1y:
5733 QualType ToType;
5734 bool HasUniqueTargetType = true;
5735
5736 // Collect explicit or viable (potentially in C++1y) conversions.
5737 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5738 NamedDecl *D = (*I)->getUnderlyingDecl();
5739 CXXConversionDecl *Conversion;
5740 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5741 if (ConvTemplate) {
5742 if (getLangOpts().CPlusPlus14)
5743 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5744 else
5745 continue; // C++11 does not consider conversion operator templates(?).
5746 } else
5747 Conversion = cast<CXXConversionDecl>(D);
5748
5749 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5751, __extension__ __PRETTY_FUNCTION__))
5750 "Conversion operator templates are considered potentially "(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5751, __extension__ __PRETTY_FUNCTION__))
5751 "viable in C++1y")(static_cast <bool> ((!ConvTemplate || getLangOpts().CPlusPlus14
) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? void (0) : __assert_fail ("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5751, __extension__ __PRETTY_FUNCTION__))
;
5752
5753 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5754 if (Converter.match(CurToType) || ConvTemplate) {
5755
5756 if (Conversion->isExplicit()) {
5757 // FIXME: For C++1y, do we need this restriction?
5758 // cf. diagnoseNoViableConversion()
5759 if (!ConvTemplate)
5760 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5761 } else {
5762 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5763 if (ToType.isNull())
5764 ToType = CurToType.getUnqualifiedType();
5765 else if (HasUniqueTargetType &&
5766 (CurToType.getUnqualifiedType() != ToType))
5767 HasUniqueTargetType = false;
5768 }
5769 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5770 }
5771 }
5772 }
5773
5774 if (getLangOpts().CPlusPlus14) {
5775 // C++1y [conv]p6:
5776 // ... An expression e of class type E appearing in such a context
5777 // is said to be contextually implicitly converted to a specified
5778 // type T and is well-formed if and only if e can be implicitly
5779 // converted to a type T that is determined as follows: E is searched
5780 // for conversion functions whose return type is cv T or reference to
5781 // cv T such that T is allowed by the context. There shall be
5782 // exactly one such T.
5783
5784 // If no unique T is found:
5785 if (ToType.isNull()) {
5786 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5787 HadMultipleCandidates,
5788 ExplicitConversions))
5789 return ExprError();
5790 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5791 }
5792
5793 // If more than one unique Ts are found:
5794 if (!HasUniqueTargetType)
5795 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5796 ViableConversions);
5797
5798 // If one unique T is found:
5799 // First, build a candidate set from the previously recorded
5800 // potentially viable conversions.
5801 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5802 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5803 CandidateSet);
5804
5805 // Then, perform overload resolution over the candidate set.
5806 OverloadCandidateSet::iterator Best;
5807 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5808 case OR_Success: {
5809 // Apply this conversion.
5810 DeclAccessPair Found =
5811 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5812 if (recordConversion(*this, Loc, From, Converter, T,
5813 HadMultipleCandidates, Found))
5814 return ExprError();
5815 break;
5816 }
5817 case OR_Ambiguous:
5818 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5819 ViableConversions);
5820 case OR_No_Viable_Function:
5821 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5822 HadMultipleCandidates,
5823 ExplicitConversions))
5824 return ExprError();
5825 LLVM_FALLTHROUGH[[clang::fallthrough]];
5826 case OR_Deleted:
5827 // We'll complain below about a non-integral condition type.
5828 break;
5829 }
5830 } else {
5831 switch (ViableConversions.size()) {
5832 case 0: {
5833 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5834 HadMultipleCandidates,
5835 ExplicitConversions))
5836 return ExprError();
5837
5838 // We'll complain below about a non-integral condition type.
5839 break;
5840 }
5841 case 1: {
5842 // Apply this conversion.
5843 DeclAccessPair Found = ViableConversions[0];
5844 if (recordConversion(*this, Loc, From, Converter, T,
5845 HadMultipleCandidates, Found))
5846 return ExprError();
5847 break;
5848 }
5849 default:
5850 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5851 ViableConversions);
5852 }
5853 }
5854
5855 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5856}
5857
5858/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5859/// an acceptable non-member overloaded operator for a call whose
5860/// arguments have types T1 (and, if non-empty, T2). This routine
5861/// implements the check in C++ [over.match.oper]p3b2 concerning
5862/// enumeration types.
5863static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5864 FunctionDecl *Fn,
5865 ArrayRef<Expr *> Args) {
5866 QualType T1 = Args[0]->getType();
5867 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5868
5869 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5870 return true;
5871
5872 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5873 return true;
5874
5875 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5876 if (Proto->getNumParams() < 1)
5877 return false;
5878
5879 if (T1->isEnumeralType()) {
5880 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5881 if (Context.hasSameUnqualifiedType(T1, ArgType))
5882 return true;
5883 }
5884
5885 if (Proto->getNumParams() < 2)
5886 return false;
5887
5888 if (!T2.isNull() && T2->isEnumeralType()) {
5889 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5890 if (Context.hasSameUnqualifiedType(T2, ArgType))
5891 return true;
5892 }
5893
5894 return false;
5895}
5896
5897/// AddOverloadCandidate - Adds the given function to the set of
5898/// candidate functions, using the given function call arguments. If
5899/// @p SuppressUserConversions, then don't allow user-defined
5900/// conversions via constructors or conversion operators.
5901///
5902/// \param PartialOverloading true if we are performing "partial" overloading
5903/// based on an incomplete set of function arguments. This feature is used by
5904/// code completion.
5905void
5906Sema::AddOverloadCandidate(FunctionDecl *Function,
5907 DeclAccessPair FoundDecl,
5908 ArrayRef<Expr *> Args,
5909 OverloadCandidateSet &CandidateSet,
5910 bool SuppressUserConversions,
5911 bool PartialOverloading,
5912 bool AllowExplicit,
5913 ConversionSequenceList EarlyConversions) {
5914 const FunctionProtoType *Proto
5915 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5916 assert(Proto && "Functions without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Functions without a prototype cannot be overloaded"
) ? void (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5916, __extension__ __PRETTY_FUNCTION__))
;
5917 assert(!Function->getDescribedFunctionTemplate() &&(static_cast <bool> (!Function->getDescribedFunctionTemplate
() && "Use AddTemplateOverloadCandidate for function templates"
) ? void (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5918, __extension__ __PRETTY_FUNCTION__))
5918 "Use AddTemplateOverloadCandidate for function templates")(static_cast <bool> (!Function->getDescribedFunctionTemplate
() && "Use AddTemplateOverloadCandidate for function templates"
) ? void (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 5918, __extension__ __PRETTY_FUNCTION__))
;
5919
5920 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5921 if (!isa<CXXConstructorDecl>(Method)) {
5922 // If we get here, it's because we're calling a member function
5923 // that is named without a member access expression (e.g.,
5924 // "this->f") that was either written explicitly or created
5925 // implicitly. This can happen with a qualified call to a member
5926 // function, e.g., X::f(). We use an empty type for the implied
5927 // object argument (C++ [over.call.func]p3), and the acting context
5928 // is irrelevant.
5929 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5930 Expr::Classification::makeSimpleLValue(), Args,
5931 CandidateSet, SuppressUserConversions,
5932 PartialOverloading, EarlyConversions);
5933 return;
5934 }
5935 // We treat a constructor like a non-member function, since its object
5936 // argument doesn't participate in overload resolution.
5937 }
5938
5939 if (!CandidateSet.isNewCandidate(Function))
5940 return;
5941
5942 // C++ [over.match.oper]p3:
5943 // if no operand has a class type, only those non-member functions in the
5944 // lookup set that have a first parameter of type T1 or "reference to
5945 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5946 // is a right operand) a second parameter of type T2 or "reference to
5947 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5948 // candidate functions.
5949 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5950 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5951 return;
5952
5953 // C++11 [class.copy]p11: [DR1402]
5954 // A defaulted move constructor that is defined as deleted is ignored by
5955 // overload resolution.
5956 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5957 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5958 Constructor->isMoveConstructor())
5959 return;
5960
5961 // Overload resolution is always an unevaluated context.
5962 EnterExpressionEvaluationContext Unevaluated(
5963 *this, Sema::ExpressionEvaluationContext::Unevaluated);
5964
5965 // Add this candidate
5966 OverloadCandidate &Candidate =
5967 CandidateSet.addCandidate(Args.size(), EarlyConversions);
5968 Candidate.FoundDecl = FoundDecl;
5969 Candidate.Function = Function;
5970 Candidate.Viable = true;
5971 Candidate.IsSurrogate = false;
5972 Candidate.IgnoreObjectArgument = false;
5973 Candidate.ExplicitCallArguments = Args.size();
5974
5975 if (Function->isMultiVersion() &&
5976 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
5977 Candidate.Viable = false;
5978 Candidate.FailureKind = ovl_non_default_multiversion_function;
5979 return;
5980 }
5981
5982 if (Constructor) {
5983 // C++ [class.copy]p3:
5984 // A member function template is never instantiated to perform the copy
5985 // of a class object to an object of its class type.
5986 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5987 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5988 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5989 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5990 ClassType))) {
5991 Candidate.Viable = false;
5992 Candidate.FailureKind = ovl_fail_illegal_constructor;
5993 return;
5994 }
5995
5996 // C++ [over.match.funcs]p8: (proposed DR resolution)
5997 // A constructor inherited from class type C that has a first parameter
5998 // of type "reference to P" (including such a constructor instantiated
5999 // from a template) is excluded from the set of candidate functions when
6000 // constructing an object of type cv D if the argument list has exactly
6001 // one argument and D is reference-related to P and P is reference-related
6002 // to C.
6003 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6004 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6005 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6006 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6007 QualType C = Context.getRecordType(Constructor->getParent());
6008 QualType D = Context.getRecordType(Shadow->getParent());
6009 SourceLocation Loc = Args.front()->getExprLoc();
6010 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6011 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6012 Candidate.Viable = false;
6013 Candidate.FailureKind = ovl_fail_inhctor_slice;
6014 return;
6015 }
6016 }
6017 }
6018
6019 unsigned NumParams = Proto->getNumParams();
6020
6021 // (C++ 13.3.2p2): A candidate function having fewer than m
6022 // parameters is viable only if it has an ellipsis in its parameter
6023 // list (8.3.5).
6024 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6025 !Proto->isVariadic()) {
6026 Candidate.Viable = false;
6027 Candidate.FailureKind = ovl_fail_too_many_arguments;
6028 return;
6029 }
6030
6031 // (C++ 13.3.2p2): A candidate function having more than m parameters
6032 // is viable only if the (m+1)st parameter has a default argument
6033 // (8.3.6). For the purposes of overload resolution, the
6034 // parameter list is truncated on the right, so that there are
6035 // exactly m parameters.
6036 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6037 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6038 // Not enough arguments.
6039 Candidate.Viable = false;
6040 Candidate.FailureKind = ovl_fail_too_few_arguments;
6041 return;
6042 }
6043
6044 // (CUDA B.1): Check for invalid calls between targets.
6045 if (getLangOpts().CUDA)
6046 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6047 // Skip the check for callers that are implicit members, because in this
6048 // case we may not yet know what the member's target is; the target is
6049 // inferred for the member automatically, based on the bases and fields of
6050 // the class.
6051 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6052 Candidate.Viable = false;
6053 Candidate.FailureKind = ovl_fail_bad_target;
6054 return;
6055 }
6056
6057 // Determine the implicit conversion sequences for each of the
6058 // arguments.
6059 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6060 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6061 // We already formed a conversion sequence for this parameter during
6062 // template argument deduction.
6063 } else if (ArgIdx < NumParams) {
6064 // (C++ 13.3.2p3): for F to be a viable function, there shall
6065 // exist for each argument an implicit conversion sequence
6066 // (13.3.3.1) that converts that argument to the corresponding
6067 // parameter of F.
6068 QualType ParamType = Proto->getParamType(ArgIdx);
6069 Candidate.Conversions[ArgIdx]
6070 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6071 SuppressUserConversions,
6072 /*InOverloadResolution=*/true,
6073 /*AllowObjCWritebackConversion=*/
6074 getLangOpts().ObjCAutoRefCount,
6075 AllowExplicit);
6076 if (Candidate.Conversions[ArgIdx].isBad()) {
6077 Candidate.Viable = false;
6078 Candidate.FailureKind = ovl_fail_bad_conversion;
6079 return;
6080 }
6081 } else {
6082 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6083 // argument for which there is no corresponding parameter is
6084 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6085 Candidate.Conversions[ArgIdx].setEllipsis();
6086 }
6087 }
6088
6089 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6090 Candidate.Viable = false;
6091 Candidate.FailureKind = ovl_fail_enable_if;
6092 Candidate.DeductionFailure.Data = FailedAttr;
6093 return;
6094 }
6095
6096 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6097 Candidate.Viable = false;
6098 Candidate.FailureKind = ovl_fail_ext_disabled;
6099 return;
6100 }
6101}
6102
6103ObjCMethodDecl *
6104Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6105 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6106 if (Methods.size() <= 1)
6107 return nullptr;
6108
6109 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6110 bool Match = true;
6111 ObjCMethodDecl *Method = Methods[b];
6112 unsigned NumNamedArgs = Sel.getNumArgs();
6113 // Method might have more arguments than selector indicates. This is due
6114 // to addition of c-style arguments in method.
6115 if (Method->param_size() > NumNamedArgs)
6116 NumNamedArgs = Method->param_size();
6117 if (Args.size() < NumNamedArgs)
6118 continue;
6119
6120 for (unsigned i = 0; i < NumNamedArgs; i++) {
6121 // We can't do any type-checking on a type-dependent argument.
6122 if (Args[i]->isTypeDependent()) {
6123 Match = false;
6124 break;
6125 }
6126
6127 ParmVarDecl *param = Method->parameters()[i];
6128 Expr *argExpr = Args[i];
6129 assert(argExpr && "SelectBestMethod(): missing expression")(static_cast <bool> (argExpr && "SelectBestMethod(): missing expression"
) ? void (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6129, __extension__ __PRETTY_FUNCTION__))
;
6130
6131 // Strip the unbridged-cast placeholder expression off unless it's
6132 // a consumed argument.
6133 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6134 !param->hasAttr<CFConsumedAttr>())
6135 argExpr = stripARCUnbridgedCast(argExpr);
6136
6137 // If the parameter is __unknown_anytype, move on to the next method.
6138 if (param->getType() == Context.UnknownAnyTy) {
6139 Match = false;
6140 break;
6141 }
6142
6143 ImplicitConversionSequence ConversionState
6144 = TryCopyInitialization(*this, argExpr, param->getType(),
6145 /*SuppressUserConversions*/false,
6146 /*InOverloadResolution=*/true,
6147 /*AllowObjCWritebackConversion=*/
6148 getLangOpts().ObjCAutoRefCount,
6149 /*AllowExplicit*/false);
6150 // This function looks for a reasonably-exact match, so we consider
6151 // incompatible pointer conversions to be a failure here.
6152 if (ConversionState.isBad() ||
6153 (ConversionState.isStandard() &&
6154 ConversionState.Standard.Second ==
6155 ICK_Incompatible_Pointer_Conversion)) {
6156 Match = false;
6157 break;
6158 }
6159 }
6160 // Promote additional arguments to variadic methods.
6161 if (Match && Method->isVariadic()) {
6162 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6163 if (Args[i]->isTypeDependent()) {
6164 Match = false;
6165 break;
6166 }
6167 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6168 nullptr);
6169 if (Arg.isInvalid()) {
6170 Match = false;
6171 break;
6172 }
6173 }
6174 } else {
6175 // Check for extra arguments to non-variadic methods.
6176 if (Args.size() != NumNamedArgs)
6177 Match = false;
6178 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6179 // Special case when selectors have no argument. In this case, select
6180 // one with the most general result type of 'id'.
6181 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6182 QualType ReturnT = Methods[b]->getReturnType();
6183 if (ReturnT->isObjCIdType())
6184 return Methods[b];
6185 }
6186 }
6187 }
6188
6189 if (Match)
6190 return Method;
6191 }
6192 return nullptr;
6193}
6194
6195// specific_attr_iterator iterates over enable_if attributes in reverse, and
6196// enable_if is order-sensitive. As a result, we need to reverse things
6197// sometimes. Size of 4 elements is arbitrary.
6198static SmallVector<EnableIfAttr *, 4>
6199getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6200 SmallVector<EnableIfAttr *, 4> Result;
6201 if (!Function->hasAttrs())
6202 return Result;
6203
6204 const auto &FuncAttrs = Function->getAttrs();
6205 for (Attr *Attr : FuncAttrs)
6206 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6207 Result.push_back(EnableIf);
6208
6209 std::reverse(Result.begin(), Result.end());
6210 return Result;
6211}
6212
6213static bool
6214convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6215 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6216 bool MissingImplicitThis, Expr *&ConvertedThis,
6217 SmallVectorImpl<Expr *> &ConvertedArgs) {
6218 if (ThisArg) {
6219 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6220 assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Shouldn't have `this` for ctors!") ? void (0) :
__assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6221, __extension__ __PRETTY_FUNCTION__))
6221 "Shouldn't have `this` for ctors!")(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Shouldn't have `this` for ctors!") ? void (0) :
__assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Shouldn't have `this` for ctors!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6221, __extension__ __PRETTY_FUNCTION__))
;
6222 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!")(static_cast <bool> (!Method->isStatic() && "Shouldn't have `this` for static methods!"
) ? void (0) : __assert_fail ("!Method->isStatic() && \"Shouldn't have `this` for static methods!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6222, __extension__ __PRETTY_FUNCTION__))
;
6223 ExprResult R = S.PerformObjectArgumentInitialization(
6224 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6225 if (R.isInvalid())
6226 return false;
6227 ConvertedThis = R.get();
6228 } else {
6229 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6230 (void)MD;
6231 assert((MissingImplicitThis || MD->isStatic() ||(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6233, __extension__ __PRETTY_FUNCTION__))
6232 isa<CXXConstructorDecl>(MD)) &&(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6233, __extension__ __PRETTY_FUNCTION__))
6233 "Expected `this` for non-ctor instance methods")(static_cast <bool> ((MissingImplicitThis || MD->isStatic
() || isa<CXXConstructorDecl>(MD)) && "Expected `this` for non-ctor instance methods"
) ? void (0) : __assert_fail ("(MissingImplicitThis || MD->isStatic() || isa<CXXConstructorDecl>(MD)) && \"Expected `this` for non-ctor instance methods\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6233, __extension__ __PRETTY_FUNCTION__))
;
6234 }
6235 ConvertedThis = nullptr;
6236 }
6237
6238 // Ignore any variadic arguments. Converting them is pointless, since the
6239 // user can't refer to them in the function condition.
6240 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6241
6242 // Convert the arguments.
6243 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6244 ExprResult R;
6245 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6246 S.Context, Function->getParamDecl(I)),
6247 SourceLocation(), Args[I]);
6248
6249 if (R.isInvalid())
6250 return false;
6251
6252 ConvertedArgs.push_back(R.get());
6253 }
6254
6255 if (Trap.hasErrorOccurred())
6256 return false;
6257
6258 // Push default arguments if needed.
6259 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6260 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6261 ParmVarDecl *P = Function->getParamDecl(i);
6262 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6263 ? P->getUninstantiatedDefaultArg()
6264 : P->getDefaultArg();
6265 // This can only happen in code completion, i.e. when PartialOverloading
6266 // is true.
6267 if (!DefArg)
6268 return false;
6269 ExprResult R =
6270 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6271 S.Context, Function->getParamDecl(i)),
6272 SourceLocation(), DefArg);
6273 if (R.isInvalid())
6274 return false;
6275 ConvertedArgs.push_back(R.get());
6276 }
6277
6278 if (Trap.hasErrorOccurred())
6279 return false;
6280 }
6281 return true;
6282}
6283
6284EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6285 bool MissingImplicitThis) {
6286 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6287 getOrderedEnableIfAttrs(Function);
6288 if (EnableIfAttrs.empty())
6289 return nullptr;
6290
6291 SFINAETrap Trap(*this);
6292 SmallVector<Expr *, 16> ConvertedArgs;
6293 // FIXME: We should look into making enable_if late-parsed.
6294 Expr *DiscardedThis;
6295 if (!convertArgsForAvailabilityChecks(
6296 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6297 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6298 return EnableIfAttrs[0];
6299
6300 for (auto *EIA : EnableIfAttrs) {
6301 APValue Result;
6302 // FIXME: This doesn't consider value-dependent cases, because doing so is
6303 // very difficult. Ideally, we should handle them more gracefully.
6304 if (!EIA->getCond()->EvaluateWithSubstitution(
6305 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6306 return EIA;
6307
6308 if (!Result.isInt() || !Result.getInt().getBoolValue())
6309 return EIA;
6310 }
6311 return nullptr;
6312}
6313
6314template <typename CheckFn>
6315static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6316 bool ArgDependent, SourceLocation Loc,
6317 CheckFn &&IsSuccessful) {
6318 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6319 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6320 if (ArgDependent == DIA->getArgDependent())
6321 Attrs.push_back(DIA);
6322 }
6323
6324 // Common case: No diagnose_if attributes, so we can quit early.
6325 if (Attrs.empty())
6326 return false;
6327
6328 auto WarningBegin = std::stable_partition(
6329 Attrs.begin(), Attrs.end(),
6330 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6331
6332 // Note that diagnose_if attributes are late-parsed, so they appear in the
6333 // correct order (unlike enable_if attributes).
6334 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6335 IsSuccessful);
6336 if (ErrAttr != WarningBegin) {
6337 const DiagnoseIfAttr *DIA = *ErrAttr;
6338 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6339 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6340 << DIA->getParent() << DIA->getCond()->getSourceRange();
6341 return true;
6342 }
6343
6344 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6345 if (IsSuccessful(DIA)) {
6346 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6347 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6348 << DIA->getParent() << DIA->getCond()->getSourceRange();
6349 }
6350
6351 return false;
6352}
6353
6354bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6355 const Expr *ThisArg,
6356 ArrayRef<const Expr *> Args,
6357 SourceLocation Loc) {
6358 return diagnoseDiagnoseIfAttrsWith(
6359 *this, Function, /*ArgDependent=*/true, Loc,
6360 [&](const DiagnoseIfAttr *DIA) {
6361 APValue Result;
6362 // It's sane to use the same Args for any redecl of this function, since
6363 // EvaluateWithSubstitution only cares about the position of each
6364 // argument in the arg list, not the ParmVarDecl* it maps to.
6365 if (!DIA->getCond()->EvaluateWithSubstitution(
6366 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6367 return false;
6368 return Result.isInt() && Result.getInt().getBoolValue();
6369 });
6370}
6371
6372bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6373 SourceLocation Loc) {
6374 return diagnoseDiagnoseIfAttrsWith(
6375 *this, ND, /*ArgDependent=*/false, Loc,
6376 [&](const DiagnoseIfAttr *DIA) {
6377 bool Result;
6378 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6379 Result;
6380 });
6381}
6382
6383/// Add all of the function declarations in the given function set to
6384/// the overload candidate set.
6385void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6386 ArrayRef<Expr *> Args,
6387 OverloadCandidateSet &CandidateSet,
6388 TemplateArgumentListInfo *ExplicitTemplateArgs,
6389 bool SuppressUserConversions,
6390 bool PartialOverloading,
6391 bool FirstArgumentIsBase) {
6392 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6393 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6394 ArrayRef<Expr *> FunctionArgs = Args;
6395
6396 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6397 FunctionDecl *FD =
6398 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6399
6400 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6401 QualType ObjectType;
6402 Expr::Classification ObjectClassification;
6403 if (Args.size() > 0) {
6404 if (Expr *E = Args[0]) {
6405 // Use the explicit base to restrict the lookup:
6406 ObjectType = E->getType();
6407 ObjectClassification = E->Classify(Context);
6408 } // .. else there is an implicit base.
6409 FunctionArgs = Args.slice(1);
6410 }
6411 if (FunTmpl) {
6412 AddMethodTemplateCandidate(
6413 FunTmpl, F.getPair(),
6414 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6415 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6416 FunctionArgs, CandidateSet, SuppressUserConversions,
6417 PartialOverloading);
6418 } else {
6419 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6420 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6421 ObjectClassification, FunctionArgs, CandidateSet,
6422 SuppressUserConversions, PartialOverloading);
6423 }
6424 } else {
6425 // This branch handles both standalone functions and static methods.
6426
6427 // Slice the first argument (which is the base) when we access
6428 // static method as non-static.
6429 if (Args.size() > 0 &&
6430 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6431 !isa<CXXConstructorDecl>(FD)))) {
6432 assert(cast<CXXMethodDecl>(FD)->isStatic())(static_cast <bool> (cast<CXXMethodDecl>(FD)->
isStatic()) ? void (0) : __assert_fail ("cast<CXXMethodDecl>(FD)->isStatic()"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6432, __extension__ __PRETTY_FUNCTION__))
;
6433 FunctionArgs = Args.slice(1);
6434 }
6435 if (FunTmpl) {
6436 AddTemplateOverloadCandidate(
6437 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6438 CandidateSet, SuppressUserConversions, PartialOverloading);
6439 } else {
6440 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6441 SuppressUserConversions, PartialOverloading);
6442 }
6443 }
6444 }
6445}
6446
6447/// AddMethodCandidate - Adds a named decl (which is some kind of
6448/// method) as a method candidate to the given overload set.
6449void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6450 QualType ObjectType,
6451 Expr::Classification ObjectClassification,
6452 ArrayRef<Expr *> Args,
6453 OverloadCandidateSet& CandidateSet,
6454 bool SuppressUserConversions) {
6455 NamedDecl *Decl = FoundDecl.getDecl();
6456 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6457
6458 if (isa<UsingShadowDecl>(Decl))
6459 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6460
6461 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6462 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl
()) && "Expected a member function template") ? void (
0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6463, __extension__ __PRETTY_FUNCTION__))
6463 "Expected a member function template")(static_cast <bool> (isa<CXXMethodDecl>(TD->getTemplatedDecl
()) && "Expected a member function template") ? void (
0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6463, __extension__ __PRETTY_FUNCTION__))
;
6464 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6465 /*ExplicitArgs*/ nullptr, ObjectType,
6466 ObjectClassification, Args, CandidateSet,
6467 SuppressUserConversions);
6468 } else {
6469 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6470 ObjectType, ObjectClassification, Args, CandidateSet,
6471 SuppressUserConversions);
6472 }
6473}
6474
6475/// AddMethodCandidate - Adds the given C++ member function to the set
6476/// of candidate functions, using the given function call arguments
6477/// and the object argument (@c Object). For example, in a call
6478/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6479/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6480/// allow user-defined conversions via constructors or conversion
6481/// operators.
6482void
6483Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6484 CXXRecordDecl *ActingContext, QualType ObjectType,
6485 Expr::Classification ObjectClassification,
6486 ArrayRef<Expr *> Args,
6487 OverloadCandidateSet &CandidateSet,
6488 bool SuppressUserConversions,
6489 bool PartialOverloading,
6490 ConversionSequenceList EarlyConversions) {
6491 const FunctionProtoType *Proto
6492 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6493 assert(Proto && "Methods without a prototype cannot be overloaded")(static_cast <bool> (Proto && "Methods without a prototype cannot be overloaded"
) ? void (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6493, __extension__ __PRETTY_FUNCTION__))
;
6494 assert(!isa<CXXConstructorDecl>(Method) &&(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Use AddOverloadCandidate for constructors") ? void
(0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6495, __extension__ __PRETTY_FUNCTION__))
6495 "Use AddOverloadCandidate for constructors")(static_cast <bool> (!isa<CXXConstructorDecl>(Method
) && "Use AddOverloadCandidate for constructors") ? void
(0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6495, __extension__ __PRETTY_FUNCTION__))
;
6496
6497 if (!CandidateSet.isNewCandidate(Method))
6498 return;
6499
6500 // C++11 [class.copy]p23: [DR1402]
6501 // A defaulted move assignment operator that is defined as deleted is
6502 // ignored by overload resolution.
6503 if (Method->isDefaulted() && Method->isDeleted() &&
6504 Method->isMoveAssignmentOperator())
6505 return;
6506
6507 // Overload resolution is always an unevaluated context.
6508 EnterExpressionEvaluationContext Unevaluated(
6509 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6510
6511 // Add this candidate
6512 OverloadCandidate &Candidate =
6513 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6514 Candidate.FoundDecl = FoundDecl;
6515 Candidate.Function = Method;
6516 Candidate.IsSurrogate = false;
6517 Candidate.IgnoreObjectArgument = false;
6518 Candidate.ExplicitCallArguments = Args.size();
6519
6520 unsigned NumParams = Proto->getNumParams();
6521
6522 // (C++ 13.3.2p2): A candidate function having fewer than m
6523 // parameters is viable only if it has an ellipsis in its parameter
6524 // list (8.3.5).
6525 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6526 !Proto->isVariadic()) {
6527 Candidate.Viable = false;
6528 Candidate.FailureKind = ovl_fail_too_many_arguments;
6529 return;
6530 }
6531
6532 // (C++ 13.3.2p2): A candidate function having more than m parameters
6533 // is viable only if the (m+1)st parameter has a default argument
6534 // (8.3.6). For the purposes of overload resolution, the
6535 // parameter list is truncated on the right, so that there are
6536 // exactly m parameters.
6537 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6538 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6539 // Not enough arguments.
6540 Candidate.Viable = false;
6541 Candidate.FailureKind = ovl_fail_too_few_arguments;
6542 return;
6543 }
6544
6545 Candidate.Viable = true;
6546
6547 if (Method->isStatic() || ObjectType.isNull())
6548 // The implicit object argument is ignored.
6549 Candidate.IgnoreObjectArgument = true;
6550 else {
6551 // Determine the implicit conversion sequence for the object
6552 // parameter.
6553 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6554 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6555 Method, ActingContext);
6556 if (Candidate.Conversions[0].isBad()) {
6557 Candidate.Viable = false;
6558 Candidate.FailureKind = ovl_fail_bad_conversion;
6559 return;
6560 }
6561 }
6562
6563 // (CUDA B.1): Check for invalid calls between targets.
6564 if (getLangOpts().CUDA)
6565 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6566 if (!IsAllowedCUDACall(Caller, Method)) {
6567 Candidate.Viable = false;
6568 Candidate.FailureKind = ovl_fail_bad_target;
6569 return;
6570 }
6571
6572 // Determine the implicit conversion sequences for each of the
6573 // arguments.
6574 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6575 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6576 // We already formed a conversion sequence for this parameter during
6577 // template argument deduction.
6578 } else if (ArgIdx < NumParams) {
6579 // (C++ 13.3.2p3): for F to be a viable function, there shall
6580 // exist for each argument an implicit conversion sequence
6581 // (13.3.3.1) that converts that argument to the corresponding
6582 // parameter of F.
6583 QualType ParamType = Proto->getParamType(ArgIdx);
6584 Candidate.Conversions[ArgIdx + 1]
6585 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6586 SuppressUserConversions,
6587 /*InOverloadResolution=*/true,
6588 /*AllowObjCWritebackConversion=*/
6589 getLangOpts().ObjCAutoRefCount);
6590 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6591 Candidate.Viable = false;
6592 Candidate.FailureKind = ovl_fail_bad_conversion;
6593 return;
6594 }
6595 } else {
6596 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6597 // argument for which there is no corresponding parameter is
6598 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6599 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6600 }
6601 }
6602
6603 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6604 Candidate.Viable = false;
6605 Candidate.FailureKind = ovl_fail_enable_if;
6606 Candidate.DeductionFailure.Data = FailedAttr;
6607 return;
6608 }
6609
6610 if (Method->isMultiVersion() &&
6611 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6612 Candidate.Viable = false;
6613 Candidate.FailureKind = ovl_non_default_multiversion_function;
6614 }
6615}
6616
6617/// Add a C++ member function template as a candidate to the candidate
6618/// set, using template argument deduction to produce an appropriate member
6619/// function template specialization.
6620void
6621Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6622 DeclAccessPair FoundDecl,
6623 CXXRecordDecl *ActingContext,
6624 TemplateArgumentListInfo *ExplicitTemplateArgs,
6625 QualType ObjectType,
6626 Expr::Classification ObjectClassification,
6627 ArrayRef<Expr *> Args,
6628 OverloadCandidateSet& CandidateSet,
6629 bool SuppressUserConversions,
6630 bool PartialOverloading) {
6631 if (!CandidateSet.isNewCandidate(MethodTmpl))
6632 return;
6633
6634 // C++ [over.match.funcs]p7:
6635 // In each case where a candidate is a function template, candidate
6636 // function template specializations are generated using template argument
6637 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6638 // candidate functions in the usual way.113) A given name can refer to one
6639 // or more function templates and also to a set of overloaded non-template
6640 // functions. In such a case, the candidate functions generated from each
6641 // function template are combined with the set of non-template candidate
6642 // functions.
6643 TemplateDeductionInfo Info(CandidateSet.getLocation());
6644 FunctionDecl *Specialization = nullptr;
6645 ConversionSequenceList Conversions;
6646 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6647 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6648 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6649 return CheckNonDependentConversions(
6650 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6651 SuppressUserConversions, ActingContext, ObjectType,
6652 ObjectClassification);
6653 })) {
6654 OverloadCandidate &Candidate =
6655 CandidateSet.addCandidate(Conversions.size(), Conversions);
6656 Candidate.FoundDecl = FoundDecl;
6657 Candidate.Function = MethodTmpl->getTemplatedDecl();
6658 Candidate.Viable = false;
6659 Candidate.IsSurrogate = false;
6660 Candidate.IgnoreObjectArgument =
6661 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6662 ObjectType.isNull();
6663 Candidate.ExplicitCallArguments = Args.size();
6664 if (Result == TDK_NonDependentConversionFailure)
6665 Candidate.FailureKind = ovl_fail_bad_conversion;
6666 else {
6667 Candidate.FailureKind = ovl_fail_bad_deduction;
6668 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6669 Info);
6670 }
6671 return;
6672 }
6673
6674 // Add the function template specialization produced by template argument
6675 // deduction as a candidate.
6676 assert(Specialization && "Missing member function template specialization?")(static_cast <bool> (Specialization && "Missing member function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6676, __extension__ __PRETTY_FUNCTION__))
;
6677 assert(isa<CXXMethodDecl>(Specialization) &&(static_cast <bool> (isa<CXXMethodDecl>(Specialization
) && "Specialization is not a member function?") ? void
(0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6678, __extension__ __PRETTY_FUNCTION__))
6678 "Specialization is not a member function?")(static_cast <bool> (isa<CXXMethodDecl>(Specialization
) && "Specialization is not a member function?") ? void
(0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6678, __extension__ __PRETTY_FUNCTION__))
;
6679 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6680 ActingContext, ObjectType, ObjectClassification, Args,
6681 CandidateSet, SuppressUserConversions, PartialOverloading,
6682 Conversions);
6683}
6684
6685/// Add a C++ function template specialization as a candidate
6686/// in the candidate set, using template argument deduction to produce
6687/// an appropriate function template specialization.
6688void
6689Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6690 DeclAccessPair FoundDecl,
6691 TemplateArgumentListInfo *ExplicitTemplateArgs,
6692 ArrayRef<Expr *> Args,
6693 OverloadCandidateSet& CandidateSet,
6694 bool SuppressUserConversions,
6695 bool PartialOverloading) {
6696 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6697 return;
6698
6699 // C++ [over.match.funcs]p7:
6700 // In each case where a candidate is a function template, candidate
6701 // function template specializations are generated using template argument
6702 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6703 // candidate functions in the usual way.113) A given name can refer to one
6704 // or more function templates and also to a set of overloaded non-template
6705 // functions. In such a case, the candidate functions generated from each
6706 // function template are combined with the set of non-template candidate
6707 // functions.
6708 TemplateDeductionInfo Info(CandidateSet.getLocation());
6709 FunctionDecl *Specialization = nullptr;
6710 ConversionSequenceList Conversions;
6711 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6712 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6713 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6714 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6715 Args, CandidateSet, Conversions,
6716 SuppressUserConversions);
6717 })) {
6718 OverloadCandidate &Candidate =
6719 CandidateSet.addCandidate(Conversions.size(), Conversions);
6720 Candidate.FoundDecl = FoundDecl;
6721 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6722 Candidate.Viable = false;
6723 Candidate.IsSurrogate = false;
6724 // Ignore the object argument if there is one, since we don't have an object
6725 // type.
6726 Candidate.IgnoreObjectArgument =
6727 isa<CXXMethodDecl>(Candidate.Function) &&
6728 !isa<CXXConstructorDecl>(Candidate.Function);
6729 Candidate.ExplicitCallArguments = Args.size();
6730 if (Result == TDK_NonDependentConversionFailure)
6731 Candidate.FailureKind = ovl_fail_bad_conversion;
6732 else {
6733 Candidate.FailureKind = ovl_fail_bad_deduction;
6734 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6735 Info);
6736 }
6737 return;
6738 }
6739
6740 // Add the function template specialization produced by template argument
6741 // deduction as a candidate.
6742 assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6742, __extension__ __PRETTY_FUNCTION__))
;
6743 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6744 SuppressUserConversions, PartialOverloading,
6745 /*AllowExplicit*/false, Conversions);
6746}
6747
6748/// Check that implicit conversion sequences can be formed for each argument
6749/// whose corresponding parameter has a non-dependent type, per DR1391's
6750/// [temp.deduct.call]p10.
6751bool Sema::CheckNonDependentConversions(
6752 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6753 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6754 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6755 CXXRecordDecl *ActingContext, QualType ObjectType,
6756 Expr::Classification ObjectClassification) {
6757 // FIXME: The cases in which we allow explicit conversions for constructor
6758 // arguments never consider calling a constructor template. It's not clear
6759 // that is correct.
6760 const bool AllowExplicit = false;
6761
6762 auto *FD = FunctionTemplate->getTemplatedDecl();
6763 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6764 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6765 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6766
6767 Conversions =
6768 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6769
6770 // Overload resolution is always an unevaluated context.
6771 EnterExpressionEvaluationContext Unevaluated(
6772 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6773
6774 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6775 // require that, but this check should never result in a hard error, and
6776 // overload resolution is permitted to sidestep instantiations.
6777 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6778 !ObjectType.isNull()) {
6779 Conversions[0] = TryObjectArgumentInitialization(
6780 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6781 Method, ActingContext);
6782 if (Conversions[0].isBad())
6783 return true;
6784 }
6785
6786 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6787 ++I) {
6788 QualType ParamType = ParamTypes[I];
6789 if (!ParamType->isDependentType()) {
6790 Conversions[ThisConversions + I]
6791 = TryCopyInitialization(*this, Args[I], ParamType,
6792 SuppressUserConversions,
6793 /*InOverloadResolution=*/true,
6794 /*AllowObjCWritebackConversion=*/
6795 getLangOpts().ObjCAutoRefCount,
6796 AllowExplicit);
6797 if (Conversions[ThisConversions + I].isBad())
6798 return true;
6799 }
6800 }
6801
6802 return false;
6803}
6804
6805/// Determine whether this is an allowable conversion from the result
6806/// of an explicit conversion operator to the expected type, per C++
6807/// [over.match.conv]p1 and [over.match.ref]p1.
6808///
6809/// \param ConvType The return type of the conversion function.
6810///
6811/// \param ToType The type we are converting to.
6812///
6813/// \param AllowObjCPointerConversion Allow a conversion from one
6814/// Objective-C pointer to another.
6815///
6816/// \returns true if the conversion is allowable, false otherwise.
6817static bool isAllowableExplicitConversion(Sema &S,
6818 QualType ConvType, QualType ToType,
6819 bool AllowObjCPointerConversion) {
6820 QualType ToNonRefType = ToType.getNonReferenceType();
6821
6822 // Easy case: the types are the same.
6823 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6824 return true;
6825
6826 // Allow qualification conversions.
6827 bool ObjCLifetimeConversion;
6828 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6829 ObjCLifetimeConversion))
6830 return true;
6831
6832 // If we're not allowed to consider Objective-C pointer conversions,
6833 // we're done.
6834 if (!AllowObjCPointerConversion)
6835 return false;
6836
6837 // Is this an Objective-C pointer conversion?
6838 bool IncompatibleObjC = false;
6839 QualType ConvertedType;
6840 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6841 IncompatibleObjC);
6842}
6843
6844/// AddConversionCandidate - Add a C++ conversion function as a
6845/// candidate in the candidate set (C++ [over.match.conv],
6846/// C++ [over.match.copy]). From is the expression we're converting from,
6847/// and ToType is the type that we're eventually trying to convert to
6848/// (which may or may not be the same type as the type that the
6849/// conversion function produces).
6850void
6851Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6852 DeclAccessPair FoundDecl,
6853 CXXRecordDecl *ActingContext,
6854 Expr *From, QualType ToType,
6855 OverloadCandidateSet& CandidateSet,
6856 bool AllowObjCConversionOnExplicit,
6857 bool AllowResultConversion) {
6858 assert(!Conversion->getDescribedFunctionTemplate() &&(static_cast <bool> (!Conversion->getDescribedFunctionTemplate
() && "Conversion function templates use AddTemplateConversionCandidate"
) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6859, __extension__ __PRETTY_FUNCTION__))
6859 "Conversion function templates use AddTemplateConversionCandidate")(static_cast <bool> (!Conversion->getDescribedFunctionTemplate
() && "Conversion function templates use AddTemplateConversionCandidate"
) ? void (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 6859, __extension__ __PRETTY_FUNCTION__))
;
6860 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6861 if (!CandidateSet.isNewCandidate(Conversion))
6862 return;
6863
6864 // If the conversion function has an undeduced return type, trigger its
6865 // deduction now.
6866 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6867 if (DeduceReturnType(Conversion, From->getExprLoc()))
6868 return;
6869 ConvType = Conversion->getConversionType().getNonReferenceType();
6870 }
6871
6872 // If we don't allow any conversion of the result type, ignore conversion
6873 // functions that don't convert to exactly (possibly cv-qualified) T.
6874 if (!AllowResultConversion &&
6875 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6876 return;
6877
6878 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6879 // operator is only a candidate if its return type is the target type or
6880 // can be converted to the target type with a qualification conversion.
6881 if (Conversion->isExplicit() &&
6882 !isAllowableExplicitConversion(*this, ConvType, ToType,
6883 AllowObjCConversionOnExplicit))
6884 return;
6885
6886 // Overload resolution is always an unevaluated context.
6887 EnterExpressionEvaluationContext Unevaluated(
6888 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6889
6890 // Add this candidate
6891 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6892 Candidate.FoundDecl = FoundDecl;
6893 Candidate.Function = Conversion;
6894 Candidate.IsSurrogate = false;
6895 Candidate.IgnoreObjectArgument = false;
6896 Candidate.FinalConversion.setAsIdentityConversion();
6897 Candidate.FinalConversion.setFromType(ConvType);
6898 Candidate.FinalConversion.setAllToTypes(ToType);
6899 Candidate.Viable = true;
6900 Candidate.ExplicitCallArguments = 1;
6901
6902 // C++ [over.match.funcs]p4:
6903 // For conversion functions, the function is considered to be a member of
6904 // the class of the implicit implied object argument for the purpose of
6905 // defining the type of the implicit object parameter.
6906 //
6907 // Determine the implicit conversion sequence for the implicit
6908 // object parameter.
6909 QualType ImplicitParamType = From->getType();
6910 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6911 ImplicitParamType = FromPtrType->getPointeeType();
6912 CXXRecordDecl *ConversionContext
6913 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6914
6915 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6916 *this, CandidateSet.getLocation(), From->getType(),
6917 From->Classify(Context), Conversion, ConversionContext);
6918
6919 if (Candidate.Conversions[0].isBad()) {
6920 Candidate.Viable = false;
6921 Candidate.FailureKind = ovl_fail_bad_conversion;
6922 return;
6923 }
6924
6925 // We won't go through a user-defined type conversion function to convert a
6926 // derived to base as such conversions are given Conversion Rank. They only
6927 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6928 QualType FromCanon
6929 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6930 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6931 if (FromCanon == ToCanon ||
6932 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6933 Candidate.Viable = false;
6934 Candidate.FailureKind = ovl_fail_trivial_conversion;
6935 return;
6936 }
6937
6938 // To determine what the conversion from the result of calling the
6939 // conversion function to the type we're eventually trying to
6940 // convert to (ToType), we need to synthesize a call to the
6941 // conversion function and attempt copy initialization from it. This
6942 // makes sure that we get the right semantics with respect to
6943 // lvalues/rvalues and the type. Fortunately, we can allocate this
6944 // call on the stack and we don't need its arguments to be
6945 // well-formed.
6946 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6947 VK_LValue, From->getLocStart());
6948 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6949 Context.getPointerType(Conversion->getType()),
6950 CK_FunctionToPointerDecay,
6951 &ConversionRef, VK_RValue);
6952
6953 QualType ConversionType = Conversion->getConversionType();
6954 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6955 Candidate.Viable = false;
6956 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6957 return;
6958 }
6959
6960 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6961
6962 // Note that it is safe to allocate CallExpr on the stack here because
6963 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6964 // allocator).
6965 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6966 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6967 From->getLocStart());
6968 ImplicitConversionSequence ICS =
6969 TryCopyInitialization(*this, &Call, ToType,
6970 /*SuppressUserConversions=*/true,
6971 /*InOverloadResolution=*/false,
6972 /*AllowObjCWritebackConversion=*/false);
6973
6974 switch (ICS.getKind()) {
6975 case ImplicitConversionSequence::StandardConversion:
6976 Candidate.FinalConversion = ICS.Standard;
6977
6978 // C++ [over.ics.user]p3:
6979 // If the user-defined conversion is specified by a specialization of a
6980 // conversion function template, the second standard conversion sequence
6981 // shall have exact match rank.
6982 if (Conversion->getPrimaryTemplate() &&
6983 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6984 Candidate.Viable = false;
6985 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6986 return;
6987 }
6988
6989 // C++0x [dcl.init.ref]p5:
6990 // In the second case, if the reference is an rvalue reference and
6991 // the second standard conversion sequence of the user-defined
6992 // conversion sequence includes an lvalue-to-rvalue conversion, the
6993 // program is ill-formed.
6994 if (ToType->isRValueReferenceType() &&
6995 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6996 Candidate.Viable = false;
6997 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6998 return;
6999 }
7000 break;
7001
7002 case ImplicitConversionSequence::BadConversion:
7003 Candidate.Viable = false;
7004 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7005 return;
7006
7007 default:
7008 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 7009)
7009 "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-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 7009)
;
7010 }
7011
7012 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7013 Candidate.Viable = false;
7014 Candidate.FailureKind = ovl_fail_enable_if;
7015 Candidate.DeductionFailure.Data = FailedAttr;
7016 return;
7017 }
7018
7019 if (Conversion->isMultiVersion() &&
7020 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7021 Candidate.Viable = false;
7022 Candidate.FailureKind = ovl_non_default_multiversion_function;
7023 }
7024}
7025
7026/// Adds a conversion function template specialization
7027/// candidate to the overload set, using template argument deduction
7028/// to deduce the template arguments of the conversion function
7029/// template from the type that we are converting to (C++
7030/// [temp.deduct.conv]).
7031void
7032Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7033 DeclAccessPair FoundDecl,
7034 CXXRecordDecl *ActingDC,
7035 Expr *From, QualType ToType,
7036 OverloadCandidateSet &CandidateSet,
7037 bool AllowObjCConversionOnExplicit,
7038 bool AllowResultConversion) {
7039 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate
->getTemplatedDecl()) && "Only conversion function templates permitted here"
) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 7040, __extension__ __PRETTY_FUNCTION__))
7040 "Only conversion function templates permitted here")(static_cast <bool> (isa<CXXConversionDecl>(FunctionTemplate
->getTemplatedDecl()) && "Only conversion function templates permitted here"
) ? void (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 7040, __extension__ __PRETTY_FUNCTION__))
;
7041
7042 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7043 return;
7044
7045 TemplateDeductionInfo Info(CandidateSet.getLocation());
7046 CXXConversionDecl *Specialization = nullptr;
7047 if (TemplateDeductionResult Result
7048 = DeduceTemplateArguments(FunctionTemplate, ToType,
7049 Specialization, Info)) {
7050 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7051 Candidate.FoundDecl = FoundDecl;
7052 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7053 Candidate.Viable = false;
7054 Candidate.FailureKind = ovl_fail_bad_deduction;
7055 Candidate.IsSurrogate = false;
7056 Candidate.IgnoreObjectArgument = false;
7057 Candidate.ExplicitCallArguments = 1;
7058 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7059 Info);
7060 return;
7061 }
7062
7063 // Add the conversion function template specialization produced by
7064 // template argument deduction as a candidate.
7065 assert(Specialization && "Missing function template specialization?")(static_cast <bool> (Specialization && "Missing function template specialization?"
) ? void (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 7065, __extension__ __PRETTY_FUNCTION__))
;
7066 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7067 CandidateSet, AllowObjCConversionOnExplicit,
7068 AllowResultConversion);
7069}
7070
7071/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7072/// converts the given @c Object to a function pointer via the
7073/// conversion function @c Conversion, and then attempts to call it
7074/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7075/// the type of function that we'll eventually be calling.
7076void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7077 DeclAccessPair FoundDecl,
7078 CXXRecordDecl *ActingContext,
7079 const FunctionProtoType *Proto,
7080 Expr *Object,
7081 ArrayRef<Expr *> Args,
7082 OverloadCandidateSet& CandidateSet) {
7083 if (!CandidateSet.isNewCandidate(Conversion))
7084 return;
7085
7086 // Overload resolution is always an unevaluated context.
7087 EnterExpressionEvaluationContext Unevaluated(
7088 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7089
7090 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7091 Candidate.FoundDecl = FoundDecl;
7092 Candidate.Function = nullptr;
7093 Candidate.Surrogate = Conversion;
7094 Candidate.Viable = true;
7095 Candidate.IsSurrogate = true;
7096 Candidate.IgnoreObjectArgument = false;
7097 Candidate.ExplicitCallArguments = Args.size();
7098
7099 // Determine the implicit conversion sequence for the implicit
7100 // object parameter.
7101 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7102 *this, CandidateSet.getLocation(), Object->getType(),
7103 Object->Classify(Context), Conversion, ActingContext);
7104 if (ObjectInit.isBad()) {
7105 Candidate.Viable = false;
7106 Candidate.FailureKind = ovl_fail_bad_conversion;
7107 Candidate.Conversions[0] = ObjectInit;
7108 return;
7109 }
7110
7111 // The first conversion is actually a user-defined conversion whose
7112 // first conversion is ObjectInit's standard conversion (which is
7113 // effectively a reference binding). Record it as such.
7114 Candidate.Conversions[0].setUserDefined();
7115 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7116 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7117 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7118 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7119 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7120 Candidate.Conversions[0].UserDefined.After
7121 = Candidate.Conversions[0].UserDefined.Before;
7122 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7123
7124 // Find the
7125 unsigned NumParams = Proto->getNumParams();
7126
7127 // (C++ 13.3.2p2): A candidate function having fewer than m
7128 // parameters is viable only if it has an ellipsis in its parameter
7129 // list (8.3.5).
7130 if (Args.size() > NumParams && !Proto->isVariadic()) {
7131 Candidate.Viable = false;
7132 Candidate.FailureKind = ovl_fail_too_many_arguments;
7133 return;
7134 }
7135
7136 // Function types don't have any default arguments, so just check if
7137 // we have enough arguments.
7138 if (Args.size() < NumParams) {
7139 // Not enough arguments.
7140 Candidate.Viable = false;
7141 Candidate.FailureKind = ovl_fail_too_few_arguments;
7142 return;
7143 }
7144
7145 // Determine the implicit conversion sequences for each of the
7146 // arguments.
7147 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7148 if (ArgIdx < NumParams) {
7149 // (C++ 13.3.2p3): for F to be a viable function, there shall
7150 // exist for each argument an implicit conversion sequence
7151 // (13.3.3.1) that converts that argument to the corresponding
7152 // parameter of F.
7153 QualType ParamType = Proto->getParamType(ArgIdx);
7154 Candidate.Conversions[ArgIdx + 1]
7155 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7156 /*SuppressUserConversions=*/false,
7157 /*InOverloadResolution=*/false,
7158 /*AllowObjCWritebackConversion=*/
7159 getLangOpts().ObjCAutoRefCount);
7160 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7161 Candidate.Viable = false;
7162 Candidate.FailureKind = ovl_fail_bad_conversion;
7163 return;
7164 }
7165 } else {
7166 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7167 // argument for which there is no corresponding parameter is
7168 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7169 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7170 }
7171 }
7172
7173 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7174 Candidate.Viable = false;
7175 Candidate.FailureKind = ovl_fail_enable_if;
7176 Candidate.DeductionFailure.Data = FailedAttr;
7177 return;
7178 }
7179}
7180
7181/// Add overload candidates for overloaded operators that are
7182/// member functions.
7183///
7184/// Add the overloaded operator candidates that are member functions
7185/// for the operator Op that was used in an operator expression such
7186/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7187/// CandidateSet will store the added overload candidates. (C++
7188/// [over.match.oper]).
7189void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7190 SourceLocation OpLoc,
7191 ArrayRef<Expr *> Args,
7192 OverloadCandidateSet& CandidateSet,
7193 SourceRange OpRange) {
7194 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7195
7196 // C++ [over.match.oper]p3:
7197 // For a unary operator @ with an operand of a type whose
7198 // cv-unqualified version is T1, and for a binary operator @ with
7199 // a left operand of a type whose cv-unqualified version is T1 and
7200 // a right operand of a type whose cv-unqualified version is T2,
7201 // three sets of candidate functions, designated member
7202 // candidates, non-member candidates and built-in candidates, are
7203 // constructed as follows:
7204 QualType T1 = Args[0]->getType();
7205
7206 // -- If T1 is a complete class type or a class currently being
7207 // defined, the set of member candidates is the result of the
7208 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7209 // the set of member candidates is empty.
7210 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7211 // Complete the type if it can be completed.
7212 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7213 return;
7214 // If the type is neither complete nor being defined, bail out now.
7215 if (!T1Rec->getDecl()->getDefinition())
7216 return;
7217
7218 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7219 LookupQualifiedName(Operators, T1Rec->getDecl());
7220 Operators.suppressDiagnostics();
7221
7222 for (LookupResult::iterator Oper = Operators.begin(),
7223 OperEnd = Operators.end();
7224 Oper != OperEnd;
7225 ++Oper)
7226 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7227 Args[0]->Classify(Context), Args.slice(1),
7228 CandidateSet, /*SuppressUserConversions=*/false);
7229 }
7230}
7231
7232/// AddBuiltinCandidate - Add a candidate for a built-in
7233/// operator. ResultTy and ParamTys are the result and parameter types
7234/// of the built-in candidate, respectively. Args and NumArgs are the
7235/// arguments being passed to the candidate. IsAssignmentOperator
7236/// should be true when this built-in candidate is an assignment
7237/// operator. NumContextualBoolArguments is the number of arguments
7238/// (at the beginning of the argument list) that will be contextually
7239/// converted to bool.
7240void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7241 OverloadCandidateSet& CandidateSet,
7242 bool IsAssignmentOperator,
7243 unsigned NumContextualBoolArguments) {
7244 // Overload resolution is always an unevaluated context.
7245 EnterExpressionEvaluationContext Unevaluated(
7246 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7247
7248 // Add this candidate
7249 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7250 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7251 Candidate.Function = nullptr;
7252 Candidate.IsSurrogate = false;
7253 Candidate.IgnoreObjectArgument = false;
7254 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7255
7256 // Determine the implicit conversion sequences for each of the
7257 // arguments.
7258 Candidate.Viable = true;
7259 Candidate.ExplicitCallArguments = Args.size();
7260 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7261 // C++ [over.match.oper]p4:
7262 // For the built-in assignment operators, conversions of the
7263 // left operand are restricted as follows:
7264 // -- no temporaries are introduced to hold the left operand, and
7265 // -- no user-defined conversions are applied to the left
7266 // operand to achieve a type match with the left-most
7267 // parameter of a built-in candidate.
7268 //
7269 // We block these conversions by turning off user-defined
7270 // conversions, since that is the only way that initialization of
7271 // a reference to a non-class type can occur from something that
7272 // is not of the same type.
7273 if (ArgIdx < NumContextualBoolArguments) {
7274 assert(ParamTys[ArgIdx] == Context.BoolTy &&(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy
&& "Contextual conversion to bool requires bool type"
) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 7275, __extension__ __PRETTY_FUNCTION__))
7275 "Contextual conversion to bool requires bool type")(static_cast <bool> (ParamTys[ArgIdx] == Context.BoolTy
&& "Contextual conversion to bool requires bool type"
) ? void (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 7275, __extension__ __PRETTY_FUNCTION__))
;
7276 Candidate.Conversions[ArgIdx]
7277 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7278 } else {
7279 Candidate.Conversions[ArgIdx]
7280 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7281 ArgIdx == 0 && IsAssignmentOperator,
7282 /*InOverloadResolution=*/false,
7283 /*AllowObjCWritebackConversion=*/
7284 getLangOpts().ObjCAutoRefCount);
7285 }
7286 if (Candidate.Conversions[ArgIdx].isBad()) {
7287 Candidate.Viable = false;
7288 Candidate.FailureKind = ovl_fail_bad_conversion;
7289 break;
7290 }
7291 }
7292}
7293
7294namespace {
7295
7296/// BuiltinCandidateTypeSet - A set of types that will be used for the
7297/// candidate operator functions for built-in operators (C++
7298/// [over.built]). The types are separated into pointer types and
7299/// enumeration types.
7300class BuiltinCandidateTypeSet {
7301 /// TypeSet - A set of types.
7302 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7303 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7304
7305 /// PointerTypes - The set of pointer types that will be used in the
7306 /// built-in candidates.
7307 TypeSet PointerTypes;
7308
7309 /// MemberPointerTypes - The set of member pointer types that will be
7310 /// used in the built-in candidates.
7311 TypeSet MemberPointerTypes;
7312
7313 /// EnumerationTypes - The set of enumeration types that will be
7314 /// used in the built-in candidates.
7315 TypeSet EnumerationTypes;
7316
7317 /// The set of vector types that will be used in the built-in
7318 /// candidates.
7319 TypeSet VectorTypes;
7320
7321 /// A flag indicating non-record types are viable candidates
7322 bool HasNonRecordTypes;
7323
7324 /// A flag indicating whether either arithmetic or enumeration types
7325 /// were present in the candidate set.
7326 bool HasArithmeticOrEnumeralTypes;
7327
7328 /// A flag indicating whether the nullptr type was present in the
7329 /// candidate set.
7330 bool HasNullPtrType;
7331
7332 /// Sema - The semantic analysis instance where we are building the
7333 /// candidate type set.
7334 Sema &SemaRef;
7335
7336 /// Context - The AST context in which we will build the type sets.
7337 ASTContext &Context;
7338
7339 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7340 const Qualifiers &VisibleQuals);
7341 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7342
7343public:
7344 /// iterator - Iterates through the types that are part of the set.
7345 typedef TypeSet::iterator iterator;
7346
7347 BuiltinCandidateTypeSet(Sema &SemaRef)
7348 : HasNonRecordTypes(false),
7349 HasArithmeticOrEnumeralTypes(false),
7350 HasNullPtrType(false),
7351 SemaRef(SemaRef),
7352 Context(SemaRef.Context) { }
7353
7354 void AddTypesConvertedFrom(QualType Ty,
7355 SourceLocation Loc,
7356 bool AllowUserConversions,
7357 bool AllowExplicitConversions,
7358 const Qualifiers &VisibleTypeConversionsQuals);
7359
7360 /// pointer_begin - First pointer type found;
7361 iterator pointer_begin() { return PointerTypes.begin(); }
7362
7363 /// pointer_end - Past the last pointer type found;
7364 iterator pointer_end() { return PointerTypes.end(); }
7365
7366 /// member_pointer_begin - First member pointer type found;
7367 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7368
7369 /// member_pointer_end - Past the last member pointer type found;
7370 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7371
7372 /// enumeration_begin - First enumeration type found;
7373 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7374
7375 /// enumeration_end - Past the last enumeration type found;
7376 iterator enumeration_end() { return EnumerationTypes.end(); }
7377
7378 iterator vector_begin() { return VectorTypes.begin(); }
7379 iterator vector_end() { return VectorTypes.end(); }
7380
7381 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7382 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7383 bool hasNullPtrType() const { return HasNullPtrType; }
7384};
7385
7386} // end anonymous namespace
7387
7388/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7389/// the set of pointer types along with any more-qualified variants of
7390/// that type. For example, if @p Ty is "int const *", this routine
7391/// will add "int const *", "int const volatile *", "int const
7392/// restrict *", and "int const volatile restrict *" to the set of
7393/// pointer types. Returns true if the add of @p Ty itself succeeded,
7394/// false otherwise.
7395///
7396/// FIXME: what to do about extended qualifiers?
7397bool
7398BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7399 const Qualifiers &VisibleQuals) {
7400
7401 // Insert this type.
7402 if (!PointerTypes.insert(Ty))
7403 return false;
7404
7405 QualType PointeeTy;
7406 const PointerType *PointerTy = Ty->getAs<PointerType>();
7407 bool buildObjCPtr = false;
7408 if (!PointerTy) {
7409 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7410 PointeeTy = PTy->getPointeeType();
7411 buildObjCPtr = true;
7412 } else {
7413 PointeeTy = PointerTy->getPointeeType();
7414 }
7415
7416 // Don't add qualified variants of arrays. For one, they're not allowed
7417 // (the qualifier would sink to the element type), and for another, the
7418 // only overload situation where it matters is subscript or pointer +- int,
7419 // and those shouldn't have qualifier variants anyway.
7420 if (PointeeTy->isArrayType())
7421 return true;
7422
7423 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7424 bool hasVolatile = VisibleQuals.hasVolatile();
7425 bool hasRestrict = VisibleQuals.hasRestrict();
7426
7427 // Iterate through all strict supersets of BaseCVR.
7428 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7429 if ((CVR | BaseCVR) != CVR) continue;
7430 // Skip over volatile if no volatile found anywhere in the types.
7431 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7432
7433 // Skip over restrict if no restrict found anywhere in the types, or if
7434 // the type cannot be restrict-qualified.
7435 if ((CVR & Qualifiers::Restrict) &&
7436 (!hasRestrict ||
7437 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7438 continue;
7439
7440 // Build qualified pointee type.
7441 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7442
7443 // Build qualified pointer type.
7444 QualType QPointerTy;
7445 if (!buildObjCPtr)
7446 QPointerTy = Context.getPointerType(QPointeeTy);
7447 else
7448 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7449
7450 // Insert qualified pointer type.
7451 PointerTypes.insert(QPointerTy);
7452 }
7453
7454 return true;
7455}
7456
7457/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7458/// to the set of pointer types along with any more-qualified variants of
7459/// that type. For example, if @p Ty is "int const *", this routine
7460/// will add "int const *", "int const volatile *", "int const
7461/// restrict *", and "int const volatile restrict *" to the set of
7462/// pointer types. Returns true if the add of @p Ty itself succeeded,
7463/// false otherwise.
7464///
7465/// FIXME: what to do about extended qualifiers?
7466bool
7467BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7468 QualType Ty) {
7469 // Insert this type.
7470 if (!MemberPointerTypes.insert(Ty))
7471 return false;
7472
7473 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7474 assert(PointerTy && "type was not a member pointer type!")(static_cast <bool> (PointerTy && "type was not a member pointer type!"
) ? void (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 7474, __extension__ __PRETTY_FUNCTION__))
;
7475
7476 QualType PointeeTy = PointerTy->getPointeeType();
7477 // Don't add qualified variants of arrays. For one, they're not allowed
7478 // (the qualifier would sink to the element type), and for another, the
7479 // only overload situation where it matters is subscript or pointer +- int,
7480 // and those shouldn't have qualifier variants anyway.
7481 if (PointeeTy->isArrayType())
7482 return true;
7483 const Type *ClassTy = PointerTy->getClass();
7484
7485 // Iterate through all strict supersets of the pointee type's CVR
7486 // qualifiers.
7487 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7488 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7489 if ((CVR | BaseCVR) != CVR) continue;
7490
7491 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7492 MemberPointerTypes.insert(
7493 Context.getMemberPointerType(QPointeeTy, ClassTy));
7494 }
7495
7496 return true;
7497}
7498
7499/// AddTypesConvertedFrom - Add each of the types to which the type @p
7500/// Ty can be implicit converted to the given set of @p Types. We're
7501/// primarily interested in pointer types and enumeration types. We also
7502/// take member pointer types, for the conditional operator.
7503/// AllowUserConversions is true if we should look at the conversion
7504/// functions of a class type, and AllowExplicitConversions if we
7505/// should also include the explicit conversion functions of a class
7506/// type.
7507void
7508BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7509 SourceLocation Loc,
7510 bool AllowUserConversions,
7511 bool AllowExplicitConversions,
7512 const Qualifiers &VisibleQuals) {
7513 // Only deal with canonical types.
7514 Ty = Context.getCanonicalType(Ty);
7515
7516 // Look through reference types; they aren't part of the type of an
7517 // expression for the purposes of conversions.
7518 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7519 Ty = RefTy->getPointeeType();
7520
7521 // If we're dealing with an array type, decay to the pointer.
7522 if (Ty->isArrayType())
7523 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7524
7525 // Otherwise, we don't care about qualifiers on the type.
7526 Ty = Ty.getLocalUnqualifiedType();
7527
7528 // Flag if we ever add a non-record type.
7529 const RecordType *TyRec = Ty->getAs<RecordType>();
7530 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7531
7532 // Flag if we encounter an arithmetic type.
7533 HasArithmeticOrEnumeralTypes =
7534 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7535
7536 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7537 PointerTypes.insert(Ty);
7538 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7539 // Insert our type, and its more-qualified variants, into the set
7540 // of types.
7541 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7542 return;
7543 } else if (Ty->isMemberPointerType()) {
7544 // Member pointers are far easier, since the pointee can't be converted.
7545 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7546 return;
7547 } else if (Ty->isEnumeralType()) {
7548 HasArithmeticOrEnumeralTypes = true;
7549 EnumerationTypes.insert(Ty);
7550 } else if (Ty->isVectorType()) {
7551 // We treat vector types as arithmetic types in many contexts as an
7552 // extension.
7553 HasArithmeticOrEnumeralTypes = true;
7554 VectorTypes.insert(Ty);
7555 } else if (Ty->isNullPtrType()) {
7556 HasNullPtrType = true;
7557 } else if (AllowUserConversions && TyRec) {
7558 // No conversion functions in incomplete types.
7559 if (!SemaRef.isCompleteType(Loc, Ty))
7560 return;
7561
7562 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7563 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7564 if (isa<UsingShadowDecl>(D))
7565 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7566
7567 // Skip conversion function templates; they don't tell us anything
7568 // about which builtin types we can convert to.
7569 if (isa<FunctionTemplateDecl>(D))
7570 continue;
7571
7572 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7573 if (AllowExplicitConversions || !Conv->isExplicit()) {
7574 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7575 VisibleQuals);
7576 }
7577 }
7578 }
7579}
7580
7581/// Helper function for AddBuiltinOperatorCandidates() that adds
7582/// the volatile- and non-volatile-qualified assignment operators for the
7583/// given type to the candidate set.
7584static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7585 QualType T,
7586 ArrayRef<Expr *> Args,
7587 OverloadCandidateSet &CandidateSet) {
7588 QualType ParamTypes[2];
7589
7590 // T& operator=(T&, T)
7591 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7592 ParamTypes[1] = T;
7593 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7594 /*IsAssignmentOperator=*/true);
7595
7596 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7597 // volatile T& operator=(volatile T&, T)
7598 ParamTypes[0]
7599 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7600 ParamTypes[1] = T;
7601 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7602 /*IsAssignmentOperator=*/true);
7603 }
7604}
7605
7606/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7607/// if any, found in visible type conversion functions found in ArgExpr's type.
7608static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7609 Qualifiers VRQuals;
7610 const RecordType *TyRec;
7611 if (const MemberPointerType *RHSMPType =
7612 ArgExpr->getType()->getAs<MemberPointerType>())
7613 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7614 else
7615 TyRec = ArgExpr->getType()->getAs<RecordType>();
7616 if (!TyRec) {
7617 // Just to be safe, assume the worst case.
7618 VRQuals.addVolatile();
7619 VRQuals.addRestrict();
7620 return VRQuals;
7621 }
7622
7623 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7624 if (!ClassDecl->hasDefinition())
7625 return VRQuals;
7626
7627 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7628 if (isa<UsingShadowDecl>(D))
7629 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7630 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7631 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7632 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7633 CanTy = ResTypeRef->getPointeeType();
7634 // Need to go down the pointer/mempointer chain and add qualifiers
7635 // as see them.
7636 bool done = false;
7637 while (!done) {
7638 if (CanTy.isRestrictQualified())
7639 VRQuals.addRestrict();
7640 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7641 CanTy = ResTypePtr->getPointeeType();
7642 else if (const MemberPointerType *ResTypeMPtr =
7643 CanTy->getAs<MemberPointerType>())
7644 CanTy = ResTypeMPtr->getPointeeType();
7645 else
7646 done = true;
7647 if (CanTy.isVolatileQualified())
7648 VRQuals.addVolatile();
7649 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7650 return VRQuals;
7651 }
7652 }
7653 }
7654 return VRQuals;
7655}
7656
7657namespace {
7658
7659/// Helper class to manage the addition of builtin operator overload
7660/// candidates. It provides shared state and utility methods used throughout
7661/// the process, as well as a helper method to add each group of builtin
7662/// operator overloads from the standard to a candidate set.
7663class BuiltinOperatorOverloadBuilder {
7664 // Common instance state available to all overload candidate addition methods.
7665 Sema &S;
7666 ArrayRef<Expr *> Args;
7667 Qualifiers VisibleTypeConversionsQuals;
7668 bool HasArithmeticOrEnumeralCandidateType;
7669 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7670 OverloadCandidateSet &CandidateSet;
7671
7672 static constexpr int ArithmeticTypesCap = 24;
7673 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7674
7675 // Define some indices used to iterate over the arithemetic types in
7676 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
7677 // types are that preserved by promotion (C++ [over.built]p2).
7678 unsigned FirstIntegralType,
7679 LastIntegralType;
7680 unsigned FirstPromotedIntegralType,
7681 LastPromotedIntegralType;
7682 unsigned FirstPromotedArithmeticType,
7683 LastPromotedArithmeticType;
7684 unsigned NumArithmeticTypes;
7685
7686 void InitArithmeticTypes() {
7687 // Start of promoted types.
7688 FirstPromotedArithmeticType = 0;
7689 ArithmeticTypes.push_back(S.Context.FloatTy);
7690 ArithmeticTypes.push_back(S.Context.DoubleTy);
7691 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7692 if (S.Context.getTargetInfo().hasFloat128Type())
7693 ArithmeticTypes.push_back(S.Context.Float128Ty);
7694
7695 // Start of integral types.
7696 FirstIntegralType = ArithmeticTypes.size();
7697 FirstPromotedIntegralType = ArithmeticTypes.size();
7698 ArithmeticTypes.push_back(S.Context.IntTy);
7699 ArithmeticTypes.push_back(S.Context.LongTy);
7700 ArithmeticTypes.push_back(S.Context.LongLongTy);
7701 if (S.Context.getTargetInfo().hasInt128Type())
7702 ArithmeticTypes.push_back(S.Context.Int128Ty);
7703 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7704 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7705 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7706 if (S.Context.getTargetInfo().hasInt128Type())
7707 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7708 LastPromotedIntegralType = ArithmeticTypes.size();
7709 LastPromotedArithmeticType = ArithmeticTypes.size();
7710 // End of promoted types.
7711
7712 ArithmeticTypes.push_back(S.Context.BoolTy);
7713 ArithmeticTypes.push_back(S.Context.CharTy);
7714 ArithmeticTypes.push_back(S.Context.WCharTy);
7715 if (S.Context.getLangOpts().Char8)
7716 ArithmeticTypes.push_back(S.Context.Char8Ty);
7717 ArithmeticTypes.push_back(S.Context.Char16Ty);
7718 ArithmeticTypes.push_back(S.Context.Char32Ty);
7719 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7720 ArithmeticTypes.push_back(S.Context.ShortTy);
7721 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7722 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7723 LastIntegralType = ArithmeticTypes.size();
7724 NumArithmeticTypes = ArithmeticTypes.size();
7725 // End of integral types.
7726 // FIXME: What about complex? What about half?
7727
7728 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap
&& "Enough inline storage for all arithmetic types."
) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 7729, __extension__ __PRETTY_FUNCTION__))
7729 "Enough inline storage for all arithmetic types.")(static_cast <bool> (ArithmeticTypes.size() <= ArithmeticTypesCap
&& "Enough inline storage for all arithmetic types."
) ? void (0) : __assert_fail ("ArithmeticTypes.size() <= ArithmeticTypesCap && \"Enough inline storage for all arithmetic types.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 7729, __extension__ __PRETTY_FUNCTION__))
;
7730 }
7731
7732 /// Helper method to factor out the common pattern of adding overloads
7733 /// for '++' and '--' builtin operators.
7734 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7735 bool HasVolatile,
7736 bool HasRestrict) {
7737 QualType ParamTypes[2] = {
7738 S.Context.getLValueReferenceType(CandidateTy),
7739 S.Context.IntTy
7740 };
7741
7742 // Non-volatile version.
7743 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7744
7745 // Use a heuristic to reduce number of builtin candidates in the set:
7746 // add volatile version only if there are conversions to a volatile type.
7747 if (HasVolatile) {
7748 ParamTypes[0] =
7749 S.Context.getLValueReferenceType(
7750 S.Context.getVolatileType(CandidateTy));
7751 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7752 }
7753
7754 // Add restrict version only if there are conversions to a restrict type
7755 // and our candidate type is a non-restrict-qualified pointer.
7756 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7757 !CandidateTy.isRestrictQualified()) {
7758 ParamTypes[0]
7759 = S.Context.getLValueReferenceType(
7760 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7761 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7762
7763 if (HasVolatile) {
7764 ParamTypes[0]
7765 = S.Context.getLValueReferenceType(
7766 S.Context.getCVRQualifiedType(CandidateTy,
7767 (Qualifiers::Volatile |
7768 Qualifiers::Restrict)));
7769 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7770 }
7771 }
7772
7773 }
7774
7775public:
7776 BuiltinOperatorOverloadBuilder(
7777 Sema &S, ArrayRef<Expr *> Args,
7778 Qualifiers VisibleTypeConversionsQuals,
7779 bool HasArithmeticOrEnumeralCandidateType,
7780 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7781 OverloadCandidateSet &CandidateSet)
7782 : S(S), Args(Args),
7783 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7784 HasArithmeticOrEnumeralCandidateType(
7785 HasArithmeticOrEnumeralCandidateType),
7786 CandidateTypes(CandidateTypes),
7787 CandidateSet(CandidateSet) {
7788
7789 InitArithmeticTypes();
7790 }
7791
7792 // Increment is deprecated for bool since C++17.
7793 //
7794 // C++ [over.built]p3:
7795 //
7796 // For every pair (T, VQ), where T is an arithmetic type other
7797 // than bool, and VQ is either volatile or empty, there exist
7798 // candidate operator functions of the form
7799 //
7800 // VQ T& operator++(VQ T&);
7801 // T operator++(VQ T&, int);
7802 //
7803 // C++ [over.built]p4:
7804 //
7805 // For every pair (T, VQ), where T is an arithmetic type other
7806 // than bool, and VQ is either volatile or empty, there exist
7807 // candidate operator functions of the form
7808 //
7809 // VQ T& operator--(VQ T&);
7810 // T operator--(VQ T&, int);
7811 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7812 if (!HasArithmeticOrEnumeralCandidateType)
7813 return;
7814
7815 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7816 const auto TypeOfT = ArithmeticTypes[Arith];
7817 if (TypeOfT == S.Context.BoolTy) {
7818 if (Op == OO_MinusMinus)
7819 continue;
7820 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7821 continue;
7822 }
7823 addPlusPlusMinusMinusStyleOverloads(
7824 TypeOfT,
7825 VisibleTypeConversionsQuals.hasVolatile(),
7826 VisibleTypeConversionsQuals.hasRestrict());
7827 }
7828 }
7829
7830 // C++ [over.built]p5:
7831 //
7832 // For every pair (T, VQ), where T is a cv-qualified or
7833 // cv-unqualified object type, and VQ is either volatile or
7834 // empty, there exist candidate operator functions of the form
7835 //
7836 // T*VQ& operator++(T*VQ&);
7837 // T*VQ& operator--(T*VQ&);
7838 // T* operator++(T*VQ&, int);
7839 // T* operator--(T*VQ&, int);
7840 void addPlusPlusMinusMinusPointerOverloads() {
7841 for (BuiltinCandidateTypeSet::iterator
7842 Ptr = CandidateTypes[0].pointer_begin(),
7843 PtrEnd = CandidateTypes[0].pointer_end();
7844 Ptr != PtrEnd; ++Ptr) {
7845 // Skip pointer types that aren't pointers to object types.
7846 if (!(*Ptr)->getPointeeType()->isObjectType())
7847 continue;
7848
7849 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7850 (!(*Ptr).isVolatileQualified() &&
7851 VisibleTypeConversionsQuals.hasVolatile()),
7852 (!(*Ptr).isRestrictQualified() &&
7853 VisibleTypeConversionsQuals.hasRestrict()));
7854 }
7855 }
7856
7857 // C++ [over.built]p6:
7858 // For every cv-qualified or cv-unqualified object type T, there
7859 // exist candidate operator functions of the form
7860 //
7861 // T& operator*(T*);
7862 //
7863 // C++ [over.built]p7:
7864 // For every function type T that does not have cv-qualifiers or a
7865 // ref-qualifier, there exist candidate operator functions of the form
7866 // T& operator*(T*);
7867 void addUnaryStarPointerOverloads() {
7868 for (BuiltinCandidateTypeSet::iterator
7869 Ptr = CandidateTypes[0].pointer_begin(),
7870 PtrEnd = CandidateTypes[0].pointer_end();
7871 Ptr != PtrEnd; ++Ptr) {
7872 QualType ParamTy = *Ptr;
7873 QualType PointeeTy = ParamTy->getPointeeType();
7874 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7875 continue;
7876
7877 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7878 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7879 continue;
7880
7881 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7882 }
7883 }
7884
7885 // C++ [over.built]p9:
7886 // For every promoted arithmetic type T, there exist candidate
7887 // operator functions of the form
7888 //
7889 // T operator+(T);
7890 // T operator-(T);
7891 void addUnaryPlusOrMinusArithmeticOverloads() {
7892 if (!HasArithmeticOrEnumeralCandidateType)
7893 return;
7894
7895 for (unsigned Arith = FirstPromotedArithmeticType;
7896 Arith < LastPromotedArithmeticType; ++Arith) {
7897 QualType ArithTy = ArithmeticTypes[Arith];
7898 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7899 }
7900
7901 // Extension: We also add these operators for vector types.
7902 for (BuiltinCandidateTypeSet::iterator
7903 Vec = CandidateTypes[0].vector_begin(),
7904 VecEnd = CandidateTypes[0].vector_end();
7905 Vec != VecEnd; ++Vec) {
7906 QualType VecTy = *Vec;
7907 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7908 }
7909 }
7910
7911 // C++ [over.built]p8:
7912 // For every type T, there exist candidate operator functions of
7913 // the form
7914 //
7915 // T* operator+(T*);
7916 void addUnaryPlusPointerOverloads() {
7917 for (BuiltinCandidateTypeSet::iterator
7918 Ptr = CandidateTypes[0].pointer_begin(),
7919 PtrEnd = CandidateTypes[0].pointer_end();
7920 Ptr != PtrEnd; ++Ptr) {
7921 QualType ParamTy = *Ptr;
7922 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7923 }
7924 }
7925
7926 // C++ [over.built]p10:
7927 // For every promoted integral type T, there exist candidate
7928 // operator functions of the form
7929 //
7930 // T operator~(T);
7931 void addUnaryTildePromotedIntegralOverloads() {
7932 if (!HasArithmeticOrEnumeralCandidateType)
7933 return;
7934
7935 for (unsigned Int = FirstPromotedIntegralType;
7936 Int < LastPromotedIntegralType; ++Int) {
7937 QualType IntTy = ArithmeticTypes[Int];
7938 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7939 }
7940
7941 // Extension: We also add this operator for vector types.
7942 for (BuiltinCandidateTypeSet::iterator
7943 Vec = CandidateTypes[0].vector_begin(),
7944 VecEnd = CandidateTypes[0].vector_end();
7945 Vec != VecEnd; ++Vec) {
7946 QualType VecTy = *Vec;
7947 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7948 }
7949 }
7950
7951 // C++ [over.match.oper]p16:
7952 // For every pointer to member type T or type std::nullptr_t, there
7953 // exist candidate operator functions of the form
7954 //
7955 // bool operator==(T,T);
7956 // bool operator!=(T,T);
7957 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7958 /// Set of (canonical) types that we've already handled.
7959 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7960
7961 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7962 for (BuiltinCandidateTypeSet::iterator
7963 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7964 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7965 MemPtr != MemPtrEnd;
7966 ++MemPtr) {
7967 // Don't add the same builtin candidate twice.
7968 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7969 continue;
7970
7971 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7972 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7973 }
7974
7975 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7976 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7977 if (AddedTypes.insert(NullPtrTy).second) {
7978 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7979 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7980 }
7981 }
7982 }
7983 }
7984
7985 // C++ [over.built]p15:
7986 //
7987 // For every T, where T is an enumeration type or a pointer type,
7988 // there exist candidate operator functions of the form
7989 //
7990 // bool operator<(T, T);
7991 // bool operator>(T, T);
7992 // bool operator<=(T, T);
7993 // bool operator>=(T, T);
7994 // bool operator==(T, T);
7995 // bool operator!=(T, T);
7996 // R operator<=>(T, T)
7997 void addGenericBinaryPointerOrEnumeralOverloads() {
7998 // C++ [over.match.oper]p3:
7999 // [...]the built-in candidates include all of the candidate operator
8000 // functions defined in 13.6 that, compared to the given operator, [...]
8001 // do not have the same parameter-type-list as any non-template non-member
8002 // candidate.
8003 //
8004 // Note that in practice, this only affects enumeration types because there
8005 // aren't any built-in candidates of record type, and a user-defined operator
8006 // must have an operand of record or enumeration type. Also, the only other
8007 // overloaded operator with enumeration arguments, operator=,
8008 // cannot be overloaded for enumeration types, so this is the only place
8009 // where we must suppress candidates like this.
8010 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8011 UserDefinedBinaryOperators;
8012
8013 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8014 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8015 CandidateTypes[ArgIdx].enumeration_end()) {
8016 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8017 CEnd = CandidateSet.end();
8018 C != CEnd; ++C) {
8019 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8020 continue;
8021
8022 if (C->Function->isFunctionTemplateSpecialization())
8023 continue;
8024
8025 QualType FirstParamType =
8026 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8027 QualType SecondParamType =
8028 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8029
8030 // Skip if either parameter isn't of enumeral type.
8031 if (!FirstParamType->isEnumeralType() ||
8032 !SecondParamType->isEnumeralType())
8033 continue;
8034
8035 // Add this operator to the set of known user-defined operators.
8036 UserDefinedBinaryOperators.insert(
8037 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8038 S.Context.getCanonicalType(SecondParamType)));
8039 }
8040 }
8041 }
8042
8043 /// Set of (canonical) types that we've already handled.
8044 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8045
8046 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8047 for (BuiltinCandidateTypeSet::iterator
8048 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8049 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8050 Ptr != PtrEnd; ++Ptr) {
8051 // Don't add the same builtin candidate twice.
8052 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8053 continue;
8054
8055 QualType ParamTypes[2] = { *Ptr, *Ptr };
8056 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8057 }
8058 for (BuiltinCandidateTypeSet::iterator
8059 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8060 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8061 Enum != EnumEnd; ++Enum) {
8062 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8063
8064 // Don't add the same builtin candidate twice, or if a user defined
8065 // candidate exists.
8066 if (!AddedTypes.insert(CanonType).second ||
8067 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8068 CanonType)))
8069 continue;
8070 QualType ParamTypes[2] = { *Enum, *Enum };
8071 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8072 }
8073 }
8074 }
8075
8076 // C++ [over.built]p13:
8077 //
8078 // For every cv-qualified or cv-unqualified object type T
8079 // there exist candidate operator functions of the form
8080 //
8081 // T* operator+(T*, ptrdiff_t);
8082 // T& operator[](T*, ptrdiff_t); [BELOW]
8083 // T* operator-(T*, ptrdiff_t);
8084 // T* operator+(ptrdiff_t, T*);
8085 // T& operator[](ptrdiff_t, T*); [BELOW]
8086 //
8087 // C++ [over.built]p14:
8088 //
8089 // For every T, where T is a pointer to object type, there
8090 // exist candidate operator functions of the form
8091 //
8092 // ptrdiff_t operator-(T, T);
8093 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8094 /// Set of (canonical) types that we've already handled.
8095 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8096
8097 for (int Arg = 0; Arg < 2; ++Arg) {
8098 QualType AsymmetricParamTypes[2] = {
8099 S.Context.getPointerDiffType(),
8100 S.Context.getPointerDiffType(),
8101 };
8102 for (BuiltinCandidateTypeSet::iterator
8103 Ptr = CandidateTypes[Arg].pointer_begin(),
8104 PtrEnd = CandidateTypes[Arg].pointer_end();
8105 Ptr != PtrEnd; ++Ptr) {
8106 QualType PointeeTy = (*Ptr)->getPointeeType();
8107 if (!PointeeTy->isObjectType())
8108 continue;
8109
8110 AsymmetricParamTypes[Arg] = *Ptr;
8111 if (Arg == 0 || Op == OO_Plus) {
8112 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8113 // T* operator+(ptrdiff_t, T*);
8114 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8115 }
8116 if (Op == OO_Minus) {
8117 // ptrdiff_t operator-(T, T);
8118 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8119 continue;
8120
8121 QualType ParamTypes[2] = { *Ptr, *Ptr };
8122 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8123 }
8124 }
8125 }
8126 }
8127
8128 // C++ [over.built]p12:
8129 //
8130 // For every pair of promoted arithmetic types L and R, there
8131 // exist candidate operator functions of the form
8132 //
8133 // LR operator*(L, R);
8134 // LR operator/(L, R);
8135 // LR operator+(L, R);
8136 // LR operator-(L, R);
8137 // bool operator<(L, R);
8138 // bool operator>(L, R);
8139 // bool operator<=(L, R);
8140 // bool operator>=(L, R);
8141 // bool operator==(L, R);
8142 // bool operator!=(L, R);
8143 //
8144 // where LR is the result of the usual arithmetic conversions
8145 // between types L and R.
8146 //
8147 // C++ [over.built]p24:
8148 //
8149 // For every pair of promoted arithmetic types L and R, there exist
8150 // candidate operator functions of the form
8151 //
8152 // LR operator?(bool, L, R);
8153 //
8154 // where LR is the result of the usual arithmetic conversions
8155 // between types L and R.
8156 // Our candidates ignore the first parameter.
8157 void addGenericBinaryArithmeticOverloads() {
8158 if (!HasArithmeticOrEnumeralCandidateType)
8159 return;
8160
8161 for (unsigned Left = FirstPromotedArithmeticType;
8162 Left < LastPromotedArithmeticType; ++Left) {
8163 for (unsigned Right = FirstPromotedArithmeticType;
8164 Right < LastPromotedArithmeticType; ++Right) {
8165 QualType LandR[2] = { ArithmeticTypes[Left],
8166 ArithmeticTypes[Right] };
8167 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8168 }
8169 }
8170
8171 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8172 // conditional operator for vector types.
8173 for (BuiltinCandidateTypeSet::iterator
8174 Vec1 = CandidateTypes[0].vector_begin(),
8175 Vec1End = CandidateTypes[0].vector_end();
8176 Vec1 != Vec1End; ++Vec1) {
8177 for (BuiltinCandidateTypeSet::iterator
8178 Vec2 = CandidateTypes[1].vector_begin(),
8179 Vec2End = CandidateTypes[1].vector_end();
8180 Vec2 != Vec2End; ++Vec2) {
8181 QualType LandR[2] = { *Vec1, *Vec2 };
8182 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8183 }
8184 }
8185 }
8186
8187 // C++2a [over.built]p14:
8188 //
8189 // For every integral type T there exists a candidate operator function
8190 // of the form
8191 //
8192 // std::strong_ordering operator<=>(T, T)
8193 //
8194 // C++2a [over.built]p15:
8195 //
8196 // For every pair of floating-point types L and R, there exists a candidate
8197 // operator function of the form
8198 //
8199 // std::partial_ordering operator<=>(L, R);
8200 //
8201 // FIXME: The current specification for integral types doesn't play nice with
8202 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8203 // comparisons. Under the current spec this can lead to ambiguity during
8204 // overload resolution. For example:
8205 //
8206 // enum A : int {a};
8207 // auto x = (a <=> (long)42);
8208 //
8209 // error: call is ambiguous for arguments 'A' and 'long'.
8210 // note: candidate operator<=>(int, int)
8211 // note: candidate operator<=>(long, long)
8212 //
8213 // To avoid this error, this function deviates from the specification and adds
8214 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8215 // arithmetic types (the same as the generic relational overloads).
8216 //
8217 // For now this function acts as a placeholder.
8218 void addThreeWayArithmeticOverloads() {
8219 addGenericBinaryArithmeticOverloads();
8220 }
8221
8222 // C++ [over.built]p17:
8223 //
8224 // For every pair of promoted integral types L and R, there
8225 // exist candidate operator functions of the form
8226 //
8227 // LR operator%(L, R);
8228 // LR operator&(L, R);
8229 // LR operator^(L, R);
8230 // LR operator|(L, R);
8231 // L operator<<(L, R);
8232 // L operator>>(L, R);
8233 //
8234 // where LR is the result of the usual arithmetic conversions
8235 // between types L and R.
8236 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8237 if (!HasArithmeticOrEnumeralCandidateType)
8238 return;
8239
8240 for (unsigned Left = FirstPromotedIntegralType;
8241 Left < LastPromotedIntegralType; ++Left) {
8242 for (unsigned Right = FirstPromotedIntegralType;
8243 Right < LastPromotedIntegralType; ++Right) {
8244 QualType LandR[2] = { ArithmeticTypes[Left],
8245 ArithmeticTypes[Right] };
8246 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8247 }
8248 }
8249 }
8250
8251 // C++ [over.built]p20:
8252 //
8253 // For every pair (T, VQ), where T is an enumeration or
8254 // pointer to member type and VQ is either volatile or
8255 // empty, there exist candidate operator functions of the form
8256 //
8257 // VQ T& operator=(VQ T&, T);
8258 void addAssignmentMemberPointerOrEnumeralOverloads() {
8259 /// Set of (canonical) types that we've already handled.
8260 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8261
8262 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8263 for (BuiltinCandidateTypeSet::iterator
8264 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8265 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8266 Enum != EnumEnd; ++Enum) {
8267 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8268 continue;
8269
8270 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8271 }
8272
8273 for (BuiltinCandidateTypeSet::iterator
8274 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8275 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8276 MemPtr != MemPtrEnd; ++MemPtr) {
8277 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8278 continue;
8279
8280 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8281 }
8282 }
8283 }
8284
8285 // C++ [over.built]p19:
8286 //
8287 // For every pair (T, VQ), where T is any type and VQ is either
8288 // volatile or empty, there exist candidate operator functions
8289 // of the form
8290 //
8291 // T*VQ& operator=(T*VQ&, T*);
8292 //
8293 // C++ [over.built]p21:
8294 //
8295 // For every pair (T, VQ), where T is a cv-qualified or
8296 // cv-unqualified object type and VQ is either volatile or
8297 // empty, there exist candidate operator functions of the form
8298 //
8299 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8300 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8301 void addAssignmentPointerOverloads(bool isEqualOp) {
8302 /// Set of (canonical) types that we've already handled.
8303 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8304
8305 for (BuiltinCandidateTypeSet::iterator
8306 Ptr = CandidateTypes[0].pointer_begin(),
8307 PtrEnd = CandidateTypes[0].pointer_end();
8308 Ptr != PtrEnd; ++Ptr) {
8309 // If this is operator=, keep track of the builtin candidates we added.
8310 if (isEqualOp)
8311 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8312 else if (!(*Ptr)->getPointeeType()->isObjectType())
8313 continue;
8314
8315 // non-volatile version
8316 QualType ParamTypes[2] = {
8317 S.Context.getLValueReferenceType(*Ptr),
8318 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8319 };
8320 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8321 /*IsAssigmentOperator=*/ isEqualOp);
8322
8323 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8324 VisibleTypeConversionsQuals.hasVolatile();
8325 if (NeedVolatile) {
8326 // volatile version
8327 ParamTypes[0] =
8328 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8329 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8330 /*IsAssigmentOperator=*/isEqualOp);
8331 }
8332
8333 if (!(*Ptr).isRestrictQualified() &&
8334 VisibleTypeConversionsQuals.hasRestrict()) {
8335 // restrict version
8336 ParamTypes[0]
8337 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8338 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8339 /*IsAssigmentOperator=*/isEqualOp);
8340
8341 if (NeedVolatile) {
8342 // volatile restrict version
8343 ParamTypes[0]
8344 = S.Context.getLValueReferenceType(
8345 S.Context.getCVRQualifiedType(*Ptr,
8346 (Qualifiers::Volatile |
8347 Qualifiers::Restrict)));
8348 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8349 /*IsAssigmentOperator=*/isEqualOp);
8350 }
8351 }
8352 }
8353
8354 if (isEqualOp) {
8355 for (BuiltinCandidateTypeSet::iterator
8356 Ptr = CandidateTypes[1].pointer_begin(),
8357 PtrEnd = CandidateTypes[1].pointer_end();
8358 Ptr != PtrEnd; ++Ptr) {
8359 // Make sure we don't add the same candidate twice.
8360 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8361 continue;
8362
8363 QualType ParamTypes[2] = {
8364 S.Context.getLValueReferenceType(*Ptr),
8365 *Ptr,
8366 };
8367
8368 // non-volatile version
8369 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8370 /*IsAssigmentOperator=*/true);
8371
8372 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8373 VisibleTypeConversionsQuals.hasVolatile();
8374 if (NeedVolatile) {
8375 // volatile version
8376 ParamTypes[0] =
8377 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8378 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8379 /*IsAssigmentOperator=*/true);
8380 }
8381
8382 if (!(*Ptr).isRestrictQualified() &&
8383 VisibleTypeConversionsQuals.hasRestrict()) {
8384 // restrict version
8385 ParamTypes[0]
8386 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8387 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8388 /*IsAssigmentOperator=*/true);
8389
8390 if (NeedVolatile) {
8391 // volatile restrict version
8392 ParamTypes[0]
8393 = S.Context.getLValueReferenceType(
8394 S.Context.getCVRQualifiedType(*Ptr,
8395 (Qualifiers::Volatile |
8396 Qualifiers::Restrict)));
8397 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8398 /*IsAssigmentOperator=*/true);
8399 }
8400 }
8401 }
8402 }
8403 }
8404
8405 // C++ [over.built]p18:
8406 //
8407 // For every triple (L, VQ, R), where L is an arithmetic type,
8408 // VQ is either volatile or empty, and R is a promoted
8409 // arithmetic type, there exist candidate operator functions of
8410 // the form
8411 //
8412 // VQ L& operator=(VQ L&, R);
8413 // VQ L& operator*=(VQ L&, R);
8414 // VQ L& operator/=(VQ L&, R);
8415 // VQ L& operator+=(VQ L&, R);
8416 // VQ L& operator-=(VQ L&, R);
8417 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8418 if (!HasArithmeticOrEnumeralCandidateType)
8419 return;
8420
8421 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8422 for (unsigned Right = FirstPromotedArithmeticType;
8423 Right < LastPromotedArithmeticType; ++Right) {
8424 QualType ParamTypes[2];
8425 ParamTypes[1] = ArithmeticTypes[Right];
8426
8427 // Add this built-in operator as a candidate (VQ is empty).
8428 ParamTypes[0] =
8429 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8430 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8431 /*IsAssigmentOperator=*/isEqualOp);
8432
8433 // Add this built-in operator as a candidate (VQ is 'volatile').
8434 if (VisibleTypeConversionsQuals.hasVolatile()) {
8435 ParamTypes[0] =
8436 S.Context.getVolatileType(ArithmeticTypes[Left]);
8437 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8439 /*IsAssigmentOperator=*/isEqualOp);
8440 }
8441 }
8442 }
8443
8444 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8445 for (BuiltinCandidateTypeSet::iterator
8446 Vec1 = CandidateTypes[0].vector_begin(),
8447 Vec1End = CandidateTypes[0].vector_end();
8448 Vec1 != Vec1End; ++Vec1) {
8449 for (BuiltinCandidateTypeSet::iterator
8450 Vec2 = CandidateTypes[1].vector_begin(),
8451 Vec2End = CandidateTypes[1].vector_end();
8452 Vec2 != Vec2End; ++Vec2) {
8453 QualType ParamTypes[2];
8454 ParamTypes[1] = *Vec2;
8455 // Add this built-in operator as a candidate (VQ is empty).
8456 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8457 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8458 /*IsAssigmentOperator=*/isEqualOp);
8459
8460 // Add this built-in operator as a candidate (VQ is 'volatile').
8461 if (VisibleTypeConversionsQuals.hasVolatile()) {
8462 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8463 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8464 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8465 /*IsAssigmentOperator=*/isEqualOp);
8466 }
8467 }
8468 }
8469 }
8470
8471 // C++ [over.built]p22:
8472 //
8473 // For every triple (L, VQ, R), where L is an integral type, VQ
8474 // is either volatile or empty, and R is a promoted integral
8475 // type, there exist candidate operator functions of the form
8476 //
8477 // VQ L& operator%=(VQ L&, R);
8478 // VQ L& operator<<=(VQ L&, R);
8479 // VQ L& operator>>=(VQ L&, R);
8480 // VQ L& operator&=(VQ L&, R);
8481 // VQ L& operator^=(VQ L&, R);
8482 // VQ L& operator|=(VQ L&, R);
8483 void addAssignmentIntegralOverloads() {
8484 if (!HasArithmeticOrEnumeralCandidateType)
8485 return;
8486
8487 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8488 for (unsigned Right = FirstPromotedIntegralType;
8489 Right < LastPromotedIntegralType; ++Right) {
8490 QualType ParamTypes[2];
8491 ParamTypes[1] = ArithmeticTypes[Right];
8492
8493 // Add this built-in operator as a candidate (VQ is empty).
8494 ParamTypes[0] =
8495 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8496 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8497 if (VisibleTypeConversionsQuals.hasVolatile()) {
8498 // Add this built-in operator as a candidate (VQ is 'volatile').
8499 ParamTypes[0] = ArithmeticTypes[Left];
8500 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8501 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8502 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8503 }
8504 }
8505 }
8506 }
8507
8508 // C++ [over.operator]p23:
8509 //
8510 // There also exist candidate operator functions of the form
8511 //
8512 // bool operator!(bool);
8513 // bool operator&&(bool, bool);
8514 // bool operator||(bool, bool);
8515 void addExclaimOverload() {
8516 QualType ParamTy = S.Context.BoolTy;
8517 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8518 /*IsAssignmentOperator=*/false,
8519 /*NumContextualBoolArguments=*/1);
8520 }
8521 void addAmpAmpOrPipePipeOverload() {
8522 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8523 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8524 /*IsAssignmentOperator=*/false,
8525 /*NumContextualBoolArguments=*/2);
8526 }
8527
8528 // C++ [over.built]p13:
8529 //
8530 // For every cv-qualified or cv-unqualified object type T there
8531 // exist candidate operator functions of the form
8532 //
8533 // T* operator+(T*, ptrdiff_t); [ABOVE]
8534 // T& operator[](T*, ptrdiff_t);
8535 // T* operator-(T*, ptrdiff_t); [ABOVE]
8536 // T* operator+(ptrdiff_t, T*); [ABOVE]
8537 // T& operator[](ptrdiff_t, T*);
8538 void addSubscriptOverloads() {
8539 for (BuiltinCandidateTypeSet::iterator
8540 Ptr = CandidateTypes[0].pointer_begin(),
8541 PtrEnd = CandidateTypes[0].pointer_end();
8542 Ptr != PtrEnd; ++Ptr) {
8543 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8544 QualType PointeeType = (*Ptr)->getPointeeType();
8545 if (!PointeeType->isObjectType())
8546 continue;
8547
8548 // T& operator[](T*, ptrdiff_t)
8549 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8550 }
8551
8552 for (BuiltinCandidateTypeSet::iterator
8553 Ptr = CandidateTypes[1].pointer_begin(),
8554 PtrEnd = CandidateTypes[1].pointer_end();
8555 Ptr != PtrEnd; ++Ptr) {
8556 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8557 QualType PointeeType = (*Ptr)->getPointeeType();
8558 if (!PointeeType->isObjectType())
8559 continue;
8560
8561 // T& operator[](ptrdiff_t, T*)
8562 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8563 }
8564 }
8565
8566 // C++ [over.built]p11:
8567 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8568 // C1 is the same type as C2 or is a derived class of C2, T is an object
8569 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8570 // there exist candidate operator functions of the form
8571 //
8572 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8573 //
8574 // where CV12 is the union of CV1 and CV2.
8575 void addArrowStarOverloads() {
8576 for (BuiltinCandidateTypeSet::iterator
8577 Ptr = CandidateTypes[0].pointer_begin(),
8578 PtrEnd = CandidateTypes[0].pointer_end();
8579 Ptr != PtrEnd; ++Ptr) {
8580 QualType C1Ty = (*Ptr);
8581 QualType C1;
8582 QualifierCollector Q1;
8583 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8584 if (!isa<RecordType>(C1))
8585 continue;
8586 // heuristic to reduce number of builtin candidates in the set.
8587 // Add volatile/restrict version only if there are conversions to a
8588 // volatile/restrict type.
8589 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8590 continue;
8591 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8592 continue;
8593 for (BuiltinCandidateTypeSet::iterator
8594 MemPtr = CandidateTypes[1].member_pointer_begin(),
8595 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8596 MemPtr != MemPtrEnd; ++MemPtr) {
8597 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8598 QualType C2 = QualType(mptr->getClass(), 0);
8599 C2 = C2.getUnqualifiedType();
8600 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8601 break;
8602 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8603 // build CV12 T&
8604 QualType T = mptr->getPointeeType();
8605 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8606 T.isVolatileQualified())
8607 continue;
8608 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8609 T.isRestrictQualified())
8610 continue;
8611 T = Q1.apply(S.Context, T);
8612 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8613 }
8614 }
8615 }
8616
8617 // Note that we don't consider the first argument, since it has been
8618 // contextually converted to bool long ago. The candidates below are
8619 // therefore added as binary.
8620 //
8621 // C++ [over.built]p25:
8622 // For every type T, where T is a pointer, pointer-to-member, or scoped
8623 // enumeration type, there exist candidate operator functions of the form
8624 //
8625 // T operator?(bool, T, T);
8626 //
8627 void addConditionalOperatorOverloads() {
8628 /// Set of (canonical) types that we've already handled.
8629 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8630
8631 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8632 for (BuiltinCandidateTypeSet::iterator
8633 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8634 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8635 Ptr != PtrEnd; ++Ptr) {
8636 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8637 continue;
8638
8639 QualType ParamTypes[2] = { *Ptr, *Ptr };
8640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8641 }
8642
8643 for (BuiltinCandidateTypeSet::iterator
8644 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8645 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8646 MemPtr != MemPtrEnd; ++MemPtr) {
8647 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8648 continue;
8649
8650 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8651 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8652 }
8653
8654 if (S.getLangOpts().CPlusPlus11) {
8655 for (BuiltinCandidateTypeSet::iterator
8656 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8657 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8658 Enum != EnumEnd; ++Enum) {
8659 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8660 continue;
8661
8662 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8663 continue;
8664
8665 QualType ParamTypes[2] = { *Enum, *Enum };
8666 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8667 }
8668 }
8669 }
8670 }
8671};
8672
8673} // end anonymous namespace
8674
8675/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8676/// operator overloads to the candidate set (C++ [over.built]), based
8677/// on the operator @p Op and the arguments given. For example, if the
8678/// operator is a binary '+', this routine might add "int
8679/// operator+(int, int)" to cover integer addition.
8680void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8681 SourceLocation OpLoc,
8682 ArrayRef<Expr *> Args,
8683 OverloadCandidateSet &CandidateSet) {
8684 // Find all of the types that the arguments can convert to, but only
8685 // if the operator we're looking at has built-in operator candidates
8686 // that make use of these types. Also record whether we encounter non-record
8687 // candidate types or either arithmetic or enumeral candidate types.
8688 Qualifiers VisibleTypeConversionsQuals;
8689 VisibleTypeConversionsQuals.addConst();
8690 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8691 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8692
8693 bool HasNonRecordCandidateType = false;
8694 bool HasArithmeticOrEnumeralCandidateType = false;
8695 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8696 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8697 CandidateTypes.emplace_back(*this);
8698 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8699 OpLoc,
8700 true,
8701 (Op == OO_Exclaim ||
8702 Op == OO_AmpAmp ||
8703 Op == OO_PipePipe),
8704 VisibleTypeConversionsQuals);
8705 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8706 CandidateTypes[ArgIdx].hasNonRecordTypes();
8707 HasArithmeticOrEnumeralCandidateType =
8708 HasArithmeticOrEnumeralCandidateType ||
8709 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8710 }
8711
8712 // Exit early when no non-record types have been added to the candidate set
8713 // for any of the arguments to the operator.
8714 //
8715 // We can't exit early for !, ||, or &&, since there we have always have
8716 // 'bool' overloads.
8717 if (!HasNonRecordCandidateType &&
8718 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8719 return;
8720
8721 // Setup an object to manage the common state for building overloads.
8722 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8723 VisibleTypeConversionsQuals,
8724 HasArithmeticOrEnumeralCandidateType,
8725 CandidateTypes, CandidateSet);
8726
8727 // Dispatch over the operation to add in only those overloads which apply.
8728 switch (Op) {
8729 case OO_None:
8730 case NUM_OVERLOADED_OPERATORS:
8731 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 8731)
;
8732
8733 case OO_New:
8734 case OO_Delete:
8735 case OO_Array_New:
8736 case OO_Array_Delete:
8737 case OO_Call:
8738 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 8739)
8739 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 8739)
;
8740
8741 case OO_Comma:
8742 case OO_Arrow:
8743 case OO_Coawait:
8744 // C++ [over.match.oper]p3:
8745 // -- For the operator ',', the unary operator '&', the
8746 // operator '->', or the operator 'co_await', the
8747 // built-in candidates set is empty.
8748 break;
8749
8750 case OO_Plus: // '+' is either unary or binary
8751 if (Args.size() == 1)
8752 OpBuilder.addUnaryPlusPointerOverloads();
8753 LLVM_FALLTHROUGH[[clang::fallthrough]];
8754
8755 case OO_Minus: // '-' is either unary or binary
8756 if (Args.size() == 1) {
8757 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8758 } else {
8759 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8760 OpBuilder.addGenericBinaryArithmeticOverloads();
8761 }
8762 break;
8763
8764 case OO_Star: // '*' is either unary or binary
8765 if (Args.size() == 1)
8766 OpBuilder.addUnaryStarPointerOverloads();
8767 else
8768 OpBuilder.addGenericBinaryArithmeticOverloads();
8769 break;
8770
8771 case OO_Slash:
8772 OpBuilder.addGenericBinaryArithmeticOverloads();
8773 break;
8774
8775 case OO_PlusPlus:
8776 case OO_MinusMinus:
8777 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8778 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8779 break;
8780
8781 case OO_EqualEqual:
8782 case OO_ExclaimEqual:
8783 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8784 LLVM_FALLTHROUGH[[clang::fallthrough]];
8785
8786 case OO_Less:
8787 case OO_Greater:
8788 case OO_LessEqual:
8789 case OO_GreaterEqual:
8790 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8791 OpBuilder.addGenericBinaryArithmeticOverloads();
8792 break;
8793
8794 case OO_Spaceship:
8795 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8796 OpBuilder.addThreeWayArithmeticOverloads();
8797 break;
8798
8799 case OO_Percent:
8800 case OO_Caret:
8801 case OO_Pipe:
8802 case OO_LessLess:
8803 case OO_GreaterGreater:
8804 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8805 break;
8806
8807 case OO_Amp: // '&' is either unary or binary
8808 if (Args.size() == 1)
8809 // C++ [over.match.oper]p3:
8810 // -- For the operator ',', the unary operator '&', or the
8811 // operator '->', the built-in candidates set is empty.
8812 break;
8813
8814 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8815 break;
8816
8817 case OO_Tilde:
8818 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8819 break;
8820
8821 case OO_Equal:
8822 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8823 LLVM_FALLTHROUGH[[clang::fallthrough]];
8824
8825 case OO_PlusEqual:
8826 case OO_MinusEqual:
8827 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8828 LLVM_FALLTHROUGH[[clang::fallthrough]];
8829
8830 case OO_StarEqual:
8831 case OO_SlashEqual:
8832 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8833 break;
8834
8835 case OO_PercentEqual:
8836 case OO_LessLessEqual:
8837 case OO_GreaterGreaterEqual:
8838 case OO_AmpEqual:
8839 case OO_CaretEqual:
8840 case OO_PipeEqual:
8841 OpBuilder.addAssignmentIntegralOverloads();
8842 break;
8843
8844 case OO_Exclaim:
8845 OpBuilder.addExclaimOverload();
8846 break;
8847
8848 case OO_AmpAmp:
8849 case OO_PipePipe:
8850 OpBuilder.addAmpAmpOrPipePipeOverload();
8851 break;
8852
8853 case OO_Subscript:
8854 OpBuilder.addSubscriptOverloads();
8855 break;
8856
8857 case OO_ArrowStar:
8858 OpBuilder.addArrowStarOverloads();
8859 break;
8860
8861 case OO_Conditional:
8862 OpBuilder.addConditionalOperatorOverloads();
8863 OpBuilder.addGenericBinaryArithmeticOverloads();
8864 break;
8865 }
8866}
8867
8868/// Add function candidates found via argument-dependent lookup
8869/// to the set of overloading candidates.
8870///
8871/// This routine performs argument-dependent name lookup based on the
8872/// given function name (which may also be an operator name) and adds
8873/// all of the overload candidates found by ADL to the overload
8874/// candidate set (C++ [basic.lookup.argdep]).
8875void
8876Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8877 SourceLocation Loc,
8878 ArrayRef<Expr *> Args,
8879 TemplateArgumentListInfo *ExplicitTemplateArgs,
8880 OverloadCandidateSet& CandidateSet,
8881 bool PartialOverloading) {
8882 ADLResult Fns;
8883
8884 // FIXME: This approach for uniquing ADL results (and removing
8885 // redundant candidates from the set) relies on pointer-equality,
8886 // which means we need to key off the canonical decl. However,
8887 // always going back to the canonical decl might not get us the
8888 // right set of default arguments. What default arguments are
8889 // we supposed to consider on ADL candidates, anyway?
8890
8891 // FIXME: Pass in the explicit template arguments?
8892 ArgumentDependentLookup(Name, Loc, Args, Fns);
8893
8894 // Erase all of the candidates we already knew about.
8895 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8896 CandEnd = CandidateSet.end();
8897 Cand != CandEnd; ++Cand)
8898 if (Cand->Function) {
8899 Fns.erase(Cand->Function);
8900 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8901 Fns.erase(FunTmpl);
8902 }
8903
8904 // For each of the ADL candidates we found, add it to the overload
8905 // set.
8906 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8907 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8908 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8909 if (ExplicitTemplateArgs)
8910 continue;
8911
8912 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8913 PartialOverloading);
8914 } else
8915 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8916 FoundDecl, ExplicitTemplateArgs,
8917 Args, CandidateSet, PartialOverloading);
8918 }
8919}
8920
8921namespace {
8922enum class Comparison { Equal, Better, Worse };
8923}
8924
8925/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8926/// overload resolution.
8927///
8928/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8929/// Cand1's first N enable_if attributes have precisely the same conditions as
8930/// Cand2's first N enable_if attributes (where N = the number of enable_if
8931/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8932///
8933/// Note that you can have a pair of candidates such that Cand1's enable_if
8934/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8935/// worse than Cand1's.
8936static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8937 const FunctionDecl *Cand2) {
8938 // Common case: One (or both) decls don't have enable_if attrs.
8939 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8940 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8941 if (!Cand1Attr || !Cand2Attr) {
8942 if (Cand1Attr == Cand2Attr)
8943 return Comparison::Equal;
8944 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8945 }
8946
8947 // FIXME: The next several lines are just
8948 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8949 // instead of reverse order which is how they're stored in the AST.
8950 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8951 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8952
8953 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8954 // has fewer enable_if attributes than Cand2.
8955 if (Cand1Attrs.size() < Cand2Attrs.size())
8956 return Comparison::Worse;
8957
8958 auto Cand1I = Cand1Attrs.begin();
8959 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8960 for (auto &Cand2A : Cand2Attrs) {
8961 Cand1ID.clear();
8962 Cand2ID.clear();
8963
8964 auto &Cand1A = *Cand1I++;
8965 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8966 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8967 if (Cand1ID != Cand2ID)
8968 return Comparison::Worse;
8969 }
8970
8971 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8972}
8973
8974/// isBetterOverloadCandidate - Determines whether the first overload
8975/// candidate is a better candidate than the second (C++ 13.3.3p1).
8976bool clang::isBetterOverloadCandidate(
8977 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
8978 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
8979 // Define viable functions to be better candidates than non-viable
8980 // functions.
8981 if (!Cand2.Viable)
8982 return Cand1.Viable;
8983 else if (!Cand1.Viable)
8984 return false;
8985
8986 // C++ [over.match.best]p1:
8987 //
8988 // -- if F is a static member function, ICS1(F) is defined such
8989 // that ICS1(F) is neither better nor worse than ICS1(G) for
8990 // any function G, and, symmetrically, ICS1(G) is neither
8991 // better nor worse than ICS1(F).
8992 unsigned StartArg = 0;
8993 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8994 StartArg = 1;
8995
8996 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8997 // We don't allow incompatible pointer conversions in C++.
8998 if (!S.getLangOpts().CPlusPlus)
8999 return ICS.isStandard() &&
9000 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9001
9002 // The only ill-formed conversion we allow in C++ is the string literal to
9003 // char* conversion, which is only considered ill-formed after C++11.
9004 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9005 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9006 };
9007
9008 // Define functions that don't require ill-formed conversions for a given
9009 // argument to be better candidates than functions that do.
9010 unsigned NumArgs = Cand1.Conversions.size();
9011 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch")(static_cast <bool> (Cand2.Conversions.size() == NumArgs
&& "Overload candidate mismatch") ? void (0) : __assert_fail
("Cand2.Conversions.size() == NumArgs && \"Overload candidate mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9011, __extension__ __PRETTY_FUNCTION__))
;
9012 bool HasBetterConversion = false;
9013 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9014 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9015 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9016 if (Cand1Bad != Cand2Bad) {
9017 if (Cand1Bad)
9018 return false;
9019 HasBetterConversion = true;
9020 }
9021 }
9022
9023 if (HasBetterConversion)
9024 return true;
9025
9026 // C++ [over.match.best]p1:
9027 // A viable function F1 is defined to be a better function than another
9028 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9029 // conversion sequence than ICSi(F2), and then...
9030 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9031 switch (CompareImplicitConversionSequences(S, Loc,
9032 Cand1.Conversions[ArgIdx],
9033 Cand2.Conversions[ArgIdx])) {
9034 case ImplicitConversionSequence::Better:
9035 // Cand1 has a better conversion sequence.
9036 HasBetterConversion = true;
9037 break;
9038
9039 case ImplicitConversionSequence::Worse:
9040 // Cand1 can't be better than Cand2.
9041 return false;
9042
9043 case ImplicitConversionSequence::Indistinguishable:
9044 // Do nothing.
9045 break;
9046 }
9047 }
9048
9049 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9050 // ICSj(F2), or, if not that,
9051 if (HasBetterConversion)
9052 return true;
9053
9054 // -- the context is an initialization by user-defined conversion
9055 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9056 // from the return type of F1 to the destination type (i.e.,
9057 // the type of the entity being initialized) is a better
9058 // conversion sequence than the standard conversion sequence
9059 // from the return type of F2 to the destination type.
9060 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9061 Cand1.Function && Cand2.Function &&
9062 isa<CXXConversionDecl>(Cand1.Function) &&
9063 isa<CXXConversionDecl>(Cand2.Function)) {
9064 // First check whether we prefer one of the conversion functions over the
9065 // other. This only distinguishes the results in non-standard, extension
9066 // cases such as the conversion from a lambda closure type to a function
9067 // pointer or block.
9068 ImplicitConversionSequence::CompareKind Result =
9069 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9070 if (Result == ImplicitConversionSequence::Indistinguishable)
9071 Result = CompareStandardConversionSequences(S, Loc,
9072 Cand1.FinalConversion,
9073 Cand2.FinalConversion);
9074
9075 if (Result != ImplicitConversionSequence::Indistinguishable)
9076 return Result == ImplicitConversionSequence::Better;
9077
9078 // FIXME: Compare kind of reference binding if conversion functions
9079 // convert to a reference type used in direct reference binding, per
9080 // C++14 [over.match.best]p1 section 2 bullet 3.
9081 }
9082
9083 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9084 // as combined with the resolution to CWG issue 243.
9085 //
9086 // When the context is initialization by constructor ([over.match.ctor] or
9087 // either phase of [over.match.list]), a constructor is preferred over
9088 // a conversion function.
9089 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9090 Cand1.Function && Cand2.Function &&
9091 isa<CXXConstructorDecl>(Cand1.Function) !=
9092 isa<CXXConstructorDecl>(Cand2.Function))
9093 return isa<CXXConstructorDecl>(Cand1.Function);
9094
9095 // -- F1 is a non-template function and F2 is a function template
9096 // specialization, or, if not that,
9097 bool Cand1IsSpecialization = Cand1.Function &&
9098 Cand1.Function->getPrimaryTemplate();
9099 bool Cand2IsSpecialization = Cand2.Function &&
9100 Cand2.Function->getPrimaryTemplate();
9101 if (Cand1IsSpecialization != Cand2IsSpecialization)
9102 return Cand2IsSpecialization;
9103
9104 // -- F1 and F2 are function template specializations, and the function
9105 // template for F1 is more specialized than the template for F2
9106 // according to the partial ordering rules described in 14.5.5.2, or,
9107 // if not that,
9108 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9109 if (FunctionTemplateDecl *BetterTemplate
9110 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9111 Cand2.Function->getPrimaryTemplate(),
9112 Loc,
9113 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9114 : TPOC_Call,
9115 Cand1.ExplicitCallArguments,
9116 Cand2.ExplicitCallArguments))
9117 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9118 }
9119
9120 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9121 // A derived-class constructor beats an (inherited) base class constructor.
9122 bool Cand1IsInherited =
9123 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9124 bool Cand2IsInherited =
9125 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9126 if (Cand1IsInherited != Cand2IsInherited)
9127 return Cand2IsInherited;
9128 else if (Cand1IsInherited) {
9129 assert(Cand2IsInherited)(static_cast <bool> (Cand2IsInherited) ? void (0) : __assert_fail
("Cand2IsInherited", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9129, __extension__ __PRETTY_FUNCTION__))
;
9130 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9131 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9132 if (Cand1Class->isDerivedFrom(Cand2Class))
9133 return true;
9134 if (Cand2Class->isDerivedFrom(Cand1Class))
9135 return false;
9136 // Inherited from sibling base classes: still ambiguous.
9137 }
9138
9139 // Check C++17 tie-breakers for deduction guides.
9140 {
9141 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9142 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9143 if (Guide1 && Guide2) {
9144 // -- F1 is generated from a deduction-guide and F2 is not
9145 if (Guide1->isImplicit() != Guide2->isImplicit())
9146 return Guide2->isImplicit();
9147
9148 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9149 if (Guide1->isCopyDeductionCandidate())
9150 return true;
9151 }
9152 }
9153
9154 // Check for enable_if value-based overload resolution.
9155 if (Cand1.Function && Cand2.Function) {
9156 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9157 if (Cmp != Comparison::Equal)
9158 return Cmp == Comparison::Better;
9159 }
9160
9161 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9162 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9163 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9164 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9165 }
9166
9167 bool HasPS1 = Cand1.Function != nullptr &&
9168 functionHasPassObjectSizeParams(Cand1.Function);
9169 bool HasPS2 = Cand2.Function != nullptr &&
9170 functionHasPassObjectSizeParams(Cand2.Function);
9171 return HasPS1 != HasPS2 && HasPS1;
9172}
9173
9174/// Determine whether two declarations are "equivalent" for the purposes of
9175/// name lookup and overload resolution. This applies when the same internal/no
9176/// linkage entity is defined by two modules (probably by textually including
9177/// the same header). In such a case, we don't consider the declarations to
9178/// declare the same entity, but we also don't want lookups with both
9179/// declarations visible to be ambiguous in some cases (this happens when using
9180/// a modularized libstdc++).
9181bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9182 const NamedDecl *B) {
9183 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9184 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9185 if (!VA || !VB)
9186 return false;
9187
9188 // The declarations must be declaring the same name as an internal linkage
9189 // entity in different modules.
9190 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9191 VB->getDeclContext()->getRedeclContext()) ||
9192 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9193 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9194 VA->isExternallyVisible() || VB->isExternallyVisible())
9195 return false;
9196
9197 // Check that the declarations appear to be equivalent.
9198 //
9199 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9200 // For constants and functions, we should check the initializer or body is
9201 // the same. For non-constant variables, we shouldn't allow it at all.
9202 if (Context.hasSameType(VA->getType(), VB->getType()))
9203 return true;
9204
9205 // Enum constants within unnamed enumerations will have different types, but
9206 // may still be similar enough to be interchangeable for our purposes.
9207 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9208 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9209 // Only handle anonymous enums. If the enumerations were named and
9210 // equivalent, they would have been merged to the same type.
9211 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9212 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9213 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9214 !Context.hasSameType(EnumA->getIntegerType(),
9215 EnumB->getIntegerType()))
9216 return false;
9217 // Allow this only if the value is the same for both enumerators.
9218 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9219 }
9220 }
9221
9222 // Nothing else is sufficiently similar.
9223 return false;
9224}
9225
9226void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9227 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9228 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9229
9230 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9231 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9232 << !M << (M ? M->getFullModuleName() : "");
9233
9234 for (auto *E : Equiv) {
9235 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9236 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9237 << !M << (M ? M->getFullModuleName() : "");
9238 }
9239}
9240
9241/// Computes the best viable function (C++ 13.3.3)
9242/// within an overload candidate set.
9243///
9244/// \param Loc The location of the function name (or operator symbol) for
9245/// which overload resolution occurs.
9246///
9247/// \param Best If overload resolution was successful or found a deleted
9248/// function, \p Best points to the candidate function found.
9249///
9250/// \returns The result of overload resolution.
9251OverloadingResult
9252OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9253 iterator &Best) {
9254 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9255 std::transform(begin(), end(), std::back_inserter(Candidates),
9256 [](OverloadCandidate &Cand) { return &Cand; });
9257
9258 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9259 // are accepted by both clang and NVCC. However, during a particular
9260 // compilation mode only one call variant is viable. We need to
9261 // exclude non-viable overload candidates from consideration based
9262 // only on their host/device attributes. Specifically, if one
9263 // candidate call is WrongSide and the other is SameSide, we ignore
9264 // the WrongSide candidate.
9265 if (S.getLangOpts().CUDA) {
9266 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9267 bool ContainsSameSideCandidate =
9268 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9269 return Cand->Function &&
9270 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9271 Sema::CFP_SameSide;
9272 });
9273 if (ContainsSameSideCandidate) {
9274 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9275 return Cand->Function &&
9276 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9277 Sema::CFP_WrongSide;
9278 };
9279 llvm::erase_if(Candidates, IsWrongSideCandidate);
9280 }
9281 }
9282
9283 // Find the best viable function.
9284 Best = end();
9285 for (auto *Cand : Candidates)
9286 if (Cand->Viable)
9287 if (Best == end() ||
9288 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9289 Best = Cand;
9290
9291 // If we didn't find any viable functions, abort.
9292 if (Best == end())
9293 return OR_No_Viable_Function;
9294
9295 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9296
9297 // Make sure that this function is better than every other viable
9298 // function. If not, we have an ambiguity.
9299 for (auto *Cand : Candidates) {
9300 if (Cand->Viable && Cand != Best &&
9301 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9302 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9303 Cand->Function)) {
9304 EquivalentCands.push_back(Cand->Function);
9305 continue;
9306 }
9307
9308 Best = end();
9309 return OR_Ambiguous;
9310 }
9311 }
9312
9313 // Best is the best viable function.
9314 if (Best->Function &&
9315 (Best->Function->isDeleted() ||
9316 S.isFunctionConsideredUnavailable(Best->Function)))
9317 return OR_Deleted;
9318
9319 if (!EquivalentCands.empty())
9320 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9321 EquivalentCands);
9322
9323 return OR_Success;
9324}
9325
9326namespace {
9327
9328enum OverloadCandidateKind {
9329 oc_function,
9330 oc_method,
9331 oc_constructor,
9332 oc_implicit_default_constructor,
9333 oc_implicit_copy_constructor,
9334 oc_implicit_move_constructor,
9335 oc_implicit_copy_assignment,
9336 oc_implicit_move_assignment,
9337 oc_inherited_constructor
9338};
9339
9340enum OverloadCandidateSelect {
9341 ocs_non_template,
9342 ocs_template,
9343 ocs_described_template,
9344};
9345
9346static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9347ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9348 std::string &Description) {
9349
9350 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9351 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9352 isTemplate = true;
9353 Description = S.getTemplateArgumentBindingsText(
9354 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9355 }
9356
9357 OverloadCandidateSelect Select = [&]() {
9358 if (!Description.empty())
9359 return ocs_described_template;
9360 return isTemplate ? ocs_template : ocs_non_template;
9361 }();
9362
9363 OverloadCandidateKind Kind = [&]() {
9364 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9365 if (!Ctor->isImplicit()) {
9366 if (isa<ConstructorUsingShadowDecl>(Found))
9367 return oc_inherited_constructor;
9368 else
9369 return oc_constructor;
9370 }
9371
9372 if (Ctor->isDefaultConstructor())
9373 return oc_implicit_default_constructor;
9374
9375 if (Ctor->isMoveConstructor())
9376 return oc_implicit_move_constructor;
9377
9378 assert(Ctor->isCopyConstructor() &&(static_cast <bool> (Ctor->isCopyConstructor() &&
"unexpected sort of implicit constructor") ? void (0) : __assert_fail
("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9379, __extension__ __PRETTY_FUNCTION__))
9379 "unexpected sort of implicit constructor")(static_cast <bool> (Ctor->isCopyConstructor() &&
"unexpected sort of implicit constructor") ? void (0) : __assert_fail
("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9379, __extension__ __PRETTY_FUNCTION__))
;
9380 return oc_implicit_copy_constructor;
9381 }
9382
9383 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9384 // This actually gets spelled 'candidate function' for now, but
9385 // it doesn't hurt to split it out.
9386 if (!Meth->isImplicit())
9387 return oc_method;
9388
9389 if (Meth->isMoveAssignmentOperator())
9390 return oc_implicit_move_assignment;
9391
9392 if (Meth->isCopyAssignmentOperator())
9393 return oc_implicit_copy_assignment;
9394
9395 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")(static_cast <bool> (isa<CXXConversionDecl>(Meth)
&& "expected conversion") ? void (0) : __assert_fail
("isa<CXXConversionDecl>(Meth) && \"expected conversion\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9395, __extension__ __PRETTY_FUNCTION__))
;
9396 return oc_method;
9397 }
9398
9399 return oc_function;
9400 }();
9401
9402 return std::make_pair(Kind, Select);
9403}
9404
9405void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9406 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9407 // set.
9408 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9409 S.Diag(FoundDecl->getLocation(),
9410 diag::note_ovl_candidate_inherited_constructor)
9411 << Shadow->getNominatedBaseClass();
9412}
9413
9414} // end anonymous namespace
9415
9416static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9417 const FunctionDecl *FD) {
9418 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9419 bool AlwaysTrue;
9420 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9421 return false;
9422 if (!AlwaysTrue)
9423 return false;
9424 }
9425 return true;
9426}
9427
9428/// Returns true if we can take the address of the function.
9429///
9430/// \param Complain - If true, we'll emit a diagnostic
9431/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9432/// we in overload resolution?
9433/// \param Loc - The location of the statement we're complaining about. Ignored
9434/// if we're not complaining, or if we're in overload resolution.
9435static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9436 bool Complain,
9437 bool InOverloadResolution,
9438 SourceLocation Loc) {
9439 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9440 if (Complain) {
9441 if (InOverloadResolution)
9442 S.Diag(FD->getLocStart(),
9443 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9444 else
9445 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9446 }
9447 return false;
9448 }
9449
9450 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9451 return P->hasAttr<PassObjectSizeAttr>();
9452 });
9453 if (I == FD->param_end())
9454 return true;
9455
9456 if (Complain) {
9457 // Add one to ParamNo because it's user-facing
9458 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9459 if (InOverloadResolution)
9460 S.Diag(FD->getLocation(),
9461 diag::note_ovl_candidate_has_pass_object_size_params)
9462 << ParamNo;
9463 else
9464 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9465 << FD << ParamNo;
9466 }
9467 return false;
9468}
9469
9470static bool checkAddressOfCandidateIsAvailable(Sema &S,
9471 const FunctionDecl *FD) {
9472 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9473 /*InOverloadResolution=*/true,
9474 /*Loc=*/SourceLocation());
9475}
9476
9477bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9478 bool Complain,
9479 SourceLocation Loc) {
9480 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9481 /*InOverloadResolution=*/false,
9482 Loc);
9483}
9484
9485// Notes the location of an overload candidate.
9486void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9487 QualType DestType, bool TakingAddress) {
9488 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9489 return;
9490 if (Fn->isMultiVersion() && !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9491 return;
9492
9493 std::string FnDesc;
9494 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9495 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9496 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9497 << (unsigned)KSPair.first << (unsigned)KSPair.second
9498 << Fn << FnDesc;
9499
9500 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9501 Diag(Fn->getLocation(), PD);
9502 MaybeEmitInheritedConstructorNote(*this, Found);
9503}
9504
9505// Notes the location of all overload candidates designated through
9506// OverloadedExpr
9507void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9508 bool TakingAddress) {
9509 assert(OverloadedExpr->getType() == Context.OverloadTy)(static_cast <bool> (OverloadedExpr->getType() == Context
.OverloadTy) ? void (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9509, __extension__ __PRETTY_FUNCTION__))
;
9510
9511 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9512 OverloadExpr *OvlExpr = Ovl.Expression;
9513
9514 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9515 IEnd = OvlExpr->decls_end();
9516 I != IEnd; ++I) {
9517 if (FunctionTemplateDecl *FunTmpl =
9518 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9519 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9520 TakingAddress);
9521 } else if (FunctionDecl *Fun
9522 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9523 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9524 }
9525 }
9526}
9527
9528/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9529/// "lead" diagnostic; it will be given two arguments, the source and
9530/// target types of the conversion.
9531void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9532 Sema &S,
9533 SourceLocation CaretLoc,
9534 const PartialDiagnostic &PDiag) const {
9535 S.Diag(CaretLoc, PDiag)
9536 << Ambiguous.getFromType() << Ambiguous.getToType();
9537 // FIXME: The note limiting machinery is borrowed from
9538 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9539 // refactoring here.
9540 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9541 unsigned CandsShown = 0;
9542 AmbiguousConversionSequence::const_iterator I, E;
9543 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9544 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9545 break;
9546 ++CandsShown;
9547 S.NoteOverloadCandidate(I->first, I->second);
9548 }
9549 if (I != E)
9550 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9551}
9552
9553static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9554 unsigned I, bool TakingCandidateAddress) {
9555 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9556 assert(Conv.isBad())(static_cast <bool> (Conv.isBad()) ? void (0) : __assert_fail
("Conv.isBad()", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9556, __extension__ __PRETTY_FUNCTION__))
;
9557 assert(Cand->Function && "for now, candidate must be a function")(static_cast <bool> (Cand->Function && "for now, candidate must be a function"
) ? void (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9557, __extension__ __PRETTY_FUNCTION__))
;
9558 FunctionDecl *Fn = Cand->Function;
9559
9560 // There's a conversion slot for the object argument if this is a
9561 // non-constructor method. Note that 'I' corresponds the
9562 // conversion-slot index.
9563 bool isObjectArgument = false;
9564 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9565 if (I == 0)
9566 isObjectArgument = true;
9567 else
9568 I--;
9569 }
9570
9571 std::string FnDesc;
9572 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9573 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9574
9575 Expr *FromExpr = Conv.Bad.FromExpr;
9576 QualType FromTy = Conv.Bad.getFromType();
9577 QualType ToTy = Conv.Bad.getToType();
9578
9579 if (FromTy == S.Context.OverloadTy) {
9580 assert(FromExpr && "overload set argument came from implicit argument?")(static_cast <bool> (FromExpr && "overload set argument came from implicit argument?"
) ? void (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9580, __extension__ __PRETTY_FUNCTION__))
;
9581 Expr *E = FromExpr->IgnoreParens();
9582 if (isa<UnaryOperator>(E))
9583 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9584 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9585
9586 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9587 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9588 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9589 << Name << I + 1;
9590 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9591 return;
9592 }
9593
9594 // Do some hand-waving analysis to see if the non-viability is due
9595 // to a qualifier mismatch.
9596 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9597 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9598 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9599 CToTy = RT->getPointeeType();
9600 else {
9601 // TODO: detect and diagnose the full richness of const mismatches.
9602 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9603 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9604 CFromTy = FromPT->getPointeeType();
9605 CToTy = ToPT->getPointeeType();
9606 }
9607 }
9608
9609 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9610 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9611 Qualifiers FromQs = CFromTy.getQualifiers();
9612 Qualifiers ToQs = CToTy.getQualifiers();
9613
9614 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9615 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9616 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9617 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9618 << ToTy << (unsigned)isObjectArgument << I + 1;
9619 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9620 return;
9621 }
9622
9623 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9624 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9625 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9626 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9627 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9628 << (unsigned)isObjectArgument << I + 1;
9629 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9630 return;
9631 }
9632
9633 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9634 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9635 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9636 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9637 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9638 << (unsigned)isObjectArgument << I + 1;
9639 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9640 return;
9641 }
9642
9643 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9644 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9645 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9646 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9647 << FromQs.hasUnaligned() << I + 1;
9648 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9649 return;
9650 }
9651
9652 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9653 assert(CVR && "unexpected qualifiers mismatch")(static_cast <bool> (CVR && "unexpected qualifiers mismatch"
) ? void (0) : __assert_fail ("CVR && \"unexpected qualifiers mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9653, __extension__ __PRETTY_FUNCTION__))
;
9654
9655 if (isObjectArgument) {
9656 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9657 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9658 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9659 << (CVR - 1);
9660 } else {
9661 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9662 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9663 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9664 << (CVR - 1) << I + 1;
9665 }
9666 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9667 return;
9668 }
9669
9670 // Special diagnostic for failure to convert an initializer list, since
9671 // telling the user that it has type void is not useful.
9672 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9673 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9674 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9675 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9676 << ToTy << (unsigned)isObjectArgument << I + 1;
9677 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9678 return;
9679 }
9680
9681 // Diagnose references or pointers to incomplete types differently,
9682 // since it's far from impossible that the incompleteness triggered
9683 // the failure.
9684 QualType TempFromTy = FromTy.getNonReferenceType();
9685 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9686 TempFromTy = PTy->getPointeeType();
9687 if (TempFromTy->isIncompleteType()) {
9688 // Emit the generic diagnostic and, optionally, add the hints to it.
9689 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9690 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9691 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9692 << ToTy << (unsigned)isObjectArgument << I + 1
9693 << (unsigned)(Cand->Fix.Kind);
9694
9695 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9696 return;
9697 }
9698
9699 // Diagnose base -> derived pointer conversions.
9700 unsigned BaseToDerivedConversion = 0;
9701 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9702 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9703 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9704 FromPtrTy->getPointeeType()) &&
9705 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9706 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9707 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9708 FromPtrTy->getPointeeType()))
9709 BaseToDerivedConversion = 1;
9710 }
9711 } else if (const ObjCObjectPointerType *FromPtrTy
9712 = FromTy->getAs<ObjCObjectPointerType>()) {
9713 if (const ObjCObjectPointerType *ToPtrTy
9714 = ToTy->getAs<ObjCObjectPointerType>())
9715 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9716 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9717 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9718 FromPtrTy->getPointeeType()) &&
9719 FromIface->isSuperClassOf(ToIface))
9720 BaseToDerivedConversion = 2;
9721 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9722 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9723 !FromTy->isIncompleteType() &&
9724 !ToRefTy->getPointeeType()->isIncompleteType() &&
9725 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9726 BaseToDerivedConversion = 3;
9727 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9728 ToTy.getNonReferenceType().getCanonicalType() ==
9729 FromTy.getNonReferenceType().getCanonicalType()) {
9730 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9731 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9732 << (unsigned)isObjectArgument << I + 1
9733 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9734 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9735 return;
9736 }
9737 }
9738
9739 if (BaseToDerivedConversion) {
9740 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9741 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9742 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9743 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9744 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9745 return;
9746 }
9747
9748 if (isa<ObjCObjectPointerType>(CFromTy) &&
9749 isa<PointerType>(CToTy)) {
9750 Qualifiers FromQs = CFromTy.getQualifiers();
9751 Qualifiers ToQs = CToTy.getQualifiers();
9752 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9753 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9754 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9755 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9756 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9757 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9758 return;
9759 }
9760 }
9761
9762 if (TakingCandidateAddress &&
9763 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9764 return;
9765
9766 // Emit the generic diagnostic and, optionally, add the hints to it.
9767 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9768 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9769 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9770 << ToTy << (unsigned)isObjectArgument << I + 1
9771 << (unsigned)(Cand->Fix.Kind);
9772
9773 // If we can fix the conversion, suggest the FixIts.
9774 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9775 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9776 FDiag << *HI;
9777 S.Diag(Fn->getLocation(), FDiag);
9778
9779 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9780}
9781
9782/// Additional arity mismatch diagnosis specific to a function overload
9783/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9784/// over a candidate in any candidate set.
9785static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9786 unsigned NumArgs) {
9787 FunctionDecl *Fn = Cand->Function;
9788 unsigned MinParams = Fn->getMinRequiredArguments();
9789
9790 // With invalid overloaded operators, it's possible that we think we
9791 // have an arity mismatch when in fact it looks like we have the
9792 // right number of arguments, because only overloaded operators have
9793 // the weird behavior of overloading member and non-member functions.
9794 // Just don't report anything.
9795 if (Fn->isInvalidDecl() &&
9796 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9797 return true;
9798
9799 if (NumArgs < MinParams) {
9800 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9802, __extension__ __PRETTY_FUNCTION__))
9801 (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9802, __extension__ __PRETTY_FUNCTION__))
9802 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_few_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9802, __extension__ __PRETTY_FUNCTION__))
;
9803 } else {
9804 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9806, __extension__ __PRETTY_FUNCTION__))
9805 (Cand->FailureKind == ovl_fail_bad_deduction &&(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9806, __extension__ __PRETTY_FUNCTION__))
9806 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(static_cast <bool> ((Cand->FailureKind == ovl_fail_too_many_arguments
) || (Cand->FailureKind == ovl_fail_bad_deduction &&
Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments
)) ? void (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9806, __extension__ __PRETTY_FUNCTION__))
;
9807 }
9808
9809 return false;
9810}
9811
9812/// General arity mismatch diagnosis over a candidate in a candidate set.
9813static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9814 unsigned NumFormalArgs) {
9815 assert(isa<FunctionDecl>(D) &&(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9818, __extension__ __PRETTY_FUNCTION__))
9816 "The templated declaration should at least be a function"(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9818, __extension__ __PRETTY_FUNCTION__))
9817 " when diagnosing bad template argument deduction due to too many"(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9818, __extension__ __PRETTY_FUNCTION__))
9818 " or too few arguments")(static_cast <bool> (isa<FunctionDecl>(D) &&
"The templated declaration should at least be a function" " when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? void (0) : __assert_fail ("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9818, __extension__ __PRETTY_FUNCTION__))
;
9819
9820 FunctionDecl *Fn = cast<FunctionDecl>(D);
9821
9822 // TODO: treat calls to a missing default constructor as a special case
9823 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9824 unsigned MinParams = Fn->getMinRequiredArguments();
9825
9826 // at least / at most / exactly
9827 unsigned mode, modeCount;
9828 if (NumFormalArgs < MinParams) {
9829 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9830 FnTy->isTemplateVariadic())
9831 mode = 0; // "at least"
9832 else
9833 mode = 2; // "exactly"
9834 modeCount = MinParams;
9835 } else {
9836 if (MinParams != FnTy->getNumParams())
9837 mode = 1; // "at most"
9838 else
9839 mode = 2; // "exactly"
9840 modeCount = FnTy->getNumParams();
9841 }
9842
9843 std::string Description;
9844 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9845 ClassifyOverloadCandidate(S, Found, Fn, Description);
9846
9847 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9848 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9849 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9850 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9851 else
9852 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9853 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9854 << Description << mode << modeCount << NumFormalArgs;
9855
9856 MaybeEmitInheritedConstructorNote(S, Found);
9857}
9858
9859/// Arity mismatch diagnosis specific to a function overload candidate.
9860static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9861 unsigned NumFormalArgs) {
9862 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9863 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9864}
9865
9866static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9867 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9868 return TD;
9869 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-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9870)
9870 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9870)
;
9871}
9872
9873/// Diagnose a failed template-argument deduction.
9874static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9875 DeductionFailureInfo &DeductionFailure,
9876 unsigned NumArgs,
9877 bool TakingCandidateAddress) {
9878 TemplateParameter Param = DeductionFailure.getTemplateParameter();
9879 NamedDecl *ParamD;
9880 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9881 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9882 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9883 switch (DeductionFailure.Result) {
9884 case Sema::TDK_Success:
9885 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9885)
;
9886
9887 case Sema::TDK_Incomplete: {
9888 assert(ParamD && "no parameter found for incomplete deduction result")(static_cast <bool> (ParamD && "no parameter found for incomplete deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9888, __extension__ __PRETTY_FUNCTION__))
;
9889 S.Diag(Templated->getLocation(),
9890 diag::note_ovl_candidate_incomplete_deduction)
9891 << ParamD->getDeclName();
9892 MaybeEmitInheritedConstructorNote(S, Found);
9893 return;
9894 }
9895
9896 case Sema::TDK_Underqualified: {
9897 assert(ParamD && "no parameter found for bad qualifiers deduction result")(static_cast <bool> (ParamD && "no parameter found for bad qualifiers deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9897, __extension__ __PRETTY_FUNCTION__))
;
9898 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9899
9900 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9901
9902 // Param will have been canonicalized, but it should just be a
9903 // qualified version of ParamD, so move the qualifiers to that.
9904 QualifierCollector Qs;
9905 Qs.strip(Param);
9906 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9907 assert(S.Context.hasSameType(Param, NonCanonParam))(static_cast <bool> (S.Context.hasSameType(Param, NonCanonParam
)) ? void (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9907, __extension__ __PRETTY_FUNCTION__))
;
9908
9909 // Arg has also been canonicalized, but there's nothing we can do
9910 // about that. It also doesn't matter as much, because it won't
9911 // have any template parameters in it (because deduction isn't
9912 // done on dependent types).
9913 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9914
9915 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9916 << ParamD->getDeclName() << Arg << NonCanonParam;
9917 MaybeEmitInheritedConstructorNote(S, Found);
9918 return;
9919 }
9920
9921 case Sema::TDK_Inconsistent: {
9922 assert(ParamD && "no parameter found for inconsistent deduction result")(static_cast <bool> (ParamD && "no parameter found for inconsistent deduction result"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9922, __extension__ __PRETTY_FUNCTION__))
;
9923 int which = 0;
9924 if (isa<TemplateTypeParmDecl>(ParamD))
9925 which = 0;
9926 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9927 // Deduction might have failed because we deduced arguments of two
9928 // different types for a non-type template parameter.
9929 // FIXME: Use a different TDK value for this.
9930 QualType T1 =
9931 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9932 QualType T2 =
9933 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9934 if (!S.Context.hasSameType(T1, T2)) {
9935 S.Diag(Templated->getLocation(),
9936 diag::note_ovl_candidate_inconsistent_deduction_types)
9937 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9938 << *DeductionFailure.getSecondArg() << T2;
9939 MaybeEmitInheritedConstructorNote(S, Found);
9940 return;
9941 }
9942
9943 which = 1;
9944 } else {
9945 which = 2;
9946 }
9947
9948 S.Diag(Templated->getLocation(),
9949 diag::note_ovl_candidate_inconsistent_deduction)
9950 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9951 << *DeductionFailure.getSecondArg();
9952 MaybeEmitInheritedConstructorNote(S, Found);
9953 return;
9954 }
9955
9956 case Sema::TDK_InvalidExplicitArguments:
9957 assert(ParamD && "no parameter found for invalid explicit arguments")(static_cast <bool> (ParamD && "no parameter found for invalid explicit arguments"
) ? void (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 9957, __extension__ __PRETTY_FUNCTION__))
;
9958 if (ParamD->getDeclName())
9959 S.Diag(Templated->getLocation(),
9960 diag::note_ovl_candidate_explicit_arg_mismatch_named)
9961 << ParamD->getDeclName();
9962 else {
9963 int index = 0;
9964 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9965 index = TTP->getIndex();
9966 else if (NonTypeTemplateParmDecl *NTTP
9967 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9968 index = NTTP->getIndex();
9969 else
9970 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9971 S.Diag(Templated->getLocation(),
9972 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9973 << (index + 1);
9974 }
9975 MaybeEmitInheritedConstructorNote(S, Found);
9976 return;
9977
9978 case Sema::TDK_TooManyArguments:
9979 case Sema::TDK_TooFewArguments:
9980 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9981 return;
9982
9983 case Sema::TDK_InstantiationDepth:
9984 S.Diag(Templated->getLocation(),
9985 diag::note_ovl_candidate_instantiation_depth);
9986 MaybeEmitInheritedConstructorNote(S, Found);
9987 return;
9988
9989 case Sema::TDK_SubstitutionFailure: {
9990 // Format the template argument list into the argument string.
9991 SmallString<128> TemplateArgString;
9992 if (TemplateArgumentList *Args =
9993 DeductionFailure.getTemplateArgumentList()) {
9994 TemplateArgString = " ";
9995 TemplateArgString += S.getTemplateArgumentBindingsText(
9996 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9997 }
9998
9999 // If this candidate was disabled by enable_if, say so.
10000 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10001 if (PDiag && PDiag->second.getDiagID() ==
10002 diag::err_typename_nested_not_found_enable_if) {
10003 // FIXME: Use the source range of the condition, and the fully-qualified
10004 // name of the enable_if template. These are both present in PDiag.
10005 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10006 << "'enable_if'" << TemplateArgString;
10007 return;
10008 }
10009
10010 // We found a specific requirement that disabled the enable_if.
10011 if (PDiag && PDiag->second.getDiagID() ==
10012 diag::err_typename_nested_not_found_requirement) {
10013 S.Diag(Templated->getLocation(),
10014 diag::note_ovl_candidate_disabled_by_requirement)
10015 << PDiag->second.getStringArg(0) << TemplateArgString;
10016 return;
10017 }
10018
10019 // Format the SFINAE diagnostic into the argument string.
10020 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10021 // formatted message in another diagnostic.
10022 SmallString<128> SFINAEArgString;
10023 SourceRange R;
10024 if (PDiag) {
10025 SFINAEArgString = ": ";
10026 R = SourceRange(PDiag->first, PDiag->first);
10027 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10028 }
10029
10030 S.Diag(Templated->getLocation(),
10031 diag::note_ovl_candidate_substitution_failure)
10032 << TemplateArgString << SFINAEArgString << R;
10033 MaybeEmitInheritedConstructorNote(S, Found);
10034 return;
10035 }
10036
10037 case Sema::TDK_DeducedMismatch:
10038 case Sema::TDK_DeducedMismatchNested: {
10039 // Format the template argument list into the argument string.
10040 SmallString<128> TemplateArgString;
10041 if (TemplateArgumentList *Args =
10042 DeductionFailure.getTemplateArgumentList()) {
10043 TemplateArgString = " ";
10044 TemplateArgString += S.getTemplateArgumentBindingsText(
10045 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10046 }
10047
10048 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10049 << (*DeductionFailure.getCallArgIndex() + 1)
10050 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10051 << TemplateArgString
10052 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10053 break;
10054 }
10055
10056 case Sema::TDK_NonDeducedMismatch: {
10057 // FIXME: Provide a source location to indicate what we couldn't match.
10058 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10059 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10060 if (FirstTA.getKind() == TemplateArgument::Template &&
10061 SecondTA.getKind() == TemplateArgument::Template) {
10062 TemplateName FirstTN = FirstTA.getAsTemplate();
10063 TemplateName SecondTN = SecondTA.getAsTemplate();
10064 if (FirstTN.getKind() == TemplateName::Template &&
10065 SecondTN.getKind() == TemplateName::Template) {
10066 if (FirstTN.getAsTemplateDecl()->getName() ==
10067 SecondTN.getAsTemplateDecl()->getName()) {
10068 // FIXME: This fixes a bad diagnostic where both templates are named
10069 // the same. This particular case is a bit difficult since:
10070 // 1) It is passed as a string to the diagnostic printer.
10071 // 2) The diagnostic printer only attempts to find a better
10072 // name for types, not decls.
10073 // Ideally, this should folded into the diagnostic printer.
10074 S.Diag(Templated->getLocation(),
10075 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10076 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10077 return;
10078 }
10079 }
10080 }
10081
10082 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10083 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10084 return;
10085
10086 // FIXME: For generic lambda parameters, check if the function is a lambda
10087 // call operator, and if so, emit a prettier and more informative
10088 // diagnostic that mentions 'auto' and lambda in addition to
10089 // (or instead of?) the canonical template type parameters.
10090 S.Diag(Templated->getLocation(),
10091 diag::note_ovl_candidate_non_deduced_mismatch)
10092 << FirstTA << SecondTA;
10093 return;
10094 }
10095 // TODO: diagnose these individually, then kill off
10096 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10097 case Sema::TDK_MiscellaneousDeductionFailure:
10098 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10099 MaybeEmitInheritedConstructorNote(S, Found);
10100 return;
10101 case Sema::TDK_CUDATargetMismatch:
10102 S.Diag(Templated->getLocation(),
10103 diag::note_cuda_ovl_candidate_target_mismatch);
10104 return;
10105 }
10106}
10107
10108/// Diagnose a failed template-argument deduction, for function calls.
10109static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10110 unsigned NumArgs,
10111 bool TakingCandidateAddress) {
10112 unsigned TDK = Cand->DeductionFailure.Result;
10113 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10114 if (CheckArityMismatch(S, Cand, NumArgs))
10115 return;
10116 }
10117 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10118 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10119}
10120
10121/// CUDA: diagnose an invalid call across targets.
10122static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10123 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10124 FunctionDecl *Callee = Cand->Function;
10125
10126 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10127 CalleeTarget = S.IdentifyCUDATarget(Callee);
10128
10129 std::string FnDesc;
10130 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10131 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10132
10133 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10134 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10135 << FnDesc /* Ignored */
10136 << CalleeTarget << CallerTarget;
10137
10138 // This could be an implicit constructor for which we could not infer the
10139 // target due to a collsion. Diagnose that case.
10140 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10141 if (Meth != nullptr && Meth->isImplicit()) {
10142 CXXRecordDecl *ParentClass = Meth->getParent();
10143 Sema::CXXSpecialMember CSM;
10144
10145 switch (FnKindPair.first) {
10146 default:
10147 return;
10148 case oc_implicit_default_constructor:
10149 CSM = Sema::CXXDefaultConstructor;
10150 break;
10151 case oc_implicit_copy_constructor:
10152 CSM = Sema::CXXCopyConstructor;
10153 break;
10154 case oc_implicit_move_constructor:
10155 CSM = Sema::CXXMoveConstructor;
10156 break;
10157 case oc_implicit_copy_assignment:
10158 CSM = Sema::CXXCopyAssignment;
10159 break;
10160 case oc_implicit_move_assignment:
10161 CSM = Sema::CXXMoveAssignment;
10162 break;
10163 };
10164
10165 bool ConstRHS = false;
10166 if (Meth->getNumParams()) {
10167 if (const ReferenceType *RT =
10168 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10169 ConstRHS = RT->getPointeeType().isConstQualified();
10170 }
10171 }
10172
10173 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10174 /* ConstRHS */ ConstRHS,
10175 /* Diagnose */ true);
10176 }
10177}
10178
10179static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10180 FunctionDecl *Callee = Cand->Function;
10181 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10182
10183 S.Diag(Callee->getLocation(),
10184 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10185 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10186}
10187
10188static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10189 FunctionDecl *Callee = Cand->Function;
10190
10191 S.Diag(Callee->getLocation(),
10192 diag::note_ovl_candidate_disabled_by_extension);
10193}
10194
10195/// Generates a 'note' diagnostic for an overload candidate. We've
10196/// already generated a primary error at the call site.
10197///
10198/// It really does need to be a single diagnostic with its caret
10199/// pointed at the candidate declaration. Yes, this creates some
10200/// major challenges of technical writing. Yes, this makes pointing
10201/// out problems with specific arguments quite awkward. It's still
10202/// better than generating twenty screens of text for every failed
10203/// overload.
10204///
10205/// It would be great to be able to express per-candidate problems
10206/// more richly for those diagnostic clients that cared, but we'd
10207/// still have to be just as careful with the default diagnostics.
10208static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10209 unsigned NumArgs,
10210 bool TakingCandidateAddress) {
10211 FunctionDecl *Fn = Cand->Function;
10212
10213 // Note deleted candidates, but only if they're viable.
10214 if (Cand->Viable) {
10215 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10216 std::string FnDesc;
10217 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10218 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10219
10220 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10221 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10222 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10223 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10224 return;
10225 }
10226
10227 // We don't really have anything else to say about viable candidates.
10228 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10229 return;
10230 }
10231
10232 switch (Cand->FailureKind) {
10233 case ovl_fail_too_many_arguments:
10234 case ovl_fail_too_few_arguments:
10235 return DiagnoseArityMismatch(S, Cand, NumArgs);
10236
10237 case ovl_fail_bad_deduction:
10238 return DiagnoseBadDeduction(S, Cand, NumArgs,
10239 TakingCandidateAddress);
10240
10241 case ovl_fail_illegal_constructor: {
10242 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10243 << (Fn->getPrimaryTemplate() ? 1 : 0);
10244 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10245 return;
10246 }
10247
10248 case ovl_fail_trivial_conversion:
10249 case ovl_fail_bad_final_conversion:
10250 case ovl_fail_final_conversion_not_exact:
10251 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10252
10253 case ovl_fail_bad_conversion: {
10254 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10255 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10256 if (Cand->Conversions[I].isBad())
10257 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10258
10259 // FIXME: this currently happens when we're called from SemaInit
10260 // when user-conversion overload fails. Figure out how to handle
10261 // those conditions and diagnose them well.
10262 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10263 }
10264
10265 case ovl_fail_bad_target:
10266 return DiagnoseBadTarget(S, Cand);
10267
10268 case ovl_fail_enable_if:
10269 return DiagnoseFailedEnableIfAttr(S, Cand);
10270
10271 case ovl_fail_ext_disabled:
10272 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10273
10274 case ovl_fail_inhctor_slice:
10275 // It's generally not interesting to note copy/move constructors here.
10276 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10277 return;
10278 S.Diag(Fn->getLocation(),
10279 diag::note_ovl_candidate_inherited_constructor_slice)
10280 << (Fn->getPrimaryTemplate() ? 1 : 0)
10281 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10282 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10283 return;
10284
10285 case ovl_fail_addr_not_available: {
10286 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10287 (void)Available;
10288 assert(!Available)(static_cast <bool> (!Available) ? void (0) : __assert_fail
("!Available", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10288, __extension__ __PRETTY_FUNCTION__))
;
10289 break;
10290 }
10291 case ovl_non_default_multiversion_function:
10292 // Do nothing, these should simply be ignored.
10293 break;
10294 }
10295}
10296
10297static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10298 // Desugar the type of the surrogate down to a function type,
10299 // retaining as many typedefs as possible while still showing
10300 // the function type (and, therefore, its parameter types).
10301 QualType FnType = Cand->Surrogate->getConversionType();
10302 bool isLValueReference = false;
10303 bool isRValueReference = false;
10304 bool isPointer = false;
10305 if (const LValueReferenceType *FnTypeRef =
10306 FnType->getAs<LValueReferenceType>()) {
10307 FnType = FnTypeRef->getPointeeType();
10308 isLValueReference = true;
10309 } else if (const RValueReferenceType *FnTypeRef =
10310 FnType->getAs<RValueReferenceType>()) {
10311 FnType = FnTypeRef->getPointeeType();
10312 isRValueReference = true;
10313 }
10314 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10315 FnType = FnTypePtr->getPointeeType();
10316 isPointer = true;
10317 }
10318 // Desugar down to a function type.
10319 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10320 // Reconstruct the pointer/reference as appropriate.
10321 if (isPointer) FnType = S.Context.getPointerType(FnType);
10322 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10323 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10324
10325 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10326 << FnType;
10327}
10328
10329static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10330 SourceLocation OpLoc,
10331 OverloadCandidate *Cand) {
10332 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary")(static_cast <bool> (Cand->Conversions.size() <= 2
&& "builtin operator is not binary") ? void (0) : __assert_fail
("Cand->Conversions.size() <= 2 && \"builtin operator is not binary\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10332, __extension__ __PRETTY_FUNCTION__))
;
10333 std::string TypeStr("operator");
10334 TypeStr += Opc;
10335 TypeStr += "(";
10336 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10337 if (Cand->Conversions.size() == 1) {
10338 TypeStr += ")";
10339 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10340 } else {
10341 TypeStr += ", ";
10342 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10343 TypeStr += ")";
10344 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10345 }
10346}
10347
10348static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10349 OverloadCandidate *Cand) {
10350 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10351 if (ICS.isBad()) break; // all meaningless after first invalid
10352 if (!ICS.isAmbiguous()) continue;
10353
10354 ICS.DiagnoseAmbiguousConversion(
10355 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10356 }
10357}
10358
10359static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10360 if (Cand->Function)
10361 return Cand->Function->getLocation();
10362 if (Cand->IsSurrogate)
10363 return Cand->Surrogate->getLocation();
10364 return SourceLocation();
10365}
10366
10367static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10368 switch ((Sema::TemplateDeductionResult)DFI.Result) {
10369 case Sema::TDK_Success:
10370 case Sema::TDK_NonDependentConversionFailure:
10371 llvm_unreachable("non-deduction failure while diagnosing bad deduction")::llvm::llvm_unreachable_internal("non-deduction failure while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10371)
;
10372
10373 case Sema::TDK_Invalid:
10374 case Sema::TDK_Incomplete:
10375 return 1;
10376
10377 case Sema::TDK_Underqualified:
10378 case Sema::TDK_Inconsistent:
10379 return 2;
10380
10381 case Sema::TDK_SubstitutionFailure:
10382 case Sema::TDK_DeducedMismatch:
10383 case Sema::TDK_DeducedMismatchNested:
10384 case Sema::TDK_NonDeducedMismatch:
10385 case Sema::TDK_MiscellaneousDeductionFailure:
10386 case Sema::TDK_CUDATargetMismatch:
10387 return 3;
10388
10389 case Sema::TDK_InstantiationDepth:
10390 return 4;
10391
10392 case Sema::TDK_InvalidExplicitArguments:
10393 return 5;
10394
10395 case Sema::TDK_TooManyArguments:
10396 case Sema::TDK_TooFewArguments:
10397 return 6;
10398 }
10399 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10399)
;
10400}
10401
10402namespace {
10403struct CompareOverloadCandidatesForDisplay {
10404 Sema &S;
10405 SourceLocation Loc;
10406 size_t NumArgs;
10407 OverloadCandidateSet::CandidateSetKind CSK;
10408
10409 CompareOverloadCandidatesForDisplay(
10410 Sema &S, SourceLocation Loc, size_t NArgs,
10411 OverloadCandidateSet::CandidateSetKind CSK)
10412 : S(S), NumArgs(NArgs), CSK(CSK) {}
10413
10414 bool operator()(const OverloadCandidate *L,
10415 const OverloadCandidate *R) {
10416 // Fast-path this check.
10417 if (L == R) return false;
10418
10419 // Order first by viability.
10420 if (L->Viable) {
10421 if (!R->Viable) return true;
10422
10423 // TODO: introduce a tri-valued comparison for overload
10424 // candidates. Would be more worthwhile if we had a sort
10425 // that could exploit it.
10426 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10427 return true;
10428 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10429 return false;
10430 } else if (R->Viable)
10431 return false;
10432
10433 assert(L->Viable == R->Viable)(static_cast <bool> (L->Viable == R->Viable) ? void
(0) : __assert_fail ("L->Viable == R->Viable", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10433, __extension__ __PRETTY_FUNCTION__))
;
10434
10435 // Criteria by which we can sort non-viable candidates:
10436 if (!L->Viable) {
10437 // 1. Arity mismatches come after other candidates.
10438 if (L->FailureKind == ovl_fail_too_many_arguments ||
10439 L->FailureKind == ovl_fail_too_few_arguments) {
10440 if (R->FailureKind == ovl_fail_too_many_arguments ||
10441 R->FailureKind == ovl_fail_too_few_arguments) {
10442 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10443 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10444 if (LDist == RDist) {
10445 if (L->FailureKind == R->FailureKind)
10446 // Sort non-surrogates before surrogates.
10447 return !L->IsSurrogate && R->IsSurrogate;
10448 // Sort candidates requiring fewer parameters than there were
10449 // arguments given after candidates requiring more parameters
10450 // than there were arguments given.
10451 return L->FailureKind == ovl_fail_too_many_arguments;
10452 }
10453 return LDist < RDist;
10454 }
10455 return false;
10456 }
10457 if (R->FailureKind == ovl_fail_too_many_arguments ||
10458 R->FailureKind == ovl_fail_too_few_arguments)
10459 return true;
10460
10461 // 2. Bad conversions come first and are ordered by the number
10462 // of bad conversions and quality of good conversions.
10463 if (L->FailureKind == ovl_fail_bad_conversion) {
10464 if (R->FailureKind != ovl_fail_bad_conversion)
10465 return true;
10466
10467 // The conversion that can be fixed with a smaller number of changes,
10468 // comes first.
10469 unsigned numLFixes = L->Fix.NumConversionsFixed;
10470 unsigned numRFixes = R->Fix.NumConversionsFixed;
10471 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes;
10472 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes;
10473 if (numLFixes != numRFixes) {
10474 return numLFixes < numRFixes;
10475 }
10476
10477 // If there's any ordering between the defined conversions...
10478 // FIXME: this might not be transitive.
10479 assert(L->Conversions.size() == R->Conversions.size())(static_cast <bool> (L->Conversions.size() == R->
Conversions.size()) ? void (0) : __assert_fail ("L->Conversions.size() == R->Conversions.size()"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10479, __extension__ __PRETTY_FUNCTION__))
;
10480
10481 int leftBetter = 0;
10482 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10483 for (unsigned E = L->Conversions.size(); I != E; ++I) {
10484 switch (CompareImplicitConversionSequences(S, Loc,
10485 L->Conversions[I],
10486 R->Conversions[I])) {
10487 case ImplicitConversionSequence::Better:
10488 leftBetter++;
10489 break;
10490
10491 case ImplicitConversionSequence::Worse:
10492 leftBetter--;
10493 break;
10494
10495 case ImplicitConversionSequence::Indistinguishable:
10496 break;
10497 }
10498 }
10499 if (leftBetter > 0) return true;
10500 if (leftBetter < 0) return false;
10501
10502 } else if (R->FailureKind == ovl_fail_bad_conversion)
10503 return false;
10504
10505 if (L->FailureKind == ovl_fail_bad_deduction) {
10506 if (R->FailureKind != ovl_fail_bad_deduction)
10507 return true;
10508
10509 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10510 return RankDeductionFailure(L->DeductionFailure)
10511 < RankDeductionFailure(R->DeductionFailure);
10512 } else if (R->FailureKind == ovl_fail_bad_deduction)
10513 return false;
10514
10515 // TODO: others?
10516 }
10517
10518 // Sort everything else by location.
10519 SourceLocation LLoc = GetLocationForCandidate(L);
10520 SourceLocation RLoc = GetLocationForCandidate(R);
10521
10522 // Put candidates without locations (e.g. builtins) at the end.
10523 if (LLoc.isInvalid()) return false;
10524 if (RLoc.isInvalid()) return true;
10525
10526 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10527 }
10528};
10529}
10530
10531/// CompleteNonViableCandidate - Normally, overload resolution only
10532/// computes up to the first bad conversion. Produces the FixIt set if
10533/// possible.
10534static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10535 ArrayRef<Expr *> Args) {
10536 assert(!Cand->Viable)(static_cast <bool> (!Cand->Viable) ? void (0) : __assert_fail
("!Cand->Viable", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10536, __extension__ __PRETTY_FUNCTION__))
;
10537
10538 // Don't do anything on failures other than bad conversion.
10539 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10540
10541 // We only want the FixIts if all the arguments can be corrected.
10542 bool Unfixable = false;
10543 // Use a implicit copy initialization to check conversion fixes.
10544 Cand->Fix.setConversionChecker(TryCopyInitialization);
10545
10546 // Attempt to fix the bad conversion.
10547 unsigned ConvCount = Cand->Conversions.size();
10548 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10549 ++ConvIdx) {
10550 assert(ConvIdx != ConvCount && "no bad conversion in candidate")(static_cast <bool> (ConvIdx != ConvCount && "no bad conversion in candidate"
) ? void (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10550, __extension__ __PRETTY_FUNCTION__))
;
10551 if (Cand->Conversions[ConvIdx].isInitialized() &&
10552 Cand->Conversions[ConvIdx].isBad()) {
10553 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10554 break;
10555 }
10556 }
10557
10558 // FIXME: this should probably be preserved from the overload
10559 // operation somehow.
10560 bool SuppressUserConversions = false;
10561
10562 unsigned ConvIdx = 0;
10563 ArrayRef<QualType> ParamTypes;
10564
10565 if (Cand->IsSurrogate) {
10566 QualType ConvType
10567 = Cand->Surrogate->getConversionType().getNonReferenceType();
10568 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10569 ConvType = ConvPtrType->getPointeeType();
10570 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10571 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10572 ConvIdx = 1;
10573 } else if (Cand->Function) {
10574 ParamTypes =
10575 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10576 if (isa<CXXMethodDecl>(Cand->Function) &&
10577 !isa<CXXConstructorDecl>(Cand->Function)) {
10578 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10579 ConvIdx = 1;
10580 }
10581 } else {
10582 // Builtin operator.
10583 assert(ConvCount <= 3)(static_cast <bool> (ConvCount <= 3) ? void (0) : __assert_fail
("ConvCount <= 3", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10583, __extension__ __PRETTY_FUNCTION__))
;
10584 ParamTypes = Cand->BuiltinParamTypes;
10585 }
10586
10587 // Fill in the rest of the conversions.
10588 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10589 if (Cand->Conversions[ConvIdx].isInitialized()) {
10590 // We've already checked this conversion.
10591 } else if (ArgIdx < ParamTypes.size()) {
10592 if (ParamTypes[ArgIdx]->isDependentType())
10593 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10594 Args[ArgIdx]->getType());
10595 else {
10596 Cand->Conversions[ConvIdx] =
10597 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10598 SuppressUserConversions,
10599 /*InOverloadResolution=*/true,
10600 /*AllowObjCWritebackConversion=*/
10601 S.getLangOpts().ObjCAutoRefCount);
10602 // Store the FixIt in the candidate if it exists.
10603 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10604 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10605 }
10606 } else
10607 Cand->Conversions[ConvIdx].setEllipsis();
10608 }
10609}
10610
10611/// When overload resolution fails, prints diagnostic messages containing the
10612/// candidates in the candidate set.
10613void OverloadCandidateSet::NoteCandidates(
10614 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10615 StringRef Opc, SourceLocation OpLoc,
10616 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10617 // Sort the candidates by viability and position. Sorting directly would
10618 // be prohibitive, so we make a set of pointers and sort those.
10619 SmallVector<OverloadCandidate*, 32> Cands;
10620 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10621 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10622 if (!Filter(*Cand))
10623 continue;
10624 if (Cand->Viable)
10625 Cands.push_back(Cand);
10626 else if (OCD == OCD_AllCandidates) {
10627 CompleteNonViableCandidate(S, Cand, Args);
10628 if (Cand->Function || Cand->IsSurrogate)
10629 Cands.push_back(Cand);
10630 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10631 // want to list every possible builtin candidate.
10632 }
10633 }
10634
10635 std::stable_sort(Cands.begin(), Cands.end(),
10636 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10637
10638 bool ReportedAmbiguousConversions = false;
10639
10640 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10641 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10642 unsigned CandsShown = 0;
10643 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10644 OverloadCandidate *Cand = *I;
10645
10646 // Set an arbitrary limit on the number of candidate functions we'll spam
10647 // the user with. FIXME: This limit should depend on details of the
10648 // candidate list.
10649 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10650 break;
10651 }
10652 ++CandsShown;
10653
10654 if (Cand->Function)
10655 NoteFunctionCandidate(S, Cand, Args.size(),
10656 /*TakingCandidateAddress=*/false);
10657 else if (Cand->IsSurrogate)
10658 NoteSurrogateCandidate(S, Cand);
10659 else {
10660 assert(Cand->Viable &&(static_cast <bool> (Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? void (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10661, __extension__ __PRETTY_FUNCTION__))
10661 "Non-viable built-in candidates are not added to Cands.")(static_cast <bool> (Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? void (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10661, __extension__ __PRETTY_FUNCTION__))
;
10662 // Generally we only see ambiguities including viable builtin
10663 // operators if overload resolution got screwed up by an
10664 // ambiguous user-defined conversion.
10665 //
10666 // FIXME: It's quite possible for different conversions to see
10667 // different ambiguities, though.
10668 if (!ReportedAmbiguousConversions) {
10669 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10670 ReportedAmbiguousConversions = true;
10671 }
10672
10673 // If this is a viable builtin, print it.
10674 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10675 }
10676 }
10677
10678 if (I != E)
10679 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10680}
10681
10682static SourceLocation
10683GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10684 return Cand->Specialization ? Cand->Specialization->getLocation()
10685 : SourceLocation();
10686}
10687
10688namespace {
10689struct CompareTemplateSpecCandidatesForDisplay {
10690 Sema &S;
10691 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10692
10693 bool operator()(const TemplateSpecCandidate *L,
10694 const TemplateSpecCandidate *R) {
10695 // Fast-path this check.
10696 if (L == R)
10697 return false;
10698
10699 // Assuming that both candidates are not matches...
10700
10701 // Sort by the ranking of deduction failures.
10702 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10703 return RankDeductionFailure(L->DeductionFailure) <
10704 RankDeductionFailure(R->DeductionFailure);
10705
10706 // Sort everything else by location.
10707 SourceLocation LLoc = GetLocationForCandidate(L);
10708 SourceLocation RLoc = GetLocationForCandidate(R);
10709
10710 // Put candidates without locations (e.g. builtins) at the end.
10711 if (LLoc.isInvalid())
10712 return false;
10713 if (RLoc.isInvalid())
10714 return true;
10715
10716 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10717 }
10718};
10719}
10720
10721/// Diagnose a template argument deduction failure.
10722/// We are treating these failures as overload failures due to bad
10723/// deductions.
10724void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10725 bool ForTakingAddress) {
10726 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10727 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10728}
10729
10730void TemplateSpecCandidateSet::destroyCandidates() {
10731 for (iterator i = begin(), e = end(); i != e; ++i) {
10732 i->DeductionFailure.Destroy();
10733 }
10734}
10735
10736void TemplateSpecCandidateSet::clear() {
10737 destroyCandidates();
10738 Candidates.clear();
10739}
10740
10741/// NoteCandidates - When no template specialization match is found, prints
10742/// diagnostic messages containing the non-matching specializations that form
10743/// the candidate set.
10744/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10745/// OCD == OCD_AllCandidates and Cand->Viable == false.
10746void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10747 // Sort the candidates by position (assuming no candidate is a match).
10748 // Sorting directly would be prohibitive, so we make a set of pointers
10749 // and sort those.
10750 SmallVector<TemplateSpecCandidate *, 32> Cands;
10751 Cands.reserve(size());
10752 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10753 if (Cand->Specialization)
10754 Cands.push_back(Cand);
10755 // Otherwise, this is a non-matching builtin candidate. We do not,
10756 // in general, want to list every possible builtin candidate.
10757 }
10758
10759 llvm::sort(Cands.begin(), Cands.end(),
10760 CompareTemplateSpecCandidatesForDisplay(S));
10761
10762 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10763 // for generalization purposes (?).
10764 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10765
10766 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10767 unsigned CandsShown = 0;
10768 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10769 TemplateSpecCandidate *Cand = *I;
10770
10771 // Set an arbitrary limit on the number of candidates we'll spam
10772 // the user with. FIXME: This limit should depend on details of the
10773 // candidate list.
10774 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10775 break;
10776 ++CandsShown;
10777
10778 assert(Cand->Specialization &&(static_cast <bool> (Cand->Specialization &&
"Non-matching built-in candidates are not added to Cands.") ?
void (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10779, __extension__ __PRETTY_FUNCTION__))
10779 "Non-matching built-in candidates are not added to Cands.")(static_cast <bool> (Cand->Specialization &&
"Non-matching built-in candidates are not added to Cands.") ?
void (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 10779, __extension__ __PRETTY_FUNCTION__))
;
10780 Cand->NoteDeductionFailure(S, ForTakingAddress);
10781 }
10782
10783 if (I != E)
10784 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10785}
10786
10787// [PossiblyAFunctionType] --> [Return]
10788// NonFunctionType --> NonFunctionType
10789// R (A) --> R(A)
10790// R (*)(A) --> R (A)
10791// R (&)(A) --> R (A)
10792// R (S::*)(A) --> R (A)
10793QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10794 QualType Ret = PossiblyAFunctionType;
10795 if (const PointerType *ToTypePtr =
10796 PossiblyAFunctionType->getAs<PointerType>())
10797 Ret = ToTypePtr->getPointeeType();
10798 else if (const ReferenceType *ToTypeRef =
10799 PossiblyAFunctionType->getAs<ReferenceType>())
10800 Ret = ToTypeRef->getPointeeType();
10801 else if (const MemberPointerType *MemTypePtr =
10802 PossiblyAFunctionType->getAs<MemberPointerType>())
10803 Ret = MemTypePtr->getPointeeType();
10804 Ret =
10805 Context.getCanonicalType(Ret).getUnqualifiedType();
10806 return Ret;
10807}
10808
10809static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10810 bool Complain = true) {
10811 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10812 S.DeduceReturnType(FD, Loc, Complain))
10813 return true;
10814
10815 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10816 if (S.getLangOpts().CPlusPlus17 &&
10817 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10818 !S.ResolveExceptionSpec(Loc, FPT))
10819 return true;
10820
10821 return false;
10822}
10823
10824namespace {
10825// A helper class to help with address of function resolution
10826// - allows us to avoid passing around all those ugly parameters
10827class AddressOfFunctionResolver {
10828 Sema& S;
10829 Expr* SourceExpr;
10830 const QualType& TargetType;
10831 QualType TargetFunctionType; // Extracted function type from target type
10832
10833 bool Complain;
10834 //DeclAccessPair& ResultFunctionAccessPair;
10835 ASTContext& Context;
10836
10837 bool TargetTypeIsNonStaticMemberFunction;
10838 bool FoundNonTemplateFunction;
10839 bool StaticMemberFunctionFromBoundPointer;
10840 bool HasComplained;
10841
10842 OverloadExpr::FindResult OvlExprInfo;
10843 OverloadExpr *OvlExpr;
10844 TemplateArgumentListInfo OvlExplicitTemplateArgs;
10845 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10846 TemplateSpecCandidateSet FailedCandidates;
10847
10848public:
10849 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10850 const QualType &TargetType, bool Complain)
10851 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10852 Complain(Complain), Context(S.getASTContext()),
10853 TargetTypeIsNonStaticMemberFunction(
10854 !!TargetType->getAs<MemberPointerType>()),
10855 FoundNonTemplateFunction(false),
10856 StaticMemberFunctionFromBoundPointer(false),
10857 HasComplained(false),
10858 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10859 OvlExpr(OvlExprInfo.Expression),
10860 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10861 ExtractUnqualifiedFunctionTypeFromTargetType();
10862
10863 if (TargetFunctionType->isFunctionType()) {
10864 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10865 if (!UME->isImplicitAccess() &&
10866 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10867 StaticMemberFunctionFromBoundPointer = true;
10868 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10869 DeclAccessPair dap;
10870 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10871 OvlExpr, false, &dap)) {
10872 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10873 if (!Method->isStatic()) {
10874 // If the target type is a non-function type and the function found
10875 // is a non-static member function, pretend as if that was the
10876 // target, it's the only possible type to end up with.
10877 TargetTypeIsNonStaticMemberFunction = true;
10878
10879 // And skip adding the function if its not in the proper form.
10880 // We'll diagnose this due to an empty set of functions.
10881 if (!OvlExprInfo.HasFormOfMemberPointer)
10882 return;
10883 }
10884
10885 Matches.push_back(std::make_pair(dap, Fn));
10886 }
10887 return;
10888 }
10889
10890 if (OvlExpr->hasExplicitTemplateArgs())
10891 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10892
10893 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10894 // C++ [over.over]p4:
10895 // If more than one function is selected, [...]
10896 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10897 if (FoundNonTemplateFunction)
10898 EliminateAllTemplateMatches();
10899 else
10900 EliminateAllExceptMostSpecializedTemplate();
10901 }
10902 }
10903
10904 if (S.getLangOpts().CUDA && Matches.size() > 1)
10905 EliminateSuboptimalCudaMatches();
10906 }
10907
10908 bool hasComplained() const { return HasComplained; }
10909
10910private:
10911 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10912 QualType Discard;
10913 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10914 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10915 }
10916
10917 /// \return true if A is considered a better overload candidate for the
10918 /// desired type than B.
10919 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10920 // If A doesn't have exactly the correct type, we don't want to classify it
10921 // as "better" than anything else. This way, the user is required to
10922 // disambiguate for us if there are multiple candidates and no exact match.
10923 return candidateHasExactlyCorrectType(A) &&
10924 (!candidateHasExactlyCorrectType(B) ||
10925 compareEnableIfAttrs(S, A, B) == Comparison::Better);
10926 }
10927
10928 /// \return true if we were able to eliminate all but one overload candidate,
10929 /// false otherwise.
10930 bool eliminiateSuboptimalOverloadCandidates() {
10931 // Same algorithm as overload resolution -- one pass to pick the "best",
10932 // another pass to be sure that nothing is better than the best.
10933 auto Best = Matches.begin();
10934 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10935 if (isBetterCandidate(I->second, Best->second))
10936 Best = I;
10937
10938 const FunctionDecl *BestFn = Best->second;
10939 auto IsBestOrInferiorToBest = [this, BestFn](
10940 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10941 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10942 };
10943
10944 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10945 // option, so we can potentially give the user a better error
10946 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10947 return false;
10948 Matches[0] = *Best;
10949 Matches.resize(1);
10950 return true;
10951 }
10952
10953 bool isTargetTypeAFunction() const {
10954 return TargetFunctionType->isFunctionType();
10955 }
10956
10957 // [ToType] [Return]
10958
10959 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10960 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10961 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10962 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10963 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10964 }
10965
10966 // return true if any matching specializations were found
10967 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10968 const DeclAccessPair& CurAccessFunPair) {
10969 if (CXXMethodDecl *Method
10970 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10971 // Skip non-static function templates when converting to pointer, and
10972 // static when converting to member pointer.
10973 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10974 return false;
10975 }
10976 else if (TargetTypeIsNonStaticMemberFunction)
10977 return false;
10978
10979 // C++ [over.over]p2:
10980 // If the name is a function template, template argument deduction is
10981 // done (14.8.2.2), and if the argument deduction succeeds, the
10982 // resulting template argument list is used to generate a single
10983 // function template specialization, which is added to the set of
10984 // overloaded functions considered.
10985 FunctionDecl *Specialization = nullptr;
10986 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10987 if (Sema::TemplateDeductionResult Result
10988 = S.DeduceTemplateArguments(FunctionTemplate,
10989 &OvlExplicitTemplateArgs,
10990 TargetFunctionType, Specialization,
10991 Info, /*IsAddressOfFunction*/true)) {
10992 // Make a note of the failed deduction for diagnostics.
10993 FailedCandidates.addCandidate()
10994 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10995 MakeDeductionFailureInfo(Context, Result, Info));
10996 return false;
10997 }
10998
10999 // Template argument deduction ensures that we have an exact match or
11000 // compatible pointer-to-function arguments that would be adjusted by ICS.
11001 // This function template specicalization works.
11002 assert(S.isSameOrCompatibleFunctionType((static_cast <bool> (S.isSameOrCompatibleFunctionType( Context
.getCanonicalType(Specialization->getType()), Context.getCanonicalType
(TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11004, __extension__ __PRETTY_FUNCTION__))
11003 Context.getCanonicalType(Specialization->getType()),(static_cast <bool> (S.isSameOrCompatibleFunctionType( Context
.getCanonicalType(Specialization->getType()), Context.getCanonicalType
(TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11004, __extension__ __PRETTY_FUNCTION__))
11004 Context.getCanonicalType(TargetFunctionType)))(static_cast <bool> (S.isSameOrCompatibleFunctionType( Context
.getCanonicalType(Specialization->getType()), Context.getCanonicalType
(TargetFunctionType))) ? void (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11004, __extension__ __PRETTY_FUNCTION__))
;
11005
11006 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11007 return false;
11008
11009 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11010 return true;
11011 }
11012
11013 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11014 const DeclAccessPair& CurAccessFunPair) {
11015 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11016 // Skip non-static functions when converting to pointer, and static
11017 // when converting to member pointer.
11018 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11019 return false;
11020 }
11021 else if (TargetTypeIsNonStaticMemberFunction)
11022 return false;
11023
11024 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11025 if (S.getLangOpts().CUDA)
11026 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11027 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11028 return false;
11029 if (FunDecl->isMultiVersion()) {
11030 const auto *TA = FunDecl->getAttr<TargetAttr>();
11031 assert(TA && "Multiversioned functions require a target attribute")(static_cast <bool> (TA && "Multiversioned functions require a target attribute"
) ? void (0) : __assert_fail ("TA && \"Multiversioned functions require a target attribute\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11031, __extension__ __PRETTY_FUNCTION__))
;
11032 if (!TA->isDefaultVersion())
11033 return false;
11034 }
11035
11036 // If any candidate has a placeholder return type, trigger its deduction
11037 // now.
11038 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
11039 Complain)) {
11040 HasComplained |= Complain;
11041 return false;
11042 }
11043
11044 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11045 return false;
11046
11047 // If we're in C, we need to support types that aren't exactly identical.
11048 if (!S.getLangOpts().CPlusPlus ||
11049 candidateHasExactlyCorrectType(FunDecl)) {
11050 Matches.push_back(std::make_pair(
11051 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11052 FoundNonTemplateFunction = true;
11053 return true;
11054 }
11055 }
11056
11057 return false;
11058 }
11059
11060 bool FindAllFunctionsThatMatchTargetTypeExactly() {
11061 bool Ret = false;
11062
11063 // If the overload expression doesn't have the form of a pointer to
11064 // member, don't try to convert it to a pointer-to-member type.
11065 if (IsInvalidFormOfPointerToMemberFunction())
11066 return false;
11067
11068 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11069 E = OvlExpr->decls_end();
11070 I != E; ++I) {
11071 // Look through any using declarations to find the underlying function.
11072 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11073
11074 // C++ [over.over]p3:
11075 // Non-member functions and static member functions match
11076 // targets of type "pointer-to-function" or "reference-to-function."
11077 // Nonstatic member functions match targets of
11078 // type "pointer-to-member-function."
11079 // Note that according to DR 247, the containing class does not matter.
11080 if (FunctionTemplateDecl *FunctionTemplate
11081 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11082 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11083 Ret = true;
11084 }
11085 // If we have explicit template arguments supplied, skip non-templates.
11086 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11087 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11088 Ret = true;
11089 }
11090 assert(Ret || Matches.empty())(static_cast <bool> (Ret || Matches.empty()) ? void (0)
: __assert_fail ("Ret || Matches.empty()", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11090, __extension__ __PRETTY_FUNCTION__))
;
11091 return Ret;
11092 }
11093
11094 void EliminateAllExceptMostSpecializedTemplate() {
11095 // [...] and any given function template specialization F1 is
11096 // eliminated if the set contains a second function template
11097 // specialization whose function template is more specialized
11098 // than the function template of F1 according to the partial
11099 // ordering rules of 14.5.5.2.
11100
11101 // The algorithm specified above is quadratic. We instead use a
11102 // two-pass algorithm (similar to the one used to identify the
11103 // best viable function in an overload set) that identifies the
11104 // best function template (if it exists).
11105
11106 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11107 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11108 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11109
11110 // TODO: It looks like FailedCandidates does not serve much purpose
11111 // here, since the no_viable diagnostic has index 0.
11112 UnresolvedSetIterator Result = S.getMostSpecialized(
11113 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11114 SourceExpr->getLocStart(), S.PDiag(),
11115 S.PDiag(diag::err_addr_ovl_ambiguous)
11116 << Matches[0].second->getDeclName(),
11117 S.PDiag(diag::note_ovl_candidate)
11118 << (unsigned)oc_function << (unsigned)ocs_described_template,
11119 Complain, TargetFunctionType);
11120
11121 if (Result != MatchesCopy.end()) {
11122 // Make it the first and only element
11123 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11124 Matches[0].second = cast<FunctionDecl>(*Result);
11125 Matches.resize(1);
11126 } else
11127 HasComplained |= Complain;
11128 }
11129
11130 void EliminateAllTemplateMatches() {
11131 // [...] any function template specializations in the set are
11132 // eliminated if the set also contains a non-template function, [...]
11133 for (unsigned I = 0, N = Matches.size(); I != N; ) {
11134 if (Matches[I].second->getPrimaryTemplate() == nullptr)
11135 ++I;
11136 else {
11137 Matches[I] = Matches[--N];
11138 Matches.resize(N);
11139 }
11140 }
11141 }
11142
11143 void EliminateSuboptimalCudaMatches() {
11144 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11145 }
11146
11147public:
11148 void ComplainNoMatchesFound() const {
11149 assert(Matches.empty())(static_cast <bool> (Matches.empty()) ? void (0) : __assert_fail
("Matches.empty()", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11149, __extension__ __PRETTY_FUNCTION__))
;
11150 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11151 << OvlExpr->getName() << TargetFunctionType
11152 << OvlExpr->getSourceRange();
11153 if (FailedCandidates.empty())
11154 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11155 /*TakingAddress=*/true);
11156 else {
11157 // We have some deduction failure messages. Use them to diagnose
11158 // the function templates, and diagnose the non-template candidates
11159 // normally.
11160 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11161 IEnd = OvlExpr->decls_end();
11162 I != IEnd; ++I)
11163 if (FunctionDecl *Fun =
11164 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11165 if (!functionHasPassObjectSizeParams(Fun))
11166 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11167 /*TakingAddress=*/true);
11168 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11169 }
11170 }
11171
11172 bool IsInvalidFormOfPointerToMemberFunction() const {
11173 return TargetTypeIsNonStaticMemberFunction &&
11174 !OvlExprInfo.HasFormOfMemberPointer;
11175 }
11176
11177 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11178 // TODO: Should we condition this on whether any functions might
11179 // have matched, or is it more appropriate to do that in callers?
11180 // TODO: a fixit wouldn't hurt.
11181 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11182 << TargetType << OvlExpr->getSourceRange();
11183 }
11184
11185 bool IsStaticMemberFunctionFromBoundPointer() const {
11186 return StaticMemberFunctionFromBoundPointer;
11187 }
11188
11189 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11190 S.Diag(OvlExpr->getLocStart(),
11191 diag::err_invalid_form_pointer_member_function)
11192 << OvlExpr->getSourceRange();
11193 }
11194
11195 void ComplainOfInvalidConversion() const {
11196 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11197 << OvlExpr->getName() << TargetType;
11198 }
11199
11200 void ComplainMultipleMatchesFound() const {
11201 assert(Matches.size() > 1)(static_cast <bool> (Matches.size() > 1) ? void (0) :
__assert_fail ("Matches.size() > 1", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11201, __extension__ __PRETTY_FUNCTION__))
;
11202 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11203 << OvlExpr->getName()
11204 << OvlExpr->getSourceRange();
11205 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11206 /*TakingAddress=*/true);
11207 }
11208
11209 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11210
11211 int getNumMatches() const { return Matches.size(); }
11212
11213 FunctionDecl* getMatchingFunctionDecl() const {
11214 if (Matches.size() != 1) return nullptr;
11215 return Matches[0].second;
11216 }
11217
11218 const DeclAccessPair* getMatchingFunctionAccessPair() const {
11219 if (Matches.size() != 1) return nullptr;
11220 return &Matches[0].first;
11221 }
11222};
11223}
11224
11225/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11226/// an overloaded function (C++ [over.over]), where @p From is an
11227/// expression with overloaded function type and @p ToType is the type
11228/// we're trying to resolve to. For example:
11229///
11230/// @code
11231/// int f(double);
11232/// int f(int);
11233///
11234/// int (*pfd)(double) = f; // selects f(double)
11235/// @endcode
11236///
11237/// This routine returns the resulting FunctionDecl if it could be
11238/// resolved, and NULL otherwise. When @p Complain is true, this
11239/// routine will emit diagnostics if there is an error.
11240FunctionDecl *
11241Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11242 QualType TargetType,
11243 bool Complain,
11244 DeclAccessPair &FoundResult,
11245 bool *pHadMultipleCandidates) {
11246 assert(AddressOfExpr->getType() == Context.OverloadTy)(static_cast <bool> (AddressOfExpr->getType() == Context
.OverloadTy) ? void (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11246, __extension__ __PRETTY_FUNCTION__))
;
11247
11248 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11249 Complain);
11250 int NumMatches = Resolver.getNumMatches();
11251 FunctionDecl *Fn = nullptr;
11252 bool ShouldComplain = Complain && !Resolver.hasComplained();
11253 if (NumMatches == 0 && ShouldComplain) {
11254 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11255 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11256 else
11257 Resolver.ComplainNoMatchesFound();
11258 }
11259 else if (NumMatches > 1 && ShouldComplain)
11260 Resolver.ComplainMultipleMatchesFound();
11261 else if (NumMatches == 1) {
11262 Fn = Resolver.getMatchingFunctionDecl();
11263 assert(Fn)(static_cast <bool> (Fn) ? void (0) : __assert_fail ("Fn"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11263, __extension__ __PRETTY_FUNCTION__))
;
11264 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11265 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11266 FoundResult = *Resolver.getMatchingFunctionAccessPair();
11267 if (Complain) {
11268 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11269 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11270 else
11271 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11272 }
11273 }
11274
11275 if (pHadMultipleCandidates)
11276 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11277 return Fn;
11278}
11279
11280/// Given an expression that refers to an overloaded function, try to
11281/// resolve that function to a single function that can have its address taken.
11282/// This will modify `Pair` iff it returns non-null.
11283///
11284/// This routine can only realistically succeed if all but one candidates in the
11285/// overload set for SrcExpr cannot have their addresses taken.
11286FunctionDecl *
11287Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11288 DeclAccessPair &Pair) {
11289 OverloadExpr::FindResult R = OverloadExpr::find(E);
11290 OverloadExpr *Ovl = R.Expression;
11291 FunctionDecl *Result = nullptr;
11292 DeclAccessPair DAP;
11293 // Don't use the AddressOfResolver because we're specifically looking for
11294 // cases where we have one overload candidate that lacks
11295 // enable_if/pass_object_size/...
11296 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11297 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11298 if (!FD)
11299 return nullptr;
11300
11301 if (!checkAddressOfFunctionIsAvailable(FD))
11302 continue;
11303
11304 // We have more than one result; quit.
11305 if (Result)
11306 return nullptr;
11307 DAP = I.getPair();
11308 Result = FD;
11309 }
11310
11311 if (Result)
11312 Pair = DAP;
11313 return Result;
11314}
11315
11316/// Given an overloaded function, tries to turn it into a non-overloaded
11317/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11318/// will perform access checks, diagnose the use of the resultant decl, and, if
11319/// requested, potentially perform a function-to-pointer decay.
11320///
11321/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11322/// Otherwise, returns true. This may emit diagnostics and return true.
11323bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11324 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11325 Expr *E = SrcExpr.get();
11326 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload")(static_cast <bool> (E->getType() == Context.OverloadTy
&& "SrcExpr must be an overload") ? void (0) : __assert_fail
("E->getType() == Context.OverloadTy && \"SrcExpr must be an overload\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11326, __extension__ __PRETTY_FUNCTION__))
;
11327
11328 DeclAccessPair DAP;
11329 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11330 if (!Found)
11331 return false;
11332
11333 // Emitting multiple diagnostics for a function that is both inaccessible and
11334 // unavailable is consistent with our behavior elsewhere. So, always check
11335 // for both.
11336 DiagnoseUseOfDecl(Found, E->getExprLoc());
11337 CheckAddressOfMemberAccess(E, DAP);
11338 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11339 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11340 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11341 else
11342 SrcExpr = Fixed;
11343 return true;
11344}
11345
11346/// Given an expression that refers to an overloaded function, try to
11347/// resolve that overloaded function expression down to a single function.
11348///
11349/// This routine can only resolve template-ids that refer to a single function
11350/// template, where that template-id refers to a single template whose template
11351/// arguments are either provided by the template-id or have defaults,
11352/// as described in C++0x [temp.arg.explicit]p3.
11353///
11354/// If no template-ids are found, no diagnostics are emitted and NULL is
11355/// returned.
11356FunctionDecl *
11357Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11358 bool Complain,
11359 DeclAccessPair *FoundResult) {
11360 // C++ [over.over]p1:
11361 // [...] [Note: any redundant set of parentheses surrounding the
11362 // overloaded function name is ignored (5.1). ]
11363 // C++ [over.over]p1:
11364 // [...] The overloaded function name can be preceded by the &
11365 // operator.
11366
11367 // If we didn't actually find any template-ids, we're done.
11368 if (!ovl->hasExplicitTemplateArgs())
2
Taking false branch
11369 return nullptr;
11370
11371 TemplateArgumentListInfo ExplicitTemplateArgs;
11372 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11373 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11374
11375 // Look through all of the overloaded functions, searching for one
11376 // whose type matches exactly.
11377 FunctionDecl *Matched = nullptr;
11378 for (UnresolvedSetIterator I = ovl->decls_begin(),
3
Loop condition is true. Entering loop body
11379 E = ovl->decls_end(); I != E; ++I) {
11380 // C++0x [temp.arg.explicit]p3:
11381 // [...] In contexts where deduction is done and fails, or in contexts
11382 // where deduction is not done, if a template argument list is
11383 // specified and it, along with any default template arguments,
11384 // identifies a single function template specialization, then the
11385 // template-id is an lvalue for the function template specialization.
11386 FunctionTemplateDecl *FunctionTemplate
11387 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11388
11389 // C++ [over.over]p2:
11390 // If the name is a function template, template argument deduction is
11391 // done (14.8.2.2), and if the argument deduction succeeds, the
11392 // resulting template argument list is used to generate a single
11393 // function template specialization, which is added to the set of
11394 // overloaded functions considered.
11395 FunctionDecl *Specialization = nullptr;
11396 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11397 if (TemplateDeductionResult Result
4
Assuming 'Result' is not equal to 0
5
Taking true branch
11398 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11399 Specialization, Info,
11400 /*IsAddressOfFunction*/true)) {
11401 // Make a note of the failed deduction for diagnostics.
11402 // TODO: Actually use the failed-deduction info?
11403 FailedCandidates.addCandidate()
11404 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11405 MakeDeductionFailureInfo(Context, Result, Info));
6
Calling 'MakeDeductionFailureInfo'
11406 continue;
11407 }
11408
11409 assert(Specialization && "no specialization and no error?")(static_cast <bool> (Specialization && "no specialization and no error?"
) ? void (0) : __assert_fail ("Specialization && \"no specialization and no error?\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11409, __extension__ __PRETTY_FUNCTION__))
;
11410
11411 // Multiple matches; we can't resolve to a single declaration.
11412 if (Matched) {
11413 if (Complain) {
11414 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11415 << ovl->getName();
11416 NoteAllOverloadCandidates(ovl);
11417 }
11418 return nullptr;
11419 }
11420
11421 Matched = Specialization;
11422 if (FoundResult) *FoundResult = I.getPair();
11423 }
11424
11425 if (Matched &&
11426 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11427 return nullptr;
11428
11429 return Matched;
11430}
11431
11432// Resolve and fix an overloaded expression that can be resolved
11433// because it identifies a single function template specialization.
11434//
11435// Last three arguments should only be supplied if Complain = true
11436//
11437// Return true if it was logically possible to so resolve the
11438// expression, regardless of whether or not it succeeded. Always
11439// returns true if 'complain' is set.
11440bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11441 ExprResult &SrcExpr, bool doFunctionPointerConverion,
11442 bool complain, SourceRange OpRangeForComplaining,
11443 QualType DestTypeForComplaining,
11444 unsigned DiagIDForComplaining) {
11445 assert(SrcExpr.get()->getType() == Context.OverloadTy)(static_cast <bool> (SrcExpr.get()->getType() == Context
.OverloadTy) ? void (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11445, __extension__ __PRETTY_FUNCTION__))
;
11446
11447 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11448
11449 DeclAccessPair found;
11450 ExprResult SingleFunctionExpression;
11451 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
1
Calling 'Sema::ResolveSingleFunctionTemplateSpecialization'
11452 ovl.Expression, /*complain*/ false, &found)) {
11453 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11454 SrcExpr = ExprError();
11455 return true;
11456 }
11457
11458 // It is only correct to resolve to an instance method if we're
11459 // resolving a form that's permitted to be a pointer to member.
11460 // Otherwise we'll end up making a bound member expression, which
11461 // is illegal in all the contexts we resolve like this.
11462 if (!ovl.HasFormOfMemberPointer &&
11463 isa<CXXMethodDecl>(fn) &&
11464 cast<CXXMethodDecl>(fn)->isInstance()) {
11465 if (!complain) return false;
11466
11467 Diag(ovl.Expression->getExprLoc(),
11468 diag::err_bound_member_function)
11469 << 0 << ovl.Expression->getSourceRange();
11470
11471 // TODO: I believe we only end up here if there's a mix of
11472 // static and non-static candidates (otherwise the expression
11473 // would have 'bound member' type, not 'overload' type).
11474 // Ideally we would note which candidate was chosen and why
11475 // the static candidates were rejected.
11476 SrcExpr = ExprError();
11477 return true;
11478 }
11479
11480 // Fix the expression to refer to 'fn'.
11481 SingleFunctionExpression =
11482 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11483
11484 // If desired, do function-to-pointer decay.
11485 if (doFunctionPointerConverion) {
11486 SingleFunctionExpression =
11487 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11488 if (SingleFunctionExpression.isInvalid()) {
11489 SrcExpr = ExprError();
11490 return true;
11491 }
11492 }
11493 }
11494
11495 if (!SingleFunctionExpression.isUsable()) {
11496 if (complain) {
11497 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11498 << ovl.Expression->getName()
11499 << DestTypeForComplaining
11500 << OpRangeForComplaining
11501 << ovl.Expression->getQualifierLoc().getSourceRange();
11502 NoteAllOverloadCandidates(SrcExpr.get());
11503
11504 SrcExpr = ExprError();
11505 return true;
11506 }
11507
11508 return false;
11509 }
11510
11511 SrcExpr = SingleFunctionExpression;
11512 return true;
11513}
11514
11515/// Add a single candidate to the overload set.
11516static void AddOverloadedCallCandidate(Sema &S,
11517 DeclAccessPair FoundDecl,
11518 TemplateArgumentListInfo *ExplicitTemplateArgs,
11519 ArrayRef<Expr *> Args,
11520 OverloadCandidateSet &CandidateSet,
11521 bool PartialOverloading,
11522 bool KnownValid) {
11523 NamedDecl *Callee = FoundDecl.getDecl();
11524 if (isa<UsingShadowDecl>(Callee))
11525 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11526
11527 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11528 if (ExplicitTemplateArgs) {
11529 assert(!KnownValid && "Explicit template arguments?")(static_cast <bool> (!KnownValid && "Explicit template arguments?"
) ? void (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11529, __extension__ __PRETTY_FUNCTION__))
;
11530 return;
11531 }
11532 // Prevent ill-formed function decls to be added as overload candidates.
11533 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11534 return;
11535
11536 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11537 /*SuppressUsedConversions=*/false,
11538 PartialOverloading);
11539 return;
11540 }
11541
11542 if (FunctionTemplateDecl *FuncTemplate
11543 = dyn_cast<FunctionTemplateDecl>(Callee)) {
11544 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11545 ExplicitTemplateArgs, Args, CandidateSet,
11546 /*SuppressUsedConversions=*/false,
11547 PartialOverloading);
11548 return;
11549 }
11550
11551 assert(!KnownValid && "unhandled case in overloaded call candidate")(static_cast <bool> (!KnownValid && "unhandled case in overloaded call candidate"
) ? void (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11551, __extension__ __PRETTY_FUNCTION__))
;
11552}
11553
11554/// Add the overload candidates named by callee and/or found by argument
11555/// dependent lookup to the given overload set.
11556void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11557 ArrayRef<Expr *> Args,
11558 OverloadCandidateSet &CandidateSet,
11559 bool PartialOverloading) {
11560
11561#ifndef NDEBUG
11562 // Verify that ArgumentDependentLookup is consistent with the rules
11563 // in C++0x [basic.lookup.argdep]p3:
11564 //
11565 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11566 // and let Y be the lookup set produced by argument dependent
11567 // lookup (defined as follows). If X contains
11568 //
11569 // -- a declaration of a class member, or
11570 //
11571 // -- a block-scope function declaration that is not a
11572 // using-declaration, or
11573 //
11574 // -- a declaration that is neither a function or a function
11575 // template
11576 //
11577 // then Y is empty.
11578
11579 if (ULE->requiresADL()) {
11580 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11581 E = ULE->decls_end(); I != E; ++I) {
11582 assert(!(*I)->getDeclContext()->isRecord())(static_cast <bool> (!(*I)->getDeclContext()->isRecord
()) ? void (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11582, __extension__ __PRETTY_FUNCTION__))
;
11583 assert(isa<UsingShadowDecl>(*I) ||(static_cast <bool> (isa<UsingShadowDecl>(*I) || !
(*I)->getDeclContext()->isFunctionOrMethod()) ? void (0
) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11584, __extension__ __PRETTY_FUNCTION__))
11584 !(*I)->getDeclContext()->isFunctionOrMethod())(static_cast <bool> (isa<UsingShadowDecl>(*I) || !
(*I)->getDeclContext()->isFunctionOrMethod()) ? void (0
) : __assert_fail ("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11584, __extension__ __PRETTY_FUNCTION__))
;
11585 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(static_cast <bool> ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? void (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11585, __extension__ __PRETTY_FUNCTION__))
;
11586 }
11587 }
11588#endif
11589
11590 // It would be nice to avoid this copy.
11591 TemplateArgumentListInfo TABuffer;
11592 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11593 if (ULE->hasExplicitTemplateArgs()) {
11594 ULE->copyTemplateArgumentsInto(TABuffer);
11595 ExplicitTemplateArgs = &TABuffer;
11596 }
11597
11598 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11599 E = ULE->decls_end(); I != E; ++I)
11600 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11601 CandidateSet, PartialOverloading,
11602 /*KnownValid*/ true);
11603
11604 if (ULE->requiresADL())
11605 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11606 Args, ExplicitTemplateArgs,
11607 CandidateSet, PartialOverloading);
11608}
11609
11610/// Determine whether a declaration with the specified name could be moved into
11611/// a different namespace.
11612static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11613 switch (Name.getCXXOverloadedOperator()) {
11614 case OO_New: case OO_Array_New:
11615 case OO_Delete: case OO_Array_Delete:
11616 return false;
11617
11618 default:
11619 return true;
11620 }
11621}
11622
11623/// Attempt to recover from an ill-formed use of a non-dependent name in a
11624/// template, where the non-dependent name was declared after the template
11625/// was defined. This is common in code written for a compilers which do not
11626/// correctly implement two-stage name lookup.
11627///
11628/// Returns true if a viable candidate was found and a diagnostic was issued.
11629static bool
11630DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11631 const CXXScopeSpec &SS, LookupResult &R,
11632 OverloadCandidateSet::CandidateSetKind CSK,
11633 TemplateArgumentListInfo *ExplicitTemplateArgs,
11634 ArrayRef<Expr *> Args,
11635 bool *DoDiagnoseEmptyLookup = nullptr) {
11636 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11637 return false;
11638
11639 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11640 if (DC->isTransparentContext())
11641 continue;
11642
11643 SemaRef.LookupQualifiedName(R, DC);
11644
11645 if (!R.empty()) {
11646 R.suppressDiagnostics();
11647
11648 if (isa<CXXRecordDecl>(DC)) {
11649 // Don't diagnose names we find in classes; we get much better
11650 // diagnostics for these from DiagnoseEmptyLookup.
11651 R.clear();
11652 if (DoDiagnoseEmptyLookup)
11653 *DoDiagnoseEmptyLookup = true;
11654 return false;
11655 }
11656
11657 OverloadCandidateSet Candidates(FnLoc, CSK);
11658 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11659 AddOverloadedCallCandidate(SemaRef, I.getPair(),
11660 ExplicitTemplateArgs, Args,
11661 Candidates, false, /*KnownValid*/ false);
11662
11663 OverloadCandidateSet::iterator Best;
11664 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11665 // No viable functions. Don't bother the user with notes for functions
11666 // which don't work and shouldn't be found anyway.
11667 R.clear();
11668 return false;
11669 }
11670
11671 // Find the namespaces where ADL would have looked, and suggest
11672 // declaring the function there instead.
11673 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11674 Sema::AssociatedClassSet AssociatedClasses;
11675 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11676 AssociatedNamespaces,
11677 AssociatedClasses);
11678 Sema::AssociatedNamespaceSet SuggestedNamespaces;
11679 if (canBeDeclaredInNamespace(R.getLookupName())) {
11680 DeclContext *Std = SemaRef.getStdNamespace();
11681 for (Sema::AssociatedNamespaceSet::iterator
11682 it = AssociatedNamespaces.begin(),
11683 end = AssociatedNamespaces.end(); it != end; ++it) {
11684 // Never suggest declaring a function within namespace 'std'.
11685 if (Std && Std->Encloses(*it))
11686 continue;
11687
11688 // Never suggest declaring a function within a namespace with a
11689 // reserved name, like __gnu_cxx.
11690 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11691 if (NS &&
11692 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11693 continue;
11694
11695 SuggestedNamespaces.insert(*it);
11696 }
11697 }
11698
11699 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11700 << R.getLookupName();
11701 if (SuggestedNamespaces.empty()) {
11702 SemaRef.Diag(Best->Function->getLocation(),
11703 diag::note_not_found_by_two_phase_lookup)
11704 << R.getLookupName() << 0;
11705 } else if (SuggestedNamespaces.size() == 1) {
11706 SemaRef.Diag(Best->Function->getLocation(),
11707 diag::note_not_found_by_two_phase_lookup)
11708 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11709 } else {
11710 // FIXME: It would be useful to list the associated namespaces here,
11711 // but the diagnostics infrastructure doesn't provide a way to produce
11712 // a localized representation of a list of items.
11713 SemaRef.Diag(Best->Function->getLocation(),
11714 diag::note_not_found_by_two_phase_lookup)
11715 << R.getLookupName() << 2;
11716 }
11717
11718 // Try to recover by calling this function.
11719 return true;
11720 }
11721
11722 R.clear();
11723 }
11724
11725 return false;
11726}
11727
11728/// Attempt to recover from ill-formed use of a non-dependent operator in a
11729/// template, where the non-dependent operator was declared after the template
11730/// was defined.
11731///
11732/// Returns true if a viable candidate was found and a diagnostic was issued.
11733static bool
11734DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11735 SourceLocation OpLoc,
11736 ArrayRef<Expr *> Args) {
11737 DeclarationName OpName =
11738 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11739 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11740 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11741 OverloadCandidateSet::CSK_Operator,
11742 /*ExplicitTemplateArgs=*/nullptr, Args);
11743}
11744
11745namespace {
11746class BuildRecoveryCallExprRAII {
11747 Sema &SemaRef;
11748public:
11749 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11750 assert(SemaRef.IsBuildingRecoveryCallExpr == false)(static_cast <bool> (SemaRef.IsBuildingRecoveryCallExpr
== false) ? void (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11750, __extension__ __PRETTY_FUNCTION__))
;
11751 SemaRef.IsBuildingRecoveryCallExpr = true;
11752 }
11753
11754 ~BuildRecoveryCallExprRAII() {
11755 SemaRef.IsBuildingRecoveryCallExpr = false;
11756 }
11757};
11758
11759}
11760
11761static std::unique_ptr<CorrectionCandidateCallback>
11762MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11763 bool HasTemplateArgs, bool AllowTypoCorrection) {
11764 if (!AllowTypoCorrection)
11765 return llvm::make_unique<NoTypoCorrectionCCC>();
11766 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11767 HasTemplateArgs, ME);
11768}
11769
11770/// Attempts to recover from a call where no functions were found.
11771///
11772/// Returns true if new candidates were found.
11773static ExprResult
11774BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11775 UnresolvedLookupExpr *ULE,
11776 SourceLocation LParenLoc,
11777 MutableArrayRef<Expr *> Args,
11778 SourceLocation RParenLoc,
11779 bool EmptyLookup, bool AllowTypoCorrection) {
11780 // Do not try to recover if it is already building a recovery call.
11781 // This stops infinite loops for template instantiations like
11782 //
11783 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11784 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11785 //
11786 if (SemaRef.IsBuildingRecoveryCallExpr)
11787 return ExprError();
11788 BuildRecoveryCallExprRAII RCE(SemaRef);
11789
11790 CXXScopeSpec SS;
11791 SS.Adopt(ULE->getQualifierLoc());
11792 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11793
11794 TemplateArgumentListInfo TABuffer;
11795 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11796 if (ULE->hasExplicitTemplateArgs()) {
11797 ULE->copyTemplateArgumentsInto(TABuffer);
11798 ExplicitTemplateArgs = &TABuffer;
11799 }
11800
11801 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11802 Sema::LookupOrdinaryName);
11803 bool DoDiagnoseEmptyLookup = EmptyLookup;
11804 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11805 OverloadCandidateSet::CSK_Normal,
11806 ExplicitTemplateArgs, Args,
11807 &DoDiagnoseEmptyLookup) &&
11808 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11809 S, SS, R,
11810 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11811 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11812 ExplicitTemplateArgs, Args)))
11813 return ExprError();
11814
11815 assert(!R.empty() && "lookup results empty despite recovery")(static_cast <bool> (!R.empty() && "lookup results empty despite recovery"
) ? void (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11815, __extension__ __PRETTY_FUNCTION__))
;
11816
11817 // If recovery created an ambiguity, just bail out.
11818 if (R.isAmbiguous()) {
11819 R.suppressDiagnostics();
11820 return ExprError();
11821 }
11822
11823 // Build an implicit member call if appropriate. Just drop the
11824 // casts and such from the call, we don't really care.
11825 ExprResult NewFn = ExprError();
11826 if ((*R.begin())->isCXXClassMember())
11827 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11828 ExplicitTemplateArgs, S);
11829 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11830 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11831 ExplicitTemplateArgs);
11832 else
11833 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11834
11835 if (NewFn.isInvalid())
11836 return ExprError();
11837
11838 // This shouldn't cause an infinite loop because we're giving it
11839 // an expression with viable lookup results, which should never
11840 // end up here.
11841 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11842 MultiExprArg(Args.data(), Args.size()),
11843 RParenLoc);
11844}
11845
11846/// Constructs and populates an OverloadedCandidateSet from
11847/// the given function.
11848/// \returns true when an the ExprResult output parameter has been set.
11849bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11850 UnresolvedLookupExpr *ULE,
11851 MultiExprArg Args,
11852 SourceLocation RParenLoc,
11853 OverloadCandidateSet *CandidateSet,
11854 ExprResult *Result) {
11855#ifndef NDEBUG
11856 if (ULE->requiresADL()) {
11857 // To do ADL, we must have found an unqualified name.
11858 assert(!ULE->getQualifier() && "qualified name with ADL")(static_cast <bool> (!ULE->getQualifier() &&
"qualified name with ADL") ? void (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11858, __extension__ __PRETTY_FUNCTION__))
;
11859
11860 // We don't perform ADL for implicit declarations of builtins.
11861 // Verify that this was correctly set up.
11862 FunctionDecl *F;
11863 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11864 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11865 F->getBuiltinID() && F->isImplicit())
11866 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11866)
;
11867
11868 // We don't perform ADL in C.
11869 assert(getLangOpts().CPlusPlus && "ADL enabled in C")(static_cast <bool> (getLangOpts().CPlusPlus &&
"ADL enabled in C") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 11869, __extension__ __PRETTY_FUNCTION__))
;
11870 }
11871#endif
11872
11873 UnbridgedCastsSet UnbridgedCasts;
11874 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11875 *Result = ExprError();
11876 return true;
11877 }
11878
11879 // Add the functions denoted by the callee to the set of candidate
11880 // functions, including those from argument-dependent lookup.
11881 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11882
11883 if (getLangOpts().MSVCCompat &&
11884 CurContext->isDependentContext() && !isSFINAEContext() &&
11885 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11886
11887 OverloadCandidateSet::iterator Best;
11888 if (CandidateSet->empty() ||
11889 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11890 OR_No_Viable_Function) {
11891 // In Microsoft mode, if we are inside a template class member function then
11892 // create a type dependent CallExpr. The goal is to postpone name lookup
11893 // to instantiation time to be able to search into type dependent base
11894 // classes.
11895 CallExpr *CE = new (Context) CallExpr(
11896 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11897 CE->setTypeDependent(true);
11898 CE->setValueDependent(true);
11899 CE->setInstantiationDependent(true);
11900 *Result = CE;
11901 return true;
11902 }
11903 }
11904
11905 if (CandidateSet->empty())
11906 return false;
11907
11908 UnbridgedCasts.restore();
11909 return false;
11910}
11911
11912/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11913/// the completed call expression. If overload resolution fails, emits
11914/// diagnostics and returns ExprError()
11915static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11916 UnresolvedLookupExpr *ULE,
11917 SourceLocation LParenLoc,
11918 MultiExprArg Args,
11919 SourceLocation RParenLoc,
11920 Expr *ExecConfig,
11921 OverloadCandidateSet *CandidateSet,
11922 OverloadCandidateSet::iterator *Best,
11923 OverloadingResult OverloadResult,
11924 bool AllowTypoCorrection) {
11925 if (CandidateSet->empty())
11926 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11927 RParenLoc, /*EmptyLookup=*/true,
11928 AllowTypoCorrection);
11929
11930 switch (OverloadResult) {
11931 case OR_Success: {
11932 FunctionDecl *FDecl = (*Best)->Function;
11933 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11934 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11935 return ExprError();
11936 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11937 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11938 ExecConfig);
11939 }
11940
11941 case OR_No_Viable_Function: {
11942 // Try to recover by looking for viable functions which the user might
11943 // have meant to call.
11944 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11945 Args, RParenLoc,
11946 /*EmptyLookup=*/false,
11947 AllowTypoCorrection);
11948 if (!Recovery.isInvalid())
11949 return Recovery;
11950
11951 // If the user passes in a function that we can't take the address of, we
11952 // generally end up emitting really bad error messages. Here, we attempt to
11953 // emit better ones.
11954 for (const Expr *Arg : Args) {
11955 if (!Arg->getType()->isFunctionType())
11956 continue;
11957 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11958 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11959 if (FD &&
11960 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11961 Arg->getExprLoc()))
11962 return ExprError();
11963 }
11964 }
11965
11966 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11967 << ULE->getName() << Fn->getSourceRange();
11968 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11969 break;
11970 }
11971
11972 case OR_Ambiguous:
11973 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11974 << ULE->getName() << Fn->getSourceRange();
11975 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11976 break;
11977
11978 case OR_Deleted: {
11979 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11980 << (*Best)->Function->isDeleted()
11981 << ULE->getName()
11982 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11983 << Fn->getSourceRange();
11984 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11985
11986 // We emitted an error for the unavailable/deleted function call but keep
11987 // the call in the AST.
11988 FunctionDecl *FDecl = (*Best)->Function;
11989 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11990 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11991 ExecConfig);
11992 }
11993 }
11994
11995 // Overload resolution failed.
11996 return ExprError();
11997}
11998
11999static void markUnaddressableCandidatesUnviable(Sema &S,
12000 OverloadCandidateSet &CS) {
12001 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12002 if (I->Viable &&
12003 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12004 I->Viable = false;
12005 I->FailureKind = ovl_fail_addr_not_available;
12006 }
12007 }
12008}
12009
12010/// BuildOverloadedCallExpr - Given the call expression that calls Fn
12011/// (which eventually refers to the declaration Func) and the call
12012/// arguments Args/NumArgs, attempt to resolve the function call down
12013/// to a specific function. If overload resolution succeeds, returns
12014/// the call expression produced by overload resolution.
12015/// Otherwise, emits diagnostics and returns ExprError.
12016ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12017 UnresolvedLookupExpr *ULE,
12018 SourceLocation LParenLoc,
12019 MultiExprArg Args,
12020 SourceLocation RParenLoc,
12021 Expr *ExecConfig,
12022 bool AllowTypoCorrection,
12023 bool CalleesAddressIsTaken) {
12024 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12025 OverloadCandidateSet::CSK_Normal);
12026 ExprResult result;
12027
12028 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12029 &result))
12030 return result;
12031
12032 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12033 // functions that aren't addressible are considered unviable.
12034 if (CalleesAddressIsTaken)
12035 markUnaddressableCandidatesUnviable(*this, CandidateSet);
12036
12037 OverloadCandidateSet::iterator Best;
12038 OverloadingResult OverloadResult =
12039 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
12040
12041 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12042 RParenLoc, ExecConfig, &CandidateSet,
12043 &Best, OverloadResult,
12044 AllowTypoCorrection);
12045}
12046
12047static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12048 return Functions.size() > 1 ||
12049 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12050}
12051
12052/// Create a unary operation that may resolve to an overloaded
12053/// operator.
12054///
12055/// \param OpLoc The location of the operator itself (e.g., '*').
12056///
12057/// \param Opc The UnaryOperatorKind that describes this operator.
12058///
12059/// \param Fns The set of non-member functions that will be
12060/// considered by overload resolution. The caller needs to build this
12061/// set based on the context using, e.g.,
12062/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12063/// set should not contain any member functions; those will be added
12064/// by CreateOverloadedUnaryOp().
12065///
12066/// \param Input The input argument.
12067ExprResult
12068Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12069 const UnresolvedSetImpl &Fns,
12070 Expr *Input, bool PerformADL) {
12071 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12072 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")(static_cast <bool> (Op != OO_None && "Invalid opcode for overloaded unary operator"
) ? void (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 12072, __extension__ __PRETTY_FUNCTION__))
;
12073 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12074 // TODO: provide better source location info.
12075 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12076
12077 if (checkPlaceholderForOverload(*this, Input))
12078 return ExprError();
12079
12080 Expr *Args[2] = { Input, nullptr };
12081 unsigned NumArgs = 1;
12082
12083 // For post-increment and post-decrement, add the implicit '0' as
12084 // the second argument, so that we know this is a post-increment or
12085 // post-decrement.
12086 if (Opc == UO_PostInc || Opc == UO_PostDec) {
12087 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12088 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12089 SourceLocation());
12090 NumArgs = 2;
12091 }
12092
12093 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12094
12095 if (Input->isTypeDependent()) {
12096 if (Fns.empty())
12097 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12098 VK_RValue, OK_Ordinary, OpLoc, false);
12099
12100 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12101 UnresolvedLookupExpr *Fn
12102 = UnresolvedLookupExpr::Create(Context, NamingClass,
12103 NestedNameSpecifierLoc(), OpNameInfo,
12104 /*ADL*/ true, IsOverloaded(Fns),
12105 Fns.begin(), Fns.end());
12106 return new (Context)
12107 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12108 VK_RValue, OpLoc, FPOptions());
12109 }
12110
12111 // Build an empty overload set.
12112 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12113
12114 // Add the candidates from the given function set.
12115 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12116
12117 // Add operator candidates that are member functions.
12118 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12119
12120 // Add candidates from ADL.
12121 if (PerformADL) {
12122 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12123 /*ExplicitTemplateArgs*/nullptr,
12124 CandidateSet);
12125 }
12126
12127 // Add builtin operator candidates.
12128 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12129
12130 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12131
12132 // Perform overload resolution.
12133 OverloadCandidateSet::iterator Best;
12134 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12135 case OR_Success: {
12136 // We found a built-in operator or an overloaded operator.
12137 FunctionDecl *FnDecl = Best->Function;
12138
12139 if (FnDecl) {
12140 Expr *Base = nullptr;
12141 // We matched an overloaded operator. Build a call to that
12142 // operator.
12143
12144 // Convert the arguments.
12145 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12146 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12147
12148 ExprResult InputRes =
12149 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12150 Best->FoundDecl, Method);
12151 if (InputRes.isInvalid())
12152 return ExprError();
12153 Base = Input = InputRes.get();
12154 } else {
12155 // Convert the arguments.
12156 ExprResult InputInit
12157 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12158 Context,
12159 FnDecl->getParamDecl(0)),
12160 SourceLocation(),
12161 Input);
12162 if (InputInit.isInvalid())
12163 return ExprError();
12164 Input = InputInit.get();
12165 }
12166
12167 // Build the actual expression node.
12168 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12169 Base, HadMultipleCandidates,
12170 OpLoc);
12171 if (FnExpr.isInvalid())
12172 return ExprError();
12173
12174 // Determine the result type.
12175 QualType ResultTy = FnDecl->getReturnType();
12176 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12177 ResultTy = ResultTy.getNonLValueExprType(Context);
12178
12179 Args[0] = Input;
12180 CallExpr *TheCall =
12181 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12182 ResultTy, VK, OpLoc, FPOptions());
12183
12184 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12185 return ExprError();
12186
12187 if (CheckFunctionCall(FnDecl, TheCall,
12188 FnDecl->getType()->castAs<FunctionProtoType>()))
12189 return ExprError();
12190
12191 return MaybeBindToTemporary(TheCall);
12192 } else {
12193 // We matched a built-in operator. Convert the arguments, then
12194 // break out so that we will build the appropriate built-in
12195 // operator node.
12196 ExprResult InputRes = PerformImplicitConversion(
12197 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12198 CCK_ForBuiltinOverloadedOp);
12199 if (InputRes.isInvalid())
12200 return ExprError();
12201 Input = InputRes.get();
12202 break;
12203 }
12204 }
12205
12206 case OR_No_Viable_Function:
12207 // This is an erroneous use of an operator which can be overloaded by
12208 // a non-member function. Check for non-member operators which were
12209 // defined too late to be candidates.
12210 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12211 // FIXME: Recover by calling the found function.
12212 return ExprError();
12213
12214 // No viable function; fall through to handling this as a
12215 // built-in operator, which will produce an error message for us.
12216 break;
12217
12218 case OR_Ambiguous:
12219 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12220 << UnaryOperator::getOpcodeStr(Opc)
12221 << Input->getType()
12222 << Input->getSourceRange();
12223 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12224 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12225 return ExprError();
12226
12227 case OR_Deleted:
12228 Diag(OpLoc, diag::err_ovl_deleted_oper)
12229 << Best->Function->isDeleted()
12230 << UnaryOperator::getOpcodeStr(Opc)
12231 << getDeletedOrUnavailableSuffix(Best->Function)
12232 << Input->getSourceRange();
12233 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12234 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12235 return ExprError();
12236 }
12237
12238 // Either we found no viable overloaded operator or we matched a
12239 // built-in operator. In either case, fall through to trying to
12240 // build a built-in operation.
12241 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12242}
12243
12244/// Create a binary operation that may resolve to an overloaded
12245/// operator.
12246///
12247/// \param OpLoc The location of the operator itself (e.g., '+').
12248///
12249/// \param Opc The BinaryOperatorKind that describes this operator.
12250///
12251/// \param Fns The set of non-member functions that will be
12252/// considered by overload resolution. The caller needs to build this
12253/// set based on the context using, e.g.,
12254/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12255/// set should not contain any member functions; those will be added
12256/// by CreateOverloadedBinOp().
12257///
12258/// \param LHS Left-hand argument.
12259/// \param RHS Right-hand argument.
12260ExprResult
12261Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12262 BinaryOperatorKind Opc,
12263 const UnresolvedSetImpl &Fns,
12264 Expr *LHS, Expr *RHS, bool PerformADL) {
12265 Expr *Args[2] = { LHS, RHS };
12266 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12267
12268 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12269 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12270
12271 // If either side is type-dependent, create an appropriate dependent
12272 // expression.
12273 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12274 if (Fns.empty()) {
12275 // If there are no functions to store, just build a dependent
12276 // BinaryOperator or CompoundAssignment.
12277 if (Opc <= BO_Assign || Opc > BO_OrAssign)
12278 return new (Context) BinaryOperator(
12279 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12280 OpLoc, FPFeatures);
12281
12282 return new (Context) CompoundAssignOperator(
12283 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12284 Context.DependentTy, Context.DependentTy, OpLoc,
12285 FPFeatures);
12286 }
12287
12288 // FIXME: save results of ADL from here?
12289 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12290 // TODO: provide better source location info in DNLoc component.
12291 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12292 UnresolvedLookupExpr *Fn
12293 = UnresolvedLookupExpr::Create(Context, NamingClass,
12294 NestedNameSpecifierLoc(), OpNameInfo,
12295 /*ADL*/PerformADL, IsOverloaded(Fns),
12296 Fns.begin(), Fns.end());
12297 return new (Context)
12298 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12299 VK_RValue, OpLoc, FPFeatures);
12300 }
12301
12302 // Always do placeholder-like conversions on the RHS.
12303 if (checkPlaceholderForOverload(*this, Args[1]))
12304 return ExprError();
12305
12306 // Do placeholder-like conversion on the LHS; note that we should
12307 // not get here with a PseudoObject LHS.
12308 assert(Args[0]->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (Args[0]->getObjectKind() != OK_ObjCProperty
) ? void (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 12308, __extension__ __PRETTY_FUNCTION__))
;
12309 if (checkPlaceholderForOverload(*this, Args[0]))
12310 return ExprError();
12311
12312 // If this is the assignment operator, we only perform overload resolution
12313 // if the left-hand side is a class or enumeration type. This is actually
12314 // a hack. The standard requires that we do overload resolution between the
12315 // various built-in candidates, but as DR507 points out, this can lead to
12316 // problems. So we do it this way, which pretty much follows what GCC does.
12317 // Note that we go the traditional code path for compound assignment forms.
12318 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12319 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12320
12321 // If this is the .* operator, which is not overloadable, just
12322 // create a built-in binary operator.
12323 if (Opc == BO_PtrMemD)
12324 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12325
12326 // Build an empty overload set.
12327 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12328
12329 // Add the candidates from the given function set.
12330 AddFunctionCandidates(Fns, Args, CandidateSet);
12331
12332 // Add operator candidates that are member functions.
12333 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12334
12335 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12336 // performed for an assignment operator (nor for operator[] nor operator->,
12337 // which don't get here).
12338 if (Opc != BO_Assign && PerformADL)
12339 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12340 /*ExplicitTemplateArgs*/ nullptr,
12341 CandidateSet);
12342
12343 // Add builtin operator candidates.
12344 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12345
12346 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12347
12348 // Perform overload resolution.
12349 OverloadCandidateSet::iterator Best;
12350 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12351 case OR_Success: {
12352 // We found a built-in operator or an overloaded operator.
12353 FunctionDecl *FnDecl = Best->Function;
12354
12355 if (FnDecl) {
12356 Expr *Base = nullptr;
12357 // We matched an overloaded operator. Build a call to that
12358 // operator.
12359
12360 // Convert the arguments.
12361 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12362 // Best->Access is only meaningful for class members.
12363 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12364
12365 ExprResult Arg1 =
12366 PerformCopyInitialization(
12367 InitializedEntity::InitializeParameter(Context,
12368 FnDecl->getParamDecl(0)),
12369 SourceLocation(), Args[1]);
12370 if (Arg1.isInvalid())
12371 return ExprError();
12372
12373 ExprResult Arg0 =
12374 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12375 Best->FoundDecl, Method);
12376 if (Arg0.isInvalid())
12377 return ExprError();
12378 Base = Args[0] = Arg0.getAs<Expr>();
12379 Args[1] = RHS = Arg1.getAs<Expr>();
12380 } else {
12381 // Convert the arguments.
12382 ExprResult Arg0 = PerformCopyInitialization(
12383 InitializedEntity::InitializeParameter(Context,
12384 FnDecl->getParamDecl(0)),
12385 SourceLocation(), Args[0]);
12386 if (Arg0.isInvalid())
12387 return ExprError();
12388
12389 ExprResult Arg1 =
12390 PerformCopyInitialization(
12391 InitializedEntity::InitializeParameter(Context,
12392 FnDecl->getParamDecl(1)),
12393 SourceLocation(), Args[1]);
12394 if (Arg1.isInvalid())
12395 return ExprError();
12396 Args[0] = LHS = Arg0.getAs<Expr>();
12397 Args[1] = RHS = Arg1.getAs<Expr>();
12398 }
12399
12400 // Build the actual expression node.
12401 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12402 Best->FoundDecl, Base,
12403 HadMultipleCandidates, OpLoc);
12404 if (FnExpr.isInvalid())
12405 return ExprError();
12406
12407 // Determine the result type.
12408 QualType ResultTy = FnDecl->getReturnType();
12409 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12410 ResultTy = ResultTy.getNonLValueExprType(Context);
12411
12412 CXXOperatorCallExpr *TheCall =
12413 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12414 Args, ResultTy, VK, OpLoc,
12415 FPFeatures);
12416
12417 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12418 FnDecl))
12419 return ExprError();
12420
12421 ArrayRef<const Expr *> ArgsArray(Args, 2);
12422 const Expr *ImplicitThis = nullptr;
12423 // Cut off the implicit 'this'.
12424 if (isa<CXXMethodDecl>(FnDecl)) {
12425 ImplicitThis = ArgsArray[0];
12426 ArgsArray = ArgsArray.slice(1);
12427 }
12428
12429 // Check for a self move.
12430 if (Op == OO_Equal)
12431 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12432
12433 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12434 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12435 VariadicDoesNotApply);
12436
12437 return MaybeBindToTemporary(TheCall);
12438 } else {
12439 // We matched a built-in operator. Convert the arguments, then
12440 // break out so that we will build the appropriate built-in
12441 // operator node.
12442 ExprResult ArgsRes0 = PerformImplicitConversion(
12443 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12444 AA_Passing, CCK_ForBuiltinOverloadedOp);
12445 if (ArgsRes0.isInvalid())
12446 return ExprError();
12447 Args[0] = ArgsRes0.get();
12448
12449 ExprResult ArgsRes1 = PerformImplicitConversion(
12450 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12451 AA_Passing, CCK_ForBuiltinOverloadedOp);
12452 if (ArgsRes1.isInvalid())
12453 return ExprError();
12454 Args[1] = ArgsRes1.get();
12455 break;
12456 }
12457 }
12458
12459 case OR_No_Viable_Function: {
12460 // C++ [over.match.oper]p9:
12461 // If the operator is the operator , [...] and there are no
12462 // viable functions, then the operator is assumed to be the
12463 // built-in operator and interpreted according to clause 5.
12464 if (Opc == BO_Comma)
12465 break;
12466
12467 // For class as left operand for assignment or compound assignment
12468 // operator do not fall through to handling in built-in, but report that
12469 // no overloaded assignment operator found
12470 ExprResult Result = ExprError();
12471 if (Args[0]->getType()->isRecordType() &&
12472 Opc >= BO_Assign && Opc <= BO_OrAssign) {
12473 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12474 << BinaryOperator::getOpcodeStr(Opc)
12475 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12476 if (Args[0]->getType()->isIncompleteType()) {
12477 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12478 << Args[0]->getType()
12479 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12480 }
12481 } else {
12482 // This is an erroneous use of an operator which can be overloaded by
12483 // a non-member function. Check for non-member operators which were
12484 // defined too late to be candidates.
12485 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12486 // FIXME: Recover by calling the found function.
12487 return ExprError();
12488
12489 // No viable function; try to create a built-in operation, which will
12490 // produce an error. Then, show the non-viable candidates.
12491 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12492 }
12493 assert(Result.isInvalid() &&(static_cast <bool> (Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? void (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 12494, __extension__ __PRETTY_FUNCTION__))
12494 "C++ binary operator overloading is missing candidates!")(static_cast <bool> (Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? void (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 12494, __extension__ __PRETTY_FUNCTION__))
;
12495 if (Result.isInvalid())
12496 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12497 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12498 return Result;
12499 }
12500
12501 case OR_Ambiguous:
12502 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
12503 << BinaryOperator::getOpcodeStr(Opc)
12504 << Args[0]->getType() << Args[1]->getType()
12505 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12506 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12507 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12508 return ExprError();
12509
12510 case OR_Deleted:
12511 if (isImplicitlyDeleted(Best->Function)) {
12512 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12513 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12514 << Context.getRecordType(Method->getParent())
12515 << getSpecialMember(Method);
12516
12517 // The user probably meant to call this special member. Just
12518 // explain why it's deleted.
12519 NoteDeletedFunction(Method);
12520 return ExprError();
12521 } else {
12522 Diag(OpLoc, diag::err_ovl_deleted_oper)
12523 << Best->Function->isDeleted()
12524 << BinaryOperator::getOpcodeStr(Opc)
12525 << getDeletedOrUnavailableSuffix(Best->Function)
12526 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12527 }
12528 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12529 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12530 return ExprError();
12531 }
12532
12533 // We matched a built-in operator; build it.
12534 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12535}
12536
12537ExprResult
12538Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12539 SourceLocation RLoc,
12540 Expr *Base, Expr *Idx) {
12541 Expr *Args[2] = { Base, Idx };
12542 DeclarationName OpName =
12543 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12544
12545 // If either side is type-dependent, create an appropriate dependent
12546 // expression.
12547 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12548
12549 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12550 // CHECKME: no 'operator' keyword?
12551 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12552 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12553 UnresolvedLookupExpr *Fn
12554 = UnresolvedLookupExpr::Create(Context, NamingClass,
12555 NestedNameSpecifierLoc(), OpNameInfo,
12556 /*ADL*/ true, /*Overloaded*/ false,
12557 UnresolvedSetIterator(),
12558 UnresolvedSetIterator());
12559 // Can't add any actual overloads yet
12560
12561 return new (Context)
12562 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12563 Context.DependentTy, VK_RValue, RLoc, FPOptions());
12564 }
12565
12566 // Handle placeholders on both operands.
12567 if (checkPlaceholderForOverload(*this, Args[0]))
12568 return ExprError();
12569 if (checkPlaceholderForOverload(*this, Args[1]))
12570 return ExprError();
12571
12572 // Build an empty overload set.
12573 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12574
12575 // Subscript can only be overloaded as a member function.
12576
12577 // Add operator candidates that are member functions.
12578 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12579
12580 // Add builtin operator candidates.
12581 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12582
12583 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12584
12585 // Perform overload resolution.
12586 OverloadCandidateSet::iterator Best;
12587 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12588 case OR_Success: {
12589 // We found a built-in operator or an overloaded operator.
12590 FunctionDecl *FnDecl = Best->Function;
12591
12592 if (FnDecl) {
12593 // We matched an overloaded operator. Build a call to that
12594 // operator.
12595
12596 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12597
12598 // Convert the arguments.
12599 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12600 ExprResult Arg0 =
12601 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12602 Best->FoundDecl, Method);
12603 if (Arg0.isInvalid())
12604 return ExprError();
12605 Args[0] = Arg0.get();
12606
12607 // Convert the arguments.
12608 ExprResult InputInit
12609 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12610 Context,
12611 FnDecl->getParamDecl(0)),
12612 SourceLocation(),
12613 Args[1]);
12614 if (InputInit.isInvalid())
12615 return ExprError();
12616
12617 Args[1] = InputInit.getAs<Expr>();
12618
12619 // Build the actual expression node.
12620 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12621 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12622 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12623 Best->FoundDecl,
12624 Base,
12625 HadMultipleCandidates,
12626 OpLocInfo.getLoc(),
12627 OpLocInfo.getInfo());
12628 if (FnExpr.isInvalid())
12629 return ExprError();
12630
12631 // Determine the result type
12632 QualType ResultTy = FnDecl->getReturnType();
12633 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12634 ResultTy = ResultTy.getNonLValueExprType(Context);
12635
12636 CXXOperatorCallExpr *TheCall =
12637 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12638 FnExpr.get(), Args,
12639 ResultTy, VK, RLoc,
12640 FPOptions());
12641
12642 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12643 return ExprError();
12644
12645 if (CheckFunctionCall(Method, TheCall,
12646 Method->getType()->castAs<FunctionProtoType>()))
12647 return ExprError();
12648
12649 return MaybeBindToTemporary(TheCall);
12650 } else {
12651 // We matched a built-in operator. Convert the arguments, then
12652 // break out so that we will build the appropriate built-in
12653 // operator node.
12654 ExprResult ArgsRes0 = PerformImplicitConversion(
12655 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12656 AA_Passing, CCK_ForBuiltinOverloadedOp);
12657 if (ArgsRes0.isInvalid())
12658 return ExprError();
12659 Args[0] = ArgsRes0.get();
12660
12661 ExprResult ArgsRes1 = PerformImplicitConversion(
12662 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12663 AA_Passing, CCK_ForBuiltinOverloadedOp);
12664 if (ArgsRes1.isInvalid())
12665 return ExprError();
12666 Args[1] = ArgsRes1.get();
12667
12668 break;
12669 }
12670 }
12671
12672 case OR_No_Viable_Function: {
12673 if (CandidateSet.empty())
12674 Diag(LLoc, diag::err_ovl_no_oper)
12675 << Args[0]->getType() << /*subscript*/ 0
12676 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12677 else
12678 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12679 << Args[0]->getType()
12680 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12681 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12682 "[]", LLoc);
12683 return ExprError();
12684 }
12685
12686 case OR_Ambiguous:
12687 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
12688 << "[]"
12689 << Args[0]->getType() << Args[1]->getType()
12690 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12691 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12692 "[]", LLoc);
12693 return ExprError();
12694
12695 case OR_Deleted:
12696 Diag(LLoc, diag::err_ovl_deleted_oper)
12697 << Best->Function->isDeleted() << "[]"
12698 << getDeletedOrUnavailableSuffix(Best->Function)
12699 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12700 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12701 "[]", LLoc);
12702 return ExprError();
12703 }
12704
12705 // We matched a built-in operator; build it.
12706 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12707}
12708
12709/// BuildCallToMemberFunction - Build a call to a member
12710/// function. MemExpr is the expression that refers to the member
12711/// function (and includes the object parameter), Args/NumArgs are the
12712/// arguments to the function call (not including the object
12713/// parameter). The caller needs to validate that the member
12714/// expression refers to a non-static member function or an overloaded
12715/// member function.
12716ExprResult
12717Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12718 SourceLocation LParenLoc,
12719 MultiExprArg Args,
12720 SourceLocation RParenLoc) {
12721 assert(MemExprE->getType() == Context.BoundMemberTy ||(static_cast <bool> (MemExprE->getType() == Context.
BoundMemberTy || MemExprE->getType() == Context.OverloadTy
) ? void (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 12722, __extension__ __PRETTY_FUNCTION__))
12722 MemExprE->getType() == Context.OverloadTy)(static_cast <bool> (MemExprE->getType() == Context.
BoundMemberTy || MemExprE->getType() == Context.OverloadTy
) ? void (0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 12722, __extension__ __PRETTY_FUNCTION__))
;
12723
12724 // Dig out the member expression. This holds both the object
12725 // argument and the member function we're referring to.
12726 Expr *NakedMemExpr = MemExprE->IgnoreParens();
12727
12728 // Determine whether this is a call to a pointer-to-member function.
12729 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12730 assert(op->getType() == Context.BoundMemberTy)(static_cast <bool> (op->getType() == Context.BoundMemberTy
) ? void (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 12730, __extension__ __PRETTY_FUNCTION__))
;
12731 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)(static_cast <bool> (op->getOpcode() == BO_PtrMemD ||
op->getOpcode() == BO_PtrMemI) ? void (0) : __assert_fail
("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 12731, __extension__ __PRETTY_FUNCTION__))
;
12732
12733 QualType fnType =
12734 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12735
12736 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12737 QualType resultType = proto->getCallResultType(Context);
12738 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12739
12740 // Check that the object type isn't more qualified than the
12741 // member function we're calling.
12742 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12743
12744 QualType objectType = op->getLHS()->getType();
12745 if (op->getOpcode() == BO_PtrMemI)
12746 objectType = objectType->castAs<PointerType>()->getPointeeType();
12747 Qualifiers objectQuals = objectType.getQualifiers();
12748
12749 Qualifiers difference = objectQuals - funcQuals;
12750 difference.removeObjCGCAttr();
12751 difference.removeAddressSpace();
12752 if (difference) {
12753 std::string qualsString = difference.getAsString();
12754 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12755 << fnType.getUnqualifiedType()
12756 << qualsString
12757 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12758 }
12759
12760 CXXMemberCallExpr *call
12761 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12762 resultType, valueKind, RParenLoc);
12763
12764 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12765 call, nullptr))
12766 return ExprError();
12767
12768 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12769 return ExprError();
12770
12771 if (CheckOtherCall(call, proto))
12772 return ExprError();
12773
12774 return MaybeBindToTemporary(call);
12775 }
12776
12777 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12778 return new (Context)
12779 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12780
12781 UnbridgedCastsSet UnbridgedCasts;
12782 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12783 return ExprError();
12784
12785 MemberExpr *MemExpr;
12786 CXXMethodDecl *Method = nullptr;
12787 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12788 NestedNameSpecifier *Qualifier = nullptr;
12789 if (isa<MemberExpr>(NakedMemExpr)) {
12790 MemExpr = cast<MemberExpr>(NakedMemExpr);
12791 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12792 FoundDecl = MemExpr->getFoundDecl();
12793 Qualifier = MemExpr->getQualifier();
12794 UnbridgedCasts.restore();
12795 } else {
12796 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12797 Qualifier = UnresExpr->getQualifier();
12798
12799 QualType ObjectType = UnresExpr->getBaseType();
12800 Expr::Classification ObjectClassification
12801 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12802 : UnresExpr->getBase()->Classify(Context);
12803
12804 // Add overload candidates
12805 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12806 OverloadCandidateSet::CSK_Normal);
12807
12808 // FIXME: avoid copy.
12809 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12810 if (UnresExpr->hasExplicitTemplateArgs()) {
12811 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12812 TemplateArgs = &TemplateArgsBuffer;
12813 }
12814
12815 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12816 E = UnresExpr->decls_end(); I != E; ++I) {
12817
12818 NamedDecl *Func = *I;
12819 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12820 if (isa<UsingShadowDecl>(Func))
12821 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12822
12823
12824 // Microsoft supports direct constructor calls.
12825 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12826 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12827 Args, CandidateSet);
12828 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12829 // If explicit template arguments were provided, we can't call a
12830 // non-template member function.
12831 if (TemplateArgs)
12832 continue;
12833
12834 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12835 ObjectClassification, Args, CandidateSet,
12836 /*SuppressUserConversions=*/false);
12837 } else {
12838 AddMethodTemplateCandidate(
12839 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12840 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12841 /*SuppressUsedConversions=*/false);
12842 }
12843 }
12844
12845 DeclarationName DeclName = UnresExpr->getMemberName();
12846
12847 UnbridgedCasts.restore();
12848
12849 OverloadCandidateSet::iterator Best;
12850 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12851 Best)) {
12852 case OR_Success:
12853 Method = cast<CXXMethodDecl>(Best->Function);
12854 FoundDecl = Best->FoundDecl;
12855 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12856 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12857 return ExprError();
12858 // If FoundDecl is different from Method (such as if one is a template
12859 // and the other a specialization), make sure DiagnoseUseOfDecl is
12860 // called on both.
12861 // FIXME: This would be more comprehensively addressed by modifying
12862 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12863 // being used.
12864 if (Method != FoundDecl.getDecl() &&
12865 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12866 return ExprError();
12867 break;
12868
12869 case OR_No_Viable_Function:
12870 Diag(UnresExpr->getMemberLoc(),
12871 diag::err_ovl_no_viable_member_function_in_call)
12872 << DeclName << MemExprE->getSourceRange();
12873 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12874 // FIXME: Leaking incoming expressions!
12875 return ExprError();
12876
12877 case OR_Ambiguous:
12878 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12879 << DeclName << MemExprE->getSourceRange();
12880 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12881 // FIXME: Leaking incoming expressions!
12882 return ExprError();
12883
12884 case OR_Deleted:
12885 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12886 << Best->Function->isDeleted()
12887 << DeclName
12888 << getDeletedOrUnavailableSuffix(Best->Function)
12889 << MemExprE->getSourceRange();
12890 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12891 // FIXME: Leaking incoming expressions!
12892 return ExprError();
12893 }
12894
12895 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12896
12897 // If overload resolution picked a static member, build a
12898 // non-member call based on that function.
12899 if (Method->isStatic()) {
12900 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12901 RParenLoc);
12902 }
12903
12904 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12905 }
12906
12907 QualType ResultType = Method->getReturnType();
12908 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12909 ResultType = ResultType.getNonLValueExprType(Context);
12910
12911 assert(Method && "Member call to something that isn't a method?")(static_cast <bool> (Method && "Member call to something that isn't a method?"
) ? void (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 12911, __extension__ __PRETTY_FUNCTION__))
;
12912 CXXMemberCallExpr *TheCall =
12913 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12914 ResultType, VK, RParenLoc);
12915
12916 // Check for a valid return type.
12917 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12918 TheCall, Method))
12919 return ExprError();
12920
12921 // Convert the object argument (for a non-static member function call).
12922 // We only need to do this if there was actually an overload; otherwise
12923 // it was done at lookup.
12924 if (!Method->isStatic()) {
12925 ExprResult ObjectArg =
12926 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12927 FoundDecl, Method);
12928 if (ObjectArg.isInvalid())
12929 return ExprError();
12930 MemExpr->setBase(ObjectArg.get());
12931 }
12932
12933 // Convert the rest of the arguments
12934 const FunctionProtoType *Proto =
12935 Method->getType()->getAs<FunctionProtoType>();
12936 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12937 RParenLoc))
12938 return ExprError();
12939
12940 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12941
12942 if (CheckFunctionCall(Method, TheCall, Proto))
12943 return ExprError();
12944
12945 // In the case the method to call was not selected by the overloading
12946 // resolution process, we still need to handle the enable_if attribute. Do
12947 // that here, so it will not hide previous -- and more relevant -- errors.
12948 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12949 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12950 Diag(MemE->getMemberLoc(),
12951 diag::err_ovl_no_viable_member_function_in_call)
12952 << Method << Method->getSourceRange();
12953 Diag(Method->getLocation(),
12954 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12955 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12956 return ExprError();
12957 }
12958 }
12959
12960 if ((isa<CXXConstructorDecl>(CurContext) ||
12961 isa<CXXDestructorDecl>(CurContext)) &&
12962 TheCall->getMethodDecl()->isPure()) {
12963 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12964
12965 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12966 MemExpr->performsVirtualDispatch(getLangOpts())) {
12967 Diag(MemExpr->getLocStart(),
12968 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12969 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12970 << MD->getParent()->getDeclName();
12971
12972 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12973 if (getLangOpts().AppleKext)
12974 Diag(MemExpr->getLocStart(),
12975 diag::note_pure_qualified_call_kext)
12976 << MD->getParent()->getDeclName()
12977 << MD->getDeclName();
12978 }
12979 }
12980
12981 if (CXXDestructorDecl *DD =
12982 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12983 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12984 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12985 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12986 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12987 MemExpr->getMemberLoc());
12988 }
12989
12990 return MaybeBindToTemporary(TheCall);
12991}
12992
12993/// BuildCallToObjectOfClassType - Build a call to an object of class
12994/// type (C++ [over.call.object]), which can end up invoking an
12995/// overloaded function call operator (@c operator()) or performing a
12996/// user-defined conversion on the object argument.
12997ExprResult
12998Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12999 SourceLocation LParenLoc,
13000 MultiExprArg Args,
13001 SourceLocation RParenLoc) {
13002 if (checkPlaceholderForOverload(*this, Obj))
13003 return ExprError();
13004 ExprResult Object = Obj;
13005
13006 UnbridgedCastsSet UnbridgedCasts;
13007 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13008 return ExprError();
13009
13010 assert(Object.get()->getType()->isRecordType() &&(static_cast <bool> (Object.get()->getType()->isRecordType
() && "Requires object type argument") ? void (0) : __assert_fail
("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13011, __extension__ __PRETTY_FUNCTION__))
13011 "Requires object type argument")(static_cast <bool> (Object.get()->getType()->isRecordType
() && "Requires object type argument") ? void (0) : __assert_fail
("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13011, __extension__ __PRETTY_FUNCTION__))
;
13012 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13013
13014 // C++ [over.call.object]p1:
13015 // If the primary-expression E in the function call syntax
13016 // evaluates to a class object of type "cv T", then the set of
13017 // candidate functions includes at least the function call
13018 // operators of T. The function call operators of T are obtained by
13019 // ordinary lookup of the name operator() in the context of
13020 // (E).operator().
13021 OverloadCandidateSet CandidateSet(LParenLoc,
13022 OverloadCandidateSet::CSK_Operator);
13023 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13024
13025 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13026 diag::err_incomplete_object_call, Object.get()))
13027 return true;
13028
13029 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13030 LookupQualifiedName(R, Record->getDecl());
13031 R.suppressDiagnostics();
13032
13033 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13034 Oper != OperEnd; ++Oper) {
13035 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13036 Object.get()->Classify(Context), Args, CandidateSet,
13037 /*SuppressUserConversions=*/false);
13038 }
13039
13040 // C++ [over.call.object]p2:
13041 // In addition, for each (non-explicit in C++0x) conversion function
13042 // declared in T of the form
13043 //
13044 // operator conversion-type-id () cv-qualifier;
13045 //
13046 // where cv-qualifier is the same cv-qualification as, or a
13047 // greater cv-qualification than, cv, and where conversion-type-id
13048 // denotes the type "pointer to function of (P1,...,Pn) returning
13049 // R", or the type "reference to pointer to function of
13050 // (P1,...,Pn) returning R", or the type "reference to function
13051 // of (P1,...,Pn) returning R", a surrogate call function [...]
13052 // is also considered as a candidate function. Similarly,
13053 // surrogate call functions are added to the set of candidate
13054 // functions for each conversion function declared in an
13055 // accessible base class provided the function is not hidden
13056 // within T by another intervening declaration.
13057 const auto &Conversions =
13058 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13059 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13060 NamedDecl *D = *I;
13061 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13062 if (isa<UsingShadowDecl>(D))
13063 D = cast<UsingShadowDecl>(D)->getTargetDecl();
13064
13065 // Skip over templated conversion functions; they aren't
13066 // surrogates.
13067 if (isa<FunctionTemplateDecl>(D))
13068 continue;
13069
13070 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13071 if (!Conv->isExplicit()) {
13072 // Strip the reference type (if any) and then the pointer type (if
13073 // any) to get down to what might be a function type.
13074 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13075 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13076 ConvType = ConvPtrType->getPointeeType();
13077
13078 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13079 {
13080 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13081 Object.get(), Args, CandidateSet);
13082 }
13083 }
13084 }
13085
13086 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13087
13088 // Perform overload resolution.
13089 OverloadCandidateSet::iterator Best;
13090 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13091 Best)) {
13092 case OR_Success:
13093 // Overload resolution succeeded; we'll build the appropriate call
13094 // below.
13095 break;
13096
13097 case OR_No_Viable_Function:
13098 if (CandidateSet.empty())
13099 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13100 << Object.get()->getType() << /*call*/ 1
13101 << Object.get()->getSourceRange();
13102 else
13103 Diag(Object.get()->getLocStart(),
13104 diag::err_ovl_no_viable_object_call)
13105 << Object.get()->getType() << Object.get()->getSourceRange();
13106 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13107 break;
13108
13109 case OR_Ambiguous:
13110 Diag(Object.get()->getLocStart(),
13111 diag::err_ovl_ambiguous_object_call)
13112 << Object.get()->getType() << Object.get()->getSourceRange();
13113 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13114 break;
13115
13116 case OR_Deleted:
13117 Diag(Object.get()->getLocStart(),
13118 diag::err_ovl_deleted_object_call)
13119 << Best->Function->isDeleted()
13120 << Object.get()->getType()
13121 << getDeletedOrUnavailableSuffix(Best->Function)
13122 << Object.get()->getSourceRange();
13123 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13124 break;
13125 }
13126
13127 if (Best == CandidateSet.end())
13128 return true;
13129
13130 UnbridgedCasts.restore();
13131
13132 if (Best->Function == nullptr) {
13133 // Since there is no function declaration, this is one of the
13134 // surrogate candidates. Dig out the conversion function.
13135 CXXConversionDecl *Conv
13136 = cast<CXXConversionDecl>(
13137 Best->Conversions[0].UserDefined.ConversionFunction);
13138
13139 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13140 Best->FoundDecl);
13141 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13142 return ExprError();
13143 assert(Conv == Best->FoundDecl.getDecl() &&(static_cast <bool> (Conv == Best->FoundDecl.getDecl
() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? void (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13144, __extension__ __PRETTY_FUNCTION__))
13144 "Found Decl & conversion-to-functionptr should be same, right?!")(static_cast <bool> (Conv == Best->FoundDecl.getDecl
() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? void (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13144, __extension__ __PRETTY_FUNCTION__))
;
13145 // We selected one of the surrogate functions that converts the
13146 // object parameter to a function pointer. Perform the conversion
13147 // on the object argument, then let ActOnCallExpr finish the job.
13148
13149 // Create an implicit member expr to refer to the conversion operator.
13150 // and then call it.
13151 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13152 Conv, HadMultipleCandidates);
13153 if (Call.isInvalid())
13154 return ExprError();
13155 // Record usage of conversion in an implicit cast.
13156 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13157 CK_UserDefinedConversion, Call.get(),
13158 nullptr, VK_RValue);
13159
13160 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13161 }
13162
13163 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13164
13165 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13166 // that calls this method, using Object for the implicit object
13167 // parameter and passing along the remaining arguments.
13168 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13169
13170 // An error diagnostic has already been printed when parsing the declaration.
13171 if (Method->isInvalidDecl())
13172 return ExprError();
13173
13174 const FunctionProtoType *Proto =
13175 Method->getType()->getAs<FunctionProtoType>();
13176
13177 unsigned NumParams = Proto->getNumParams();
13178
13179 DeclarationNameInfo OpLocInfo(
13180 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13181 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13182 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13183 Obj, HadMultipleCandidates,
13184 OpLocInfo.getLoc(),
13185 OpLocInfo.getInfo());
13186 if (NewFn.isInvalid())
13187 return true;
13188
13189 // Build the full argument list for the method call (the implicit object
13190 // parameter is placed at the beginning of the list).
13191 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13192 MethodArgs[0] = Object.get();
13193 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13194
13195 // Once we've built TheCall, all of the expressions are properly
13196 // owned.
13197 QualType ResultTy = Method->getReturnType();
13198 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13199 ResultTy = ResultTy.getNonLValueExprType(Context);
13200
13201 CXXOperatorCallExpr *TheCall = new (Context)
13202 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13203 VK, RParenLoc, FPOptions());
13204
13205 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13206 return true;
13207
13208 // We may have default arguments. If so, we need to allocate more
13209 // slots in the call for them.
13210 if (Args.size() < NumParams)
13211 TheCall->setNumArgs(Context, NumParams + 1);
13212
13213 bool IsError = false;
13214
13215 // Initialize the implicit object parameter.
13216 ExprResult ObjRes =
13217 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13218 Best->FoundDecl, Method);
13219 if (ObjRes.isInvalid())
13220 IsError = true;
13221 else
13222 Object = ObjRes;
13223 TheCall->setArg(0, Object.get());
13224
13225 // Check the argument types.
13226 for (unsigned i = 0; i != NumParams; i++) {
13227 Expr *Arg;
13228 if (i < Args.size()) {
13229 Arg = Args[i];
13230
13231 // Pass the argument.
13232
13233 ExprResult InputInit
13234 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13235 Context,
13236 Method->getParamDecl(i)),
13237 SourceLocation(), Arg);
13238
13239 IsError |= InputInit.isInvalid();
13240 Arg = InputInit.getAs<Expr>();
13241 } else {
13242 ExprResult DefArg
13243 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13244 if (DefArg.isInvalid()) {
13245 IsError = true;
13246 break;
13247 }
13248
13249 Arg = DefArg.getAs<Expr>();
13250 }
13251
13252 TheCall->setArg(i + 1, Arg);
13253 }
13254
13255 // If this is a variadic call, handle args passed through "...".
13256 if (Proto->isVariadic()) {
13257 // Promote the arguments (C99 6.5.2.2p7).
13258 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13259 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13260 nullptr);
13261 IsError |= Arg.isInvalid();
13262 TheCall->setArg(i + 1, Arg.get());
13263 }
13264 }
13265
13266 if (IsError) return true;
13267
13268 DiagnoseSentinelCalls(Method, LParenLoc, Args);
13269
13270 if (CheckFunctionCall(Method, TheCall, Proto))
13271 return true;
13272
13273 return MaybeBindToTemporary(TheCall);
13274}
13275
13276/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13277/// (if one exists), where @c Base is an expression of class type and
13278/// @c Member is the name of the member we're trying to find.
13279ExprResult
13280Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13281 bool *NoArrowOperatorFound) {
13282 assert(Base->getType()->isRecordType() &&(static_cast <bool> (Base->getType()->isRecordType
() && "left-hand side must have class type") ? void (
0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13283, __extension__ __PRETTY_FUNCTION__))
13283 "left-hand side must have class type")(static_cast <bool> (Base->getType()->isRecordType
() && "left-hand side must have class type") ? void (
0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13283, __extension__ __PRETTY_FUNCTION__))
;
13284
13285 if (checkPlaceholderForOverload(*this, Base))
13286 return ExprError();
13287
13288 SourceLocation Loc = Base->getExprLoc();
13289
13290 // C++ [over.ref]p1:
13291 //
13292 // [...] An expression x->m is interpreted as (x.operator->())->m
13293 // for a class object x of type T if T::operator->() exists and if
13294 // the operator is selected as the best match function by the
13295 // overload resolution mechanism (13.3).
13296 DeclarationName OpName =
13297 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13298 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13299 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13300
13301 if (RequireCompleteType(Loc, Base->getType(),
13302 diag::err_typecheck_incomplete_tag, Base))
13303 return ExprError();
13304
13305 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13306 LookupQualifiedName(R, BaseRecord->getDecl());
13307 R.suppressDiagnostics();
13308
13309 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13310 Oper != OperEnd; ++Oper) {
13311 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13312 None, CandidateSet, /*SuppressUserConversions=*/false);
13313 }
13314
13315 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13316
13317 // Perform overload resolution.
13318 OverloadCandidateSet::iterator Best;
13319 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13320 case OR_Success:
13321 // Overload resolution succeeded; we'll build the call below.
13322 break;
13323
13324 case OR_No_Viable_Function:
13325 if (CandidateSet.empty()) {
13326 QualType BaseType = Base->getType();
13327 if (NoArrowOperatorFound) {
13328 // Report this specific error to the caller instead of emitting a
13329 // diagnostic, as requested.
13330 *NoArrowOperatorFound = true;
13331 return ExprError();
13332 }
13333 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13334 << BaseType << Base->getSourceRange();
13335 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13336 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13337 << FixItHint::CreateReplacement(OpLoc, ".");
13338 }
13339 } else
13340 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13341 << "operator->" << Base->getSourceRange();
13342 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13343 return ExprError();
13344
13345 case OR_Ambiguous:
13346 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13347 << "->" << Base->getType() << Base->getSourceRange();
13348 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13349 return ExprError();
13350
13351 case OR_Deleted:
13352 Diag(OpLoc, diag::err_ovl_deleted_oper)
13353 << Best->Function->isDeleted()
13354 << "->"
13355 << getDeletedOrUnavailableSuffix(Best->Function)
13356 << Base->getSourceRange();
13357 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13358 return ExprError();
13359 }
13360
13361 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13362
13363 // Convert the object parameter.
13364 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13365 ExprResult BaseResult =
13366 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13367 Best->FoundDecl, Method);
13368 if (BaseResult.isInvalid())
13369 return ExprError();
13370 Base = BaseResult.get();
13371
13372 // Build the operator call.
13373 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13374 Base, HadMultipleCandidates, OpLoc);
13375 if (FnExpr.isInvalid())
13376 return ExprError();
13377
13378 QualType ResultTy = Method->getReturnType();
13379 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13380 ResultTy = ResultTy.getNonLValueExprType(Context);
13381 CXXOperatorCallExpr *TheCall =
13382 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13383 Base, ResultTy, VK, OpLoc, FPOptions());
13384
13385 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13386 return ExprError();
13387
13388 if (CheckFunctionCall(Method, TheCall,
13389 Method->getType()->castAs<FunctionProtoType>()))
13390 return ExprError();
13391
13392 return MaybeBindToTemporary(TheCall);
13393}
13394
13395/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13396/// a literal operator described by the provided lookup results.
13397ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13398 DeclarationNameInfo &SuffixInfo,
13399 ArrayRef<Expr*> Args,
13400 SourceLocation LitEndLoc,
13401 TemplateArgumentListInfo *TemplateArgs) {
13402 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13403
13404 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13405 OverloadCandidateSet::CSK_Normal);
13406 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13407 /*SuppressUserConversions=*/true);
13408
13409 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13410
13411 // Perform overload resolution. This will usually be trivial, but might need
13412 // to perform substitutions for a literal operator template.
13413 OverloadCandidateSet::iterator Best;
13414 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13415 case OR_Success:
13416 case OR_Deleted:
13417 break;
13418
13419 case OR_No_Viable_Function:
13420 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13421 << R.getLookupName();
13422 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13423 return ExprError();
13424
13425 case OR_Ambiguous:
13426 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13427 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13428 return ExprError();
13429 }
13430
13431 FunctionDecl *FD = Best->Function;
13432 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13433 nullptr, HadMultipleCandidates,
13434 SuffixInfo.getLoc(),
13435 SuffixInfo.getInfo());
13436 if (Fn.isInvalid())
13437 return true;
13438
13439 // Check the argument types. This should almost always be a no-op, except
13440 // that array-to-pointer decay is applied to string literals.
13441 Expr *ConvArgs[2];
13442 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13443 ExprResult InputInit = PerformCopyInitialization(
13444 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13445 SourceLocation(), Args[ArgIdx]);
13446 if (InputInit.isInvalid())
13447 return true;
13448 ConvArgs[ArgIdx] = InputInit.get();
13449 }
13450
13451 QualType ResultTy = FD->getReturnType();
13452 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13453 ResultTy = ResultTy.getNonLValueExprType(Context);
13454
13455 UserDefinedLiteral *UDL =
13456 new (Context) UserDefinedLiteral(Context, Fn.get(),
13457 llvm::makeArrayRef(ConvArgs, Args.size()),
13458 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13459
13460 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13461 return ExprError();
13462
13463 if (CheckFunctionCall(FD, UDL, nullptr))
13464 return ExprError();
13465
13466 return MaybeBindToTemporary(UDL);
13467}
13468
13469/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13470/// given LookupResult is non-empty, it is assumed to describe a member which
13471/// will be invoked. Otherwise, the function will be found via argument
13472/// dependent lookup.
13473/// CallExpr is set to a valid expression and FRS_Success returned on success,
13474/// otherwise CallExpr is set to ExprError() and some non-success value
13475/// is returned.
13476Sema::ForRangeStatus
13477Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13478 SourceLocation RangeLoc,
13479 const DeclarationNameInfo &NameInfo,
13480 LookupResult &MemberLookup,
13481 OverloadCandidateSet *CandidateSet,
13482 Expr *Range, ExprResult *CallExpr) {
13483 Scope *S = nullptr;
13484
13485 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13486 if (!MemberLookup.empty()) {
13487 ExprResult MemberRef =
13488 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13489 /*IsPtr=*/false, CXXScopeSpec(),
13490 /*TemplateKWLoc=*/SourceLocation(),
13491 /*FirstQualifierInScope=*/nullptr,
13492 MemberLookup,
13493 /*TemplateArgs=*/nullptr, S);
13494 if (MemberRef.isInvalid()) {
13495 *CallExpr = ExprError();
13496 return FRS_DiagnosticIssued;
13497 }
13498 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13499 if (CallExpr->isInvalid()) {
13500 *CallExpr = ExprError();
13501 return FRS_DiagnosticIssued;
13502 }
13503 } else {
13504 UnresolvedSet<0> FoundNames;
13505 UnresolvedLookupExpr *Fn =
13506 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13507 NestedNameSpecifierLoc(), NameInfo,
13508 /*NeedsADL=*/true, /*Overloaded=*/false,
13509 FoundNames.begin(), FoundNames.end());
13510
13511 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13512 CandidateSet, CallExpr);
13513 if (CandidateSet->empty() || CandidateSetError) {
13514 *CallExpr = ExprError();
13515 return FRS_NoViableFunction;
13516 }
13517 OverloadCandidateSet::iterator Best;
13518 OverloadingResult OverloadResult =
13519 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13520
13521 if (OverloadResult == OR_No_Viable_Function) {
13522 *CallExpr = ExprError();
13523 return FRS_NoViableFunction;
13524 }
13525 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13526 Loc, nullptr, CandidateSet, &Best,
13527 OverloadResult,
13528 /*AllowTypoCorrection=*/false);
13529 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13530 *CallExpr = ExprError();
13531 return FRS_DiagnosticIssued;
13532 }
13533 }
13534 return FRS_Success;
13535}
13536
13537
13538/// FixOverloadedFunctionReference - E is an expression that refers to
13539/// a C++ overloaded function (possibly with some parentheses and
13540/// perhaps a '&' around it). We have resolved the overloaded function
13541/// to the function declaration Fn, so patch up the expression E to
13542/// refer (possibly indirectly) to Fn. Returns the new expr.
13543Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13544 FunctionDecl *Fn) {
13545 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13546 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13547 Found, Fn);
13548 if (SubExpr == PE->getSubExpr())
13549 return PE;
13550
13551 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13552 }
13553
13554 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13555 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13556 Found, Fn);
13557 assert(Context.hasSameType(ICE->getSubExpr()->getType(),(static_cast <bool> (Context.hasSameType(ICE->getSubExpr
()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload"
) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13559, __extension__ __PRETTY_FUNCTION__))
13558 SubExpr->getType()) &&(static_cast <bool> (Context.hasSameType(ICE->getSubExpr
()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload"
) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13559, __extension__ __PRETTY_FUNCTION__))
13559 "Implicit cast type cannot be determined from overload")(static_cast <bool> (Context.hasSameType(ICE->getSubExpr
()->getType(), SubExpr->getType()) && "Implicit cast type cannot be determined from overload"
) ? void (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13559, __extension__ __PRETTY_FUNCTION__))
;
13560 assert(ICE->path_empty() && "fixing up hierarchy conversion?")(static_cast <bool> (ICE->path_empty() && "fixing up hierarchy conversion?"
) ? void (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13560, __extension__ __PRETTY_FUNCTION__))
;
13561 if (SubExpr == ICE->getSubExpr())
13562 return ICE;
13563
13564 return ImplicitCastExpr::Create(Context, ICE->getType(),
13565 ICE->getCastKind(),
13566 SubExpr, nullptr,
13567 ICE->getValueKind());
13568 }
13569
13570 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13571 if (!GSE->isResultDependent()) {
13572 Expr *SubExpr =
13573 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13574 if (SubExpr == GSE->getResultExpr())
13575 return GSE;
13576
13577 // Replace the resulting type information before rebuilding the generic
13578 // selection expression.
13579 ArrayRef<Expr *> A = GSE->getAssocExprs();
13580 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13581 unsigned ResultIdx = GSE->getResultIndex();
13582 AssocExprs[ResultIdx] = SubExpr;
13583
13584 return new (Context) GenericSelectionExpr(
13585 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13586 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13587 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13588 ResultIdx);
13589 }
13590 // Rather than fall through to the unreachable, return the original generic
13591 // selection expression.
13592 return GSE;
13593 }
13594
13595 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13596 assert(UnOp->getOpcode() == UO_AddrOf &&(static_cast <bool> (UnOp->getOpcode() == UO_AddrOf &&
"Can only take the address of an overloaded function") ? void
(0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13597, __extension__ __PRETTY_FUNCTION__))
13597 "Can only take the address of an overloaded function")(static_cast <bool> (UnOp->getOpcode() == UO_AddrOf &&
"Can only take the address of an overloaded function") ? void
(0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13597, __extension__ __PRETTY_FUNCTION__))
;
13598 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13599 if (Method->isStatic()) {
13600 // Do nothing: static member functions aren't any different
13601 // from non-member functions.
13602 } else {
13603 // Fix the subexpression, which really has to be an
13604 // UnresolvedLookupExpr holding an overloaded member function
13605 // or template.
13606 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13607 Found, Fn);
13608 if (SubExpr == UnOp->getSubExpr())
13609 return UnOp;
13610
13611 assert(isa<DeclRefExpr>(SubExpr)(static_cast <bool> (isa<DeclRefExpr>(SubExpr) &&
"fixed to something other than a decl ref") ? void (0) : __assert_fail
("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13612, __extension__ __PRETTY_FUNCTION__))
13612 && "fixed to something other than a decl ref")(static_cast <bool> (isa<DeclRefExpr>(SubExpr) &&
"fixed to something other than a decl ref") ? void (0) : __assert_fail
("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13612, __extension__ __PRETTY_FUNCTION__))
;
13613 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()(static_cast <bool> (cast<DeclRefExpr>(SubExpr)->
getQualifier() && "fixed to a member ref with no nested name qualifier"
) ? void (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13614, __extension__ __PRETTY_FUNCTION__))
13614 && "fixed to a member ref with no nested name qualifier")(static_cast <bool> (cast<DeclRefExpr>(SubExpr)->
getQualifier() && "fixed to a member ref with no nested name qualifier"
) ? void (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13614, __extension__ __PRETTY_FUNCTION__))
;
13615
13616 // We have taken the address of a pointer to member
13617 // function. Perform the computation here so that we get the
13618 // appropriate pointer to member type.
13619 QualType ClassType
13620 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13621 QualType MemPtrType
13622 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13623 // Under the MS ABI, lock down the inheritance model now.
13624 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13625 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13626
13627 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13628 VK_RValue, OK_Ordinary,
13629 UnOp->getOperatorLoc(), false);
13630 }
13631 }
13632 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13633 Found, Fn);
13634 if (SubExpr == UnOp->getSubExpr())
13635 return UnOp;
13636
13637 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13638 Context.getPointerType(SubExpr->getType()),
13639 VK_RValue, OK_Ordinary,
13640 UnOp->getOperatorLoc(), false);
13641 }
13642
13643 // C++ [except.spec]p17:
13644 // An exception-specification is considered to be needed when:
13645 // - in an expression the function is the unique lookup result or the
13646 // selected member of a set of overloaded functions
13647 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13648 ResolveExceptionSpec(E->getExprLoc(), FPT);
13649
13650 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13651 // FIXME: avoid copy.
13652 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13653 if (ULE->hasExplicitTemplateArgs()) {
13654 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13655 TemplateArgs = &TemplateArgsBuffer;
13656 }
13657
13658 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13659 ULE->getQualifierLoc(),
13660 ULE->getTemplateKeywordLoc(),
13661 Fn,
13662 /*enclosing*/ false, // FIXME?
13663 ULE->getNameLoc(),
13664 Fn->getType(),
13665 VK_LValue,
13666 Found.getDecl(),
13667 TemplateArgs);
13668 MarkDeclRefReferenced(DRE);
13669 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13670 return DRE;
13671 }
13672
13673 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13674 // FIXME: avoid copy.
13675 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13676 if (MemExpr->hasExplicitTemplateArgs()) {
13677 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13678 TemplateArgs = &TemplateArgsBuffer;
13679 }
13680
13681 Expr *Base;
13682
13683 // If we're filling in a static method where we used to have an
13684 // implicit member access, rewrite to a simple decl ref.
13685 if (MemExpr->isImplicitAccess()) {
13686 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13687 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13688 MemExpr->getQualifierLoc(),
13689 MemExpr->getTemplateKeywordLoc(),
13690 Fn,
13691 /*enclosing*/ false,
13692 MemExpr->getMemberLoc(),
13693 Fn->getType(),
13694 VK_LValue,
13695 Found.getDecl(),
13696 TemplateArgs);
13697 MarkDeclRefReferenced(DRE);
13698 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13699 return DRE;
13700 } else {
13701 SourceLocation Loc = MemExpr->getMemberLoc();
13702 if (MemExpr->getQualifier())
13703 Loc = MemExpr->getQualifierLoc().getBeginLoc();
13704 CheckCXXThisCapture(Loc);
13705 Base = new (Context) CXXThisExpr(Loc,
13706 MemExpr->getBaseType(),
13707 /*isImplicit=*/true);
13708 }
13709 } else
13710 Base = MemExpr->getBase();
13711
13712 ExprValueKind valueKind;
13713 QualType type;
13714 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13715 valueKind = VK_LValue;
13716 type = Fn->getType();
13717 } else {
13718 valueKind = VK_RValue;
13719 type = Context.BoundMemberTy;
13720 }
13721
13722 MemberExpr *ME = MemberExpr::Create(
13723 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13724 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13725 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13726 OK_Ordinary);
13727 ME->setHadMultipleCandidates(true);
13728 MarkMemberReferenced(ME);
13729 return ME;
13730 }
13731
13732 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Sema/SemaOverload.cpp"
, 13732)
;
13733}
13734
13735ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13736 DeclAccessPair Found,
13737 FunctionDecl *Fn) {
13738 return FixOverloadedFunctionReference(E.get(), Found, Fn);
13739}