Bug Summary

File:tools/clang/lib/Sema/SemaOverload.cpp
Warning:line 638, 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~svn338205/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/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/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/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-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp -faddrsig
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~svn338205/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~svn338205/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~svn338205/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~svn338205/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~svn338205/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_IncompletePack:' 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_IncompletePack:
633 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
634 case Sema::TDK_Inconsistent:
635 case Sema::TDK_Underqualified: {
636 // FIXME: Should allocate from normal heap so that we can free this later.
637 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
8
'Saved' initialized to a null pointer value
638 Saved->Param = Info.Param;
9
Called C++ object pointer is null
639 Saved->FirstArg = Info.FirstArg;
640 Saved->SecondArg = Info.SecondArg;
641 Result.Data = Saved;
642 break;
643 }
644
645 case Sema::TDK_SubstitutionFailure:
646 Result.Data = Info.take();
647 if (Info.hasSFINAEDiagnostic()) {
648 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
649 SourceLocation(), PartialDiagnostic::NullDiagnostic());
650 Info.takeSFINAEDiagnostic(*Diag);
651 Result.HasDiagnostic = true;
652 }
653 break;
654
655 case Sema::TDK_Success:
656 case Sema::TDK_NonDependentConversionFailure:
657 llvm_unreachable("not a deduction failure")::llvm::llvm_unreachable_internal("not a deduction failure", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 657)
;
658 }
659
660 return Result;
661}
662
663void DeductionFailureInfo::Destroy() {
664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
665 case Sema::TDK_Success:
666 case Sema::TDK_Invalid:
667 case Sema::TDK_InstantiationDepth:
668 case Sema::TDK_Incomplete:
669 case Sema::TDK_TooManyArguments:
670 case Sema::TDK_TooFewArguments:
671 case Sema::TDK_InvalidExplicitArguments:
672 case Sema::TDK_CUDATargetMismatch:
673 case Sema::TDK_NonDependentConversionFailure:
674 break;
675
676 case Sema::TDK_IncompletePack:
677 case Sema::TDK_Inconsistent:
678 case Sema::TDK_Underqualified:
679 case Sema::TDK_DeducedMismatch:
680 case Sema::TDK_DeducedMismatchNested:
681 case Sema::TDK_NonDeducedMismatch:
682 // FIXME: Destroy the data?
683 Data = nullptr;
684 break;
685
686 case Sema::TDK_SubstitutionFailure:
687 // FIXME: Destroy the template argument list?
688 Data = nullptr;
689 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
690 Diag->~PartialDiagnosticAt();
691 HasDiagnostic = false;
692 }
693 break;
694
695 // Unhandled
696 case Sema::TDK_MiscellaneousDeductionFailure:
697 break;
698 }
699}
700
701PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
702 if (HasDiagnostic)
703 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
704 return nullptr;
705}
706
707TemplateParameter DeductionFailureInfo::getTemplateParameter() {
708 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
709 case Sema::TDK_Success:
710 case Sema::TDK_Invalid:
711 case Sema::TDK_InstantiationDepth:
712 case Sema::TDK_TooManyArguments:
713 case Sema::TDK_TooFewArguments:
714 case Sema::TDK_SubstitutionFailure:
715 case Sema::TDK_DeducedMismatch:
716 case Sema::TDK_DeducedMismatchNested:
717 case Sema::TDK_NonDeducedMismatch:
718 case Sema::TDK_CUDATargetMismatch:
719 case Sema::TDK_NonDependentConversionFailure:
720 return TemplateParameter();
721
722 case Sema::TDK_Incomplete:
723 case Sema::TDK_InvalidExplicitArguments:
724 return TemplateParameter::getFromOpaqueValue(Data);
725
726 case Sema::TDK_IncompletePack:
727 case Sema::TDK_Inconsistent:
728 case Sema::TDK_Underqualified:
729 return static_cast<DFIParamWithArguments*>(Data)->Param;
730
731 // Unhandled
732 case Sema::TDK_MiscellaneousDeductionFailure:
733 break;
734 }
735
736 return TemplateParameter();
737}
738
739TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
741 case Sema::TDK_Success:
742 case Sema::TDK_Invalid:
743 case Sema::TDK_InstantiationDepth:
744 case Sema::TDK_TooManyArguments:
745 case Sema::TDK_TooFewArguments:
746 case Sema::TDK_Incomplete:
747 case Sema::TDK_IncompletePack:
748 case Sema::TDK_InvalidExplicitArguments:
749 case Sema::TDK_Inconsistent:
750 case Sema::TDK_Underqualified:
751 case Sema::TDK_NonDeducedMismatch:
752 case Sema::TDK_CUDATargetMismatch:
753 case Sema::TDK_NonDependentConversionFailure:
754 return nullptr;
755
756 case Sema::TDK_DeducedMismatch:
757 case Sema::TDK_DeducedMismatchNested:
758 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
759
760 case Sema::TDK_SubstitutionFailure:
761 return static_cast<TemplateArgumentList*>(Data);
762
763 // Unhandled
764 case Sema::TDK_MiscellaneousDeductionFailure:
765 break;
766 }
767
768 return nullptr;
769}
770
771const TemplateArgument *DeductionFailureInfo::getFirstArg() {
772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
773 case Sema::TDK_Success:
774 case Sema::TDK_Invalid:
775 case Sema::TDK_InstantiationDepth:
776 case Sema::TDK_Incomplete:
777 case Sema::TDK_TooManyArguments:
778 case Sema::TDK_TooFewArguments:
779 case Sema::TDK_InvalidExplicitArguments:
780 case Sema::TDK_SubstitutionFailure:
781 case Sema::TDK_CUDATargetMismatch:
782 case Sema::TDK_NonDependentConversionFailure:
783 return nullptr;
784
785 case Sema::TDK_IncompletePack:
786 case Sema::TDK_Inconsistent:
787 case Sema::TDK_Underqualified:
788 case Sema::TDK_DeducedMismatch:
789 case Sema::TDK_DeducedMismatchNested:
790 case Sema::TDK_NonDeducedMismatch:
791 return &static_cast<DFIArguments*>(Data)->FirstArg;
792
793 // Unhandled
794 case Sema::TDK_MiscellaneousDeductionFailure:
795 break;
796 }
797
798 return nullptr;
799}
800
801const TemplateArgument *DeductionFailureInfo::getSecondArg() {
802 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
803 case Sema::TDK_Success:
804 case Sema::TDK_Invalid:
805 case Sema::TDK_InstantiationDepth:
806 case Sema::TDK_Incomplete:
807 case Sema::TDK_IncompletePack:
808 case Sema::TDK_TooManyArguments:
809 case Sema::TDK_TooFewArguments:
810 case Sema::TDK_InvalidExplicitArguments:
811 case Sema::TDK_SubstitutionFailure:
812 case Sema::TDK_CUDATargetMismatch:
813 case Sema::TDK_NonDependentConversionFailure:
814 return nullptr;
815
816 case Sema::TDK_Inconsistent:
817 case Sema::TDK_Underqualified:
818 case Sema::TDK_DeducedMismatch:
819 case Sema::TDK_DeducedMismatchNested:
820 case Sema::TDK_NonDeducedMismatch:
821 return &static_cast<DFIArguments*>(Data)->SecondArg;
822
823 // Unhandled
824 case Sema::TDK_MiscellaneousDeductionFailure:
825 break;
826 }
827
828 return nullptr;
829}
830
831llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
832 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
833 case Sema::TDK_DeducedMismatch:
834 case Sema::TDK_DeducedMismatchNested:
835 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
836
837 default:
838 return llvm::None;
839 }
840}
841
842void OverloadCandidateSet::destroyCandidates() {
843 for (iterator i = begin(), e = end(); i != e; ++i) {
844 for (auto &C : i->Conversions)
845 C.~ImplicitConversionSequence();
846 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
847 i->DeductionFailure.Destroy();
848 }
849}
850
851void OverloadCandidateSet::clear(CandidateSetKind CSK) {
852 destroyCandidates();
853 SlabAllocator.Reset();
854 NumInlineBytesUsed = 0;
855 Candidates.clear();
856 Functions.clear();
857 Kind = CSK;
858}
859
860namespace {
861 class UnbridgedCastsSet {
862 struct Entry {
863 Expr **Addr;
864 Expr *Saved;
865 };
866 SmallVector<Entry, 2> Entries;
867
868 public:
869 void save(Sema &S, Expr *&E) {
870 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 870, __extension__ __PRETTY_FUNCTION__))
;
871 Entry entry = { &E, E };
872 Entries.push_back(entry);
873 E = S.stripARCUnbridgedCast(E);
874 }
875
876 void restore() {
877 for (SmallVectorImpl<Entry>::iterator
878 i = Entries.begin(), e = Entries.end(); i != e; ++i)
879 *i->Addr = i->Saved;
880 }
881 };
882}
883
884/// checkPlaceholderForOverload - Do any interesting placeholder-like
885/// preprocessing on the given expression.
886///
887/// \param unbridgedCasts a collection to which to add unbridged casts;
888/// without this, they will be immediately diagnosed as errors
889///
890/// Return true on unrecoverable error.
891static bool
892checkPlaceholderForOverload(Sema &S, Expr *&E,
893 UnbridgedCastsSet *unbridgedCasts = nullptr) {
894 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
895 // We can't handle overloaded expressions here because overload
896 // resolution might reasonably tweak them.
897 if (placeholder->getKind() == BuiltinType::Overload) return false;
898
899 // If the context potentially accepts unbridged ARC casts, strip
900 // the unbridged cast and add it to the collection for later restoration.
901 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
902 unbridgedCasts) {
903 unbridgedCasts->save(S, E);
904 return false;
905 }
906
907 // Go ahead and check everything else.
908 ExprResult result = S.CheckPlaceholderExpr(E);
909 if (result.isInvalid())
910 return true;
911
912 E = result.get();
913 return false;
914 }
915
916 // Nothing to do.
917 return false;
918}
919
920/// checkArgPlaceholdersForOverload - Check a set of call operands for
921/// placeholders.
922static bool checkArgPlaceholdersForOverload(Sema &S,
923 MultiExprArg Args,
924 UnbridgedCastsSet &unbridged) {
925 for (unsigned i = 0, e = Args.size(); i != e; ++i)
926 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
927 return true;
928
929 return false;
930}
931
932/// Determine whether the given New declaration is an overload of the
933/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
934/// New and Old cannot be overloaded, e.g., if New has the same signature as
935/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
936/// functions (or function templates) at all. When it does return Ovl_Match or
937/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
938/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
939/// declaration.
940///
941/// Example: Given the following input:
942///
943/// void f(int, float); // #1
944/// void f(int, int); // #2
945/// int f(int, int); // #3
946///
947/// When we process #1, there is no previous declaration of "f", so IsOverload
948/// will not be used.
949///
950/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
951/// the parameter types, we see that #1 and #2 are overloaded (since they have
952/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
953/// unchanged.
954///
955/// When we process #3, Old is an overload set containing #1 and #2. We compare
956/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
957/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
958/// functions are not part of the signature), IsOverload returns Ovl_Match and
959/// MatchedDecl will be set to point to the FunctionDecl for #2.
960///
961/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
962/// by a using declaration. The rules for whether to hide shadow declarations
963/// ignore some properties which otherwise figure into a function template's
964/// signature.
965Sema::OverloadKind
966Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
967 NamedDecl *&Match, bool NewIsUsingDecl) {
968 for (LookupResult::iterator I = Old.begin(), E = Old.end();
969 I != E; ++I) {
970 NamedDecl *OldD = *I;
971
972 bool OldIsUsingDecl = false;
973 if (isa<UsingShadowDecl>(OldD)) {
974 OldIsUsingDecl = true;
975
976 // We can always introduce two using declarations into the same
977 // context, even if they have identical signatures.
978 if (NewIsUsingDecl) continue;
979
980 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
981 }
982
983 // A using-declaration does not conflict with another declaration
984 // if one of them is hidden.
985 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
986 continue;
987
988 // If either declaration was introduced by a using declaration,
989 // we'll need to use slightly different rules for matching.
990 // Essentially, these rules are the normal rules, except that
991 // function templates hide function templates with different
992 // return types or template parameter lists.
993 bool UseMemberUsingDeclRules =
994 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
995 !New->getFriendObjectKind();
996
997 if (FunctionDecl *OldF = OldD->getAsFunction()) {
998 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
999 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1000 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1001 continue;
1002 }
1003
1004 if (!isa<FunctionTemplateDecl>(OldD) &&
1005 !shouldLinkPossiblyHiddenDecl(*I, New))
1006 continue;
1007
1008 Match = *I;
1009 return Ovl_Match;
1010 }
1011
1012 // Builtins that have custom typechecking or have a reference should
1013 // not be overloadable or redeclarable.
1014 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1015 Match = *I;
1016 return Ovl_NonFunction;
1017 }
1018 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1019 // We can overload with these, which can show up when doing
1020 // redeclaration checks for UsingDecls.
1021 assert(Old.getLookupKind() == LookupUsingDeclName)(static_cast <bool> (Old.getLookupKind() == LookupUsingDeclName
) ? void (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1021, __extension__ __PRETTY_FUNCTION__))
;
1022 } else if (isa<TagDecl>(OldD)) {
1023 // We can always overload with tags by hiding them.
1024 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1025 // Optimistically assume that an unresolved using decl will
1026 // overload; if it doesn't, we'll have to diagnose during
1027 // template instantiation.
1028 //
1029 // Exception: if the scope is dependent and this is not a class
1030 // member, the using declaration can only introduce an enumerator.
1031 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1032 Match = *I;
1033 return Ovl_NonFunction;
1034 }
1035 } else {
1036 // (C++ 13p1):
1037 // Only function declarations can be overloaded; object and type
1038 // declarations cannot be overloaded.
1039 Match = *I;
1040 return Ovl_NonFunction;
1041 }
1042 }
1043
1044 return Ovl_Overload;
1045}
1046
1047bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1048 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1049 // C++ [basic.start.main]p2: This function shall not be overloaded.
1050 if (New->isMain())
1051 return false;
1052
1053 // MSVCRT user defined entry points cannot be overloaded.
1054 if (New->isMSVCRTEntryPoint())
1055 return false;
1056
1057 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1058 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1059
1060 // C++ [temp.fct]p2:
1061 // A function template can be overloaded with other function templates
1062 // and with normal (non-template) functions.
1063 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1064 return true;
1065
1066 // Is the function New an overload of the function Old?
1067 QualType OldQType = Context.getCanonicalType(Old->getType());
1068 QualType NewQType = Context.getCanonicalType(New->getType());
1069
1070 // Compare the signatures (C++ 1.3.10) of the two functions to
1071 // determine whether they are overloads. If we find any mismatch
1072 // in the signature, they are overloads.
1073
1074 // If either of these functions is a K&R-style function (no
1075 // prototype), then we consider them to have matching signatures.
1076 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1077 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1078 return false;
1079
1080 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1081 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1082
1083 // The signature of a function includes the types of its
1084 // parameters (C++ 1.3.10), which includes the presence or absence
1085 // of the ellipsis; see C++ DR 357).
1086 if (OldQType != NewQType &&
1087 (OldType->getNumParams() != NewType->getNumParams() ||
1088 OldType->isVariadic() != NewType->isVariadic() ||
1089 !FunctionParamTypesAreEqual(OldType, NewType)))
1090 return true;
1091
1092 // C++ [temp.over.link]p4:
1093 // The signature of a function template consists of its function
1094 // signature, its return type and its template parameter list. The names
1095 // of the template parameters are significant only for establishing the
1096 // relationship between the template parameters and the rest of the
1097 // signature.
1098 //
1099 // We check the return type and template parameter lists for function
1100 // templates first; the remaining checks follow.
1101 //
1102 // However, we don't consider either of these when deciding whether
1103 // a member introduced by a shadow declaration is hidden.
1104 if (!UseMemberUsingDeclRules && NewTemplate &&
1105 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1106 OldTemplate->getTemplateParameters(),
1107 false, TPL_TemplateMatch) ||
1108 OldType->getReturnType() != NewType->getReturnType()))
1109 return true;
1110
1111 // If the function is a class member, its signature includes the
1112 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1113 //
1114 // As part of this, also check whether one of the member functions
1115 // is static, in which case they are not overloads (C++
1116 // 13.1p2). While not part of the definition of the signature,
1117 // this check is important to determine whether these functions
1118 // can be overloaded.
1119 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1120 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1121 if (OldMethod && NewMethod &&
1122 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1123 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1124 if (!UseMemberUsingDeclRules &&
1125 (OldMethod->getRefQualifier() == RQ_None ||
1126 NewMethod->getRefQualifier() == RQ_None)) {
1127 // C++0x [over.load]p2:
1128 // - Member function declarations with the same name and the same
1129 // parameter-type-list as well as member function template
1130 // declarations with the same name, the same parameter-type-list, and
1131 // the same template parameter lists cannot be overloaded if any of
1132 // them, but not all, have a ref-qualifier (8.3.5).
1133 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1134 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1135 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1136 }
1137 return true;
1138 }
1139
1140 // We may not have applied the implicit const for a constexpr member
1141 // function yet (because we haven't yet resolved whether this is a static
1142 // or non-static member function). Add it now, on the assumption that this
1143 // is a redeclaration of OldMethod.
1144 unsigned OldQuals = OldMethod->getTypeQualifiers();
1145 unsigned NewQuals = NewMethod->getTypeQualifiers();
1146 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1147 !isa<CXXConstructorDecl>(NewMethod))
1148 NewQuals |= Qualifiers::Const;
1149
1150 // We do not allow overloading based off of '__restrict'.
1151 OldQuals &= ~Qualifiers::Restrict;
1152 NewQuals &= ~Qualifiers::Restrict;
1153 if (OldQuals != NewQuals)
1154 return true;
1155 }
1156
1157 // Though pass_object_size is placed on parameters and takes an argument, we
1158 // consider it to be a function-level modifier for the sake of function
1159 // identity. Either the function has one or more parameters with
1160 // pass_object_size or it doesn't.
1161 if (functionHasPassObjectSizeParams(New) !=
1162 functionHasPassObjectSizeParams(Old))
1163 return true;
1164
1165 // enable_if attributes are an order-sensitive part of the signature.
1166 for (specific_attr_iterator<EnableIfAttr>
1167 NewI = New->specific_attr_begin<EnableIfAttr>(),
1168 NewE = New->specific_attr_end<EnableIfAttr>(),
1169 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1170 OldE = Old->specific_attr_end<EnableIfAttr>();
1171 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1172 if (NewI == NewE || OldI == OldE)
1173 return true;
1174 llvm::FoldingSetNodeID NewID, OldID;
1175 NewI->getCond()->Profile(NewID, Context, true);
1176 OldI->getCond()->Profile(OldID, Context, true);
1177 if (NewID != OldID)
1178 return true;
1179 }
1180
1181 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1182 // Don't allow overloading of destructors. (In theory we could, but it
1183 // would be a giant change to clang.)
1184 if (isa<CXXDestructorDecl>(New))
1185 return false;
1186
1187 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1188 OldTarget = IdentifyCUDATarget(Old);
1189 if (NewTarget == CFT_InvalidTarget)
1190 return false;
1191
1192 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1192, __extension__ __PRETTY_FUNCTION__))
;
1193
1194 // Allow overloading of functions with same signature and different CUDA
1195 // target attributes.
1196 return NewTarget != OldTarget;
1197 }
1198
1199 // The signatures match; this is not an overload.
1200 return false;
1201}
1202
1203/// Checks availability of the function depending on the current
1204/// function context. Inside an unavailable function, unavailability is ignored.
1205///
1206/// \returns true if \arg FD is unavailable and current context is inside
1207/// an available function, false otherwise.
1208bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1209 if (!FD->isUnavailable())
1210 return false;
1211
1212 // Walk up the context of the caller.
1213 Decl *C = cast<Decl>(CurContext);
1214 do {
1215 if (C->isUnavailable())
1216 return false;
1217 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1218 return true;
1219}
1220
1221/// Tries a user-defined conversion from From to ToType.
1222///
1223/// Produces an implicit conversion sequence for when a standard conversion
1224/// is not an option. See TryImplicitConversion for more information.
1225static ImplicitConversionSequence
1226TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1227 bool SuppressUserConversions,
1228 bool AllowExplicit,
1229 bool InOverloadResolution,
1230 bool CStyle,
1231 bool AllowObjCWritebackConversion,
1232 bool AllowObjCConversionOnExplicit) {
1233 ImplicitConversionSequence ICS;
1234
1235 if (SuppressUserConversions) {
1236 // We're not in the case above, so there is no conversion that
1237 // we can perform.
1238 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1239 return ICS;
1240 }
1241
1242 // Attempt user-defined conversion.
1243 OverloadCandidateSet Conversions(From->getExprLoc(),
1244 OverloadCandidateSet::CSK_Normal);
1245 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1246 Conversions, AllowExplicit,
1247 AllowObjCConversionOnExplicit)) {
1248 case OR_Success:
1249 case OR_Deleted:
1250 ICS.setUserDefined();
1251 // C++ [over.ics.user]p4:
1252 // A conversion of an expression of class type to the same class
1253 // type is given Exact Match rank, and a conversion of an
1254 // expression of class type to a base class of that type is
1255 // given Conversion rank, in spite of the fact that a copy
1256 // constructor (i.e., a user-defined conversion function) is
1257 // called for those cases.
1258 if (CXXConstructorDecl *Constructor
1259 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1260 QualType FromCanon
1261 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1262 QualType ToCanon
1263 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1264 if (Constructor->isCopyConstructor() &&
1265 (FromCanon == ToCanon ||
1266 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1267 // Turn this into a "standard" conversion sequence, so that it
1268 // gets ranked with standard conversion sequences.
1269 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1270 ICS.setStandard();
1271 ICS.Standard.setAsIdentityConversion();
1272 ICS.Standard.setFromType(From->getType());
1273 ICS.Standard.setAllToTypes(ToType);
1274 ICS.Standard.CopyConstructor = Constructor;
1275 ICS.Standard.FoundCopyConstructor = Found;
1276 if (ToCanon != FromCanon)
1277 ICS.Standard.Second = ICK_Derived_To_Base;
1278 }
1279 }
1280 break;
1281
1282 case OR_Ambiguous:
1283 ICS.setAmbiguous();
1284 ICS.Ambiguous.setFromType(From->getType());
1285 ICS.Ambiguous.setToType(ToType);
1286 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1287 Cand != Conversions.end(); ++Cand)
1288 if (Cand->Viable)
1289 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1290 break;
1291
1292 // Fall through.
1293 case OR_No_Viable_Function:
1294 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1295 break;
1296 }
1297
1298 return ICS;
1299}
1300
1301/// TryImplicitConversion - Attempt to perform an implicit conversion
1302/// from the given expression (Expr) to the given type (ToType). This
1303/// function returns an implicit conversion sequence that can be used
1304/// to perform the initialization. Given
1305///
1306/// void f(float f);
1307/// void g(int i) { f(i); }
1308///
1309/// this routine would produce an implicit conversion sequence to
1310/// describe the initialization of f from i, which will be a standard
1311/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1312/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1313//
1314/// Note that this routine only determines how the conversion can be
1315/// performed; it does not actually perform the conversion. As such,
1316/// it will not produce any diagnostics if no conversion is available,
1317/// but will instead return an implicit conversion sequence of kind
1318/// "BadConversion".
1319///
1320/// If @p SuppressUserConversions, then user-defined conversions are
1321/// not permitted.
1322/// If @p AllowExplicit, then explicit user-defined conversions are
1323/// permitted.
1324///
1325/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1326/// writeback conversion, which allows __autoreleasing id* parameters to
1327/// be initialized with __strong id* or __weak id* arguments.
1328static ImplicitConversionSequence
1329TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1330 bool SuppressUserConversions,
1331 bool AllowExplicit,
1332 bool InOverloadResolution,
1333 bool CStyle,
1334 bool AllowObjCWritebackConversion,
1335 bool AllowObjCConversionOnExplicit) {
1336 ImplicitConversionSequence ICS;
1337 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1338 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1339 ICS.setStandard();
1340 return ICS;
1341 }
1342
1343 if (!S.getLangOpts().CPlusPlus) {
1344 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1345 return ICS;
1346 }
1347
1348 // C++ [over.ics.user]p4:
1349 // A conversion of an expression of class type to the same class
1350 // type is given Exact Match rank, and a conversion of an
1351 // expression of class type to a base class of that type is
1352 // given Conversion rank, in spite of the fact that a copy/move
1353 // constructor (i.e., a user-defined conversion function) is
1354 // called for those cases.
1355 QualType FromType = From->getType();
1356 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1357 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1358 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1359 ICS.setStandard();
1360 ICS.Standard.setAsIdentityConversion();
1361 ICS.Standard.setFromType(FromType);
1362 ICS.Standard.setAllToTypes(ToType);
1363
1364 // We don't actually check at this point whether there is a valid
1365 // copy/move constructor, since overloading just assumes that it
1366 // exists. When we actually perform initialization, we'll find the
1367 // appropriate constructor to copy the returned object, if needed.
1368 ICS.Standard.CopyConstructor = nullptr;
1369
1370 // Determine whether this is considered a derived-to-base conversion.
1371 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1372 ICS.Standard.Second = ICK_Derived_To_Base;
1373
1374 return ICS;
1375 }
1376
1377 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1378 AllowExplicit, InOverloadResolution, CStyle,
1379 AllowObjCWritebackConversion,
1380 AllowObjCConversionOnExplicit);
1381}
1382
1383ImplicitConversionSequence
1384Sema::TryImplicitConversion(Expr *From, QualType ToType,
1385 bool SuppressUserConversions,
1386 bool AllowExplicit,
1387 bool InOverloadResolution,
1388 bool CStyle,
1389 bool AllowObjCWritebackConversion) {
1390 return ::TryImplicitConversion(*this, From, ToType,
1391 SuppressUserConversions, AllowExplicit,
1392 InOverloadResolution, CStyle,
1393 AllowObjCWritebackConversion,
1394 /*AllowObjCConversionOnExplicit=*/false);
1395}
1396
1397/// PerformImplicitConversion - Perform an implicit conversion of the
1398/// expression From to the type ToType. Returns the
1399/// converted expression. Flavor is the kind of conversion we're
1400/// performing, used in the error message. If @p AllowExplicit,
1401/// explicit user-defined conversions are permitted.
1402ExprResult
1403Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1404 AssignmentAction Action, bool AllowExplicit) {
1405 ImplicitConversionSequence ICS;
1406 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1407}
1408
1409ExprResult
1410Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1411 AssignmentAction Action, bool AllowExplicit,
1412 ImplicitConversionSequence& ICS) {
1413 if (checkPlaceholderForOverload(*this, From))
1414 return ExprError();
1415
1416 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1417 bool AllowObjCWritebackConversion
1418 = getLangOpts().ObjCAutoRefCount &&
1419 (Action == AA_Passing || Action == AA_Sending);
1420 if (getLangOpts().ObjC1)
1421 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1422 ToType, From->getType(), From);
1423 ICS = ::TryImplicitConversion(*this, From, ToType,
1424 /*SuppressUserConversions=*/false,
1425 AllowExplicit,
1426 /*InOverloadResolution=*/false,
1427 /*CStyle=*/false,
1428 AllowObjCWritebackConversion,
1429 /*AllowObjCConversionOnExplicit=*/false);
1430 return PerformImplicitConversion(From, ToType, ICS, Action);
1431}
1432
1433/// Determine whether the conversion from FromType to ToType is a valid
1434/// conversion that strips "noexcept" or "noreturn" off the nested function
1435/// type.
1436bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1437 QualType &ResultTy) {
1438 if (Context.hasSameUnqualifiedType(FromType, ToType))
1439 return false;
1440
1441 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1442 // or F(t noexcept) -> F(t)
1443 // where F adds one of the following at most once:
1444 // - a pointer
1445 // - a member pointer
1446 // - a block pointer
1447 // Changes here need matching changes in FindCompositePointerType.
1448 CanQualType CanTo = Context.getCanonicalType(ToType);
1449 CanQualType CanFrom = Context.getCanonicalType(FromType);
1450 Type::TypeClass TyClass = CanTo->getTypeClass();
1451 if (TyClass != CanFrom->getTypeClass()) return false;
1452 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1453 if (TyClass == Type::Pointer) {
1454 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1455 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1456 } else if (TyClass == Type::BlockPointer) {
1457 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1458 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1459 } else if (TyClass == Type::MemberPointer) {
1460 auto ToMPT = CanTo.getAs<MemberPointerType>();
1461 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1462 // A function pointer conversion cannot change the class of the function.
1463 if (ToMPT->getClass() != FromMPT->getClass())
1464 return false;
1465 CanTo = ToMPT->getPointeeType();
1466 CanFrom = FromMPT->getPointeeType();
1467 } else {
1468 return false;
1469 }
1470
1471 TyClass = CanTo->getTypeClass();
1472 if (TyClass != CanFrom->getTypeClass()) return false;
1473 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1474 return false;
1475 }
1476
1477 const auto *FromFn = cast<FunctionType>(CanFrom);
1478 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1479
1480 const auto *ToFn = cast<FunctionType>(CanTo);
1481 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1482
1483 bool Changed = false;
1484
1485 // Drop 'noreturn' if not present in target type.
1486 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1487 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1488 Changed = true;
1489 }
1490
1491 // Drop 'noexcept' if not present in target type.
1492 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1493 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1494 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1495 FromFn = cast<FunctionType>(
1496 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1497 EST_None)
1498 .getTypePtr());
1499 Changed = true;
1500 }
1501
1502 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1503 // only if the ExtParameterInfo lists of the two function prototypes can be
1504 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1505 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1506 bool CanUseToFPT, CanUseFromFPT;
1507 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1508 CanUseFromFPT, NewParamInfos) &&
1509 CanUseToFPT && !CanUseFromFPT) {
1510 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1511 ExtInfo.ExtParameterInfos =
1512 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1513 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1514 FromFPT->getParamTypes(), ExtInfo);
1515 FromFn = QT->getAs<FunctionType>();
1516 Changed = true;
1517 }
1518 }
1519
1520 if (!Changed)
1521 return false;
1522
1523 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1523, __extension__ __PRETTY_FUNCTION__))
;
1524 if (QualType(FromFn, 0) != CanTo) return false;
1525
1526 ResultTy = ToType;
1527 return true;
1528}
1529
1530/// Determine whether the conversion from FromType to ToType is a valid
1531/// vector conversion.
1532///
1533/// \param ICK Will be set to the vector conversion kind, if this is a vector
1534/// conversion.
1535static bool IsVectorConversion(Sema &S, QualType FromType,
1536 QualType ToType, ImplicitConversionKind &ICK) {
1537 // We need at least one of these types to be a vector type to have a vector
1538 // conversion.
1539 if (!ToType->isVectorType() && !FromType->isVectorType())
1540 return false;
1541
1542 // Identical types require no conversions.
1543 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1544 return false;
1545
1546 // There are no conversions between extended vector types, only identity.
1547 if (ToType->isExtVectorType()) {
1548 // There are no conversions between extended vector types other than the
1549 // identity conversion.
1550 if (FromType->isExtVectorType())
1551 return false;
1552
1553 // Vector splat from any arithmetic type to a vector.
1554 if (FromType->isArithmeticType()) {
1555 ICK = ICK_Vector_Splat;
1556 return true;
1557 }
1558 }
1559
1560 // We can perform the conversion between vector types in the following cases:
1561 // 1)vector types are equivalent AltiVec and GCC vector types
1562 // 2)lax vector conversions are permitted and the vector types are of the
1563 // same size
1564 if (ToType->isVectorType() && FromType->isVectorType()) {
1565 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1566 S.isLaxVectorConversion(FromType, ToType)) {
1567 ICK = ICK_Vector_Conversion;
1568 return true;
1569 }
1570 }
1571
1572 return false;
1573}
1574
1575static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1576 bool InOverloadResolution,
1577 StandardConversionSequence &SCS,
1578 bool CStyle);
1579
1580/// IsStandardConversion - Determines whether there is a standard
1581/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1582/// expression From to the type ToType. Standard conversion sequences
1583/// only consider non-class types; for conversions that involve class
1584/// types, use TryImplicitConversion. If a conversion exists, SCS will
1585/// contain the standard conversion sequence required to perform this
1586/// conversion and this routine will return true. Otherwise, this
1587/// routine will return false and the value of SCS is unspecified.
1588static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1589 bool InOverloadResolution,
1590 StandardConversionSequence &SCS,
1591 bool CStyle,
1592 bool AllowObjCWritebackConversion) {
1593 QualType FromType = From->getType();
1594
1595 // Standard conversions (C++ [conv])
1596 SCS.setAsIdentityConversion();
1597 SCS.IncompatibleObjC = false;
1598 SCS.setFromType(FromType);
1599 SCS.CopyConstructor = nullptr;
1600
1601 // There are no standard conversions for class types in C++, so
1602 // abort early. When overloading in C, however, we do permit them.
1603 if (S.getLangOpts().CPlusPlus &&
1604 (FromType->isRecordType() || ToType->isRecordType()))
1605 return false;
1606
1607 // The first conversion can be an lvalue-to-rvalue conversion,
1608 // array-to-pointer conversion, or function-to-pointer conversion
1609 // (C++ 4p1).
1610
1611 if (FromType == S.Context.OverloadTy) {
1612 DeclAccessPair AccessPair;
1613 if (FunctionDecl *Fn
1614 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1615 AccessPair)) {
1616 // We were able to resolve the address of the overloaded function,
1617 // so we can convert to the type of that function.
1618 FromType = Fn->getType();
1619 SCS.setFromType(FromType);
1620
1621 // we can sometimes resolve &foo<int> regardless of ToType, so check
1622 // if the type matches (identity) or we are converting to bool
1623 if (!S.Context.hasSameUnqualifiedType(
1624 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1625 QualType resultTy;
1626 // if the function type matches except for [[noreturn]], it's ok
1627 if (!S.IsFunctionConversion(FromType,
1628 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1629 // otherwise, only a boolean conversion is standard
1630 if (!ToType->isBooleanType())
1631 return false;
1632 }
1633
1634 // Check if the "from" expression is taking the address of an overloaded
1635 // function and recompute the FromType accordingly. Take advantage of the
1636 // fact that non-static member functions *must* have such an address-of
1637 // expression.
1638 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1639 if (Method && !Method->isStatic()) {
1640 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1641, __extension__ __PRETTY_FUNCTION__))
1641 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1641, __extension__ __PRETTY_FUNCTION__))
;
1642 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~svn338205/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 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
1644 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1644, __extension__ __PRETTY_FUNCTION__))
;
1645 const Type *ClassType
1646 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1647 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1648 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1649 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1651, __extension__ __PRETTY_FUNCTION__))
1650 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1651, __extension__ __PRETTY_FUNCTION__))
1651 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1651, __extension__ __PRETTY_FUNCTION__))
;
1652 FromType = S.Context.getPointerType(FromType);
1653 }
1654
1655 // Check that we've computed the proper type after overload resolution.
1656 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1657 // be calling it from within an NDEBUG block.
1658 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1660, __extension__ __PRETTY_FUNCTION__))
1659 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1660, __extension__ __PRETTY_FUNCTION__))
1660 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1660, __extension__ __PRETTY_FUNCTION__))
;
1661 } else {
1662 return false;
1663 }
1664 }
1665 // Lvalue-to-rvalue conversion (C++11 4.1):
1666 // A glvalue (3.10) of a non-function, non-array type T can
1667 // be converted to a prvalue.
1668 bool argIsLValue = From->isGLValue();
1669 if (argIsLValue &&
1670 !FromType->isFunctionType() && !FromType->isArrayType() &&
1671 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1672 SCS.First = ICK_Lvalue_To_Rvalue;
1673
1674 // C11 6.3.2.1p2:
1675 // ... if the lvalue has atomic type, the value has the non-atomic version
1676 // of the type of the lvalue ...
1677 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1678 FromType = Atomic->getValueType();
1679
1680 // If T is a non-class type, the type of the rvalue is the
1681 // cv-unqualified version of T. Otherwise, the type of the rvalue
1682 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1683 // just strip the qualifiers because they don't matter.
1684 FromType = FromType.getUnqualifiedType();
1685 } else if (FromType->isArrayType()) {
1686 // Array-to-pointer conversion (C++ 4.2)
1687 SCS.First = ICK_Array_To_Pointer;
1688
1689 // An lvalue or rvalue of type "array of N T" or "array of unknown
1690 // bound of T" can be converted to an rvalue of type "pointer to
1691 // T" (C++ 4.2p1).
1692 FromType = S.Context.getArrayDecayedType(FromType);
1693
1694 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1695 // This conversion is deprecated in C++03 (D.4)
1696 SCS.DeprecatedStringLiteralToCharPtr = true;
1697
1698 // For the purpose of ranking in overload resolution
1699 // (13.3.3.1.1), this conversion is considered an
1700 // array-to-pointer conversion followed by a qualification
1701 // conversion (4.4). (C++ 4.2p2)
1702 SCS.Second = ICK_Identity;
1703 SCS.Third = ICK_Qualification;
1704 SCS.QualificationIncludesObjCLifetime = false;
1705 SCS.setAllToTypes(FromType);
1706 return true;
1707 }
1708 } else if (FromType->isFunctionType() && argIsLValue) {
1709 // Function-to-pointer conversion (C++ 4.3).
1710 SCS.First = ICK_Function_To_Pointer;
1711
1712 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1713 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1714 if (!S.checkAddressOfFunctionIsAvailable(FD))
1715 return false;
1716
1717 // An lvalue of function type T can be converted to an rvalue of
1718 // type "pointer to T." The result is a pointer to the
1719 // function. (C++ 4.3p1).
1720 FromType = S.Context.getPointerType(FromType);
1721 } else {
1722 // We don't require any conversions for the first step.
1723 SCS.First = ICK_Identity;
1724 }
1725 SCS.setToType(0, FromType);
1726
1727 // The second conversion can be an integral promotion, floating
1728 // point promotion, integral conversion, floating point conversion,
1729 // floating-integral conversion, pointer conversion,
1730 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1731 // For overloading in C, this can also be a "compatible-type"
1732 // conversion.
1733 bool IncompatibleObjC = false;
1734 ImplicitConversionKind SecondICK = ICK_Identity;
1735 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1736 // The unqualified versions of the types are the same: there's no
1737 // conversion to do.
1738 SCS.Second = ICK_Identity;
1739 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1740 // Integral promotion (C++ 4.5).
1741 SCS.Second = ICK_Integral_Promotion;
1742 FromType = ToType.getUnqualifiedType();
1743 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1744 // Floating point promotion (C++ 4.6).
1745 SCS.Second = ICK_Floating_Promotion;
1746 FromType = ToType.getUnqualifiedType();
1747 } else if (S.IsComplexPromotion(FromType, ToType)) {
1748 // Complex promotion (Clang extension)
1749 SCS.Second = ICK_Complex_Promotion;
1750 FromType = ToType.getUnqualifiedType();
1751 } else if (ToType->isBooleanType() &&
1752 (FromType->isArithmeticType() ||
1753 FromType->isAnyPointerType() ||
1754 FromType->isBlockPointerType() ||
1755 FromType->isMemberPointerType() ||
1756 FromType->isNullPtrType())) {
1757 // Boolean conversions (C++ 4.12).
1758 SCS.Second = ICK_Boolean_Conversion;
1759 FromType = S.Context.BoolTy;
1760 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1761 ToType->isIntegralType(S.Context)) {
1762 // Integral conversions (C++ 4.7).
1763 SCS.Second = ICK_Integral_Conversion;
1764 FromType = ToType.getUnqualifiedType();
1765 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1766 // Complex conversions (C99 6.3.1.6)
1767 SCS.Second = ICK_Complex_Conversion;
1768 FromType = ToType.getUnqualifiedType();
1769 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1770 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1771 // Complex-real conversions (C99 6.3.1.7)
1772 SCS.Second = ICK_Complex_Real;
1773 FromType = ToType.getUnqualifiedType();
1774 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1775 // FIXME: disable conversions between long double and __float128 if
1776 // their representation is different until there is back end support
1777 // We of course allow this conversion if long double is really double.
1778 if (&S.Context.getFloatTypeSemantics(FromType) !=
1779 &S.Context.getFloatTypeSemantics(ToType)) {
1780 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1781 ToType == S.Context.LongDoubleTy) ||
1782 (FromType == S.Context.LongDoubleTy &&
1783 ToType == S.Context.Float128Ty));
1784 if (Float128AndLongDouble &&
1785 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1786 &llvm::APFloat::PPCDoubleDouble()))
1787 return false;
1788 }
1789 // Floating point conversions (C++ 4.8).
1790 SCS.Second = ICK_Floating_Conversion;
1791 FromType = ToType.getUnqualifiedType();
1792 } else if ((FromType->isRealFloatingType() &&
1793 ToType->isIntegralType(S.Context)) ||
1794 (FromType->isIntegralOrUnscopedEnumerationType() &&
1795 ToType->isRealFloatingType())) {
1796 // Floating-integral conversions (C++ 4.9).
1797 SCS.Second = ICK_Floating_Integral;
1798 FromType = ToType.getUnqualifiedType();
1799 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1800 SCS.Second = ICK_Block_Pointer_Conversion;
1801 } else if (AllowObjCWritebackConversion &&
1802 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1803 SCS.Second = ICK_Writeback_Conversion;
1804 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1805 FromType, IncompatibleObjC)) {
1806 // Pointer conversions (C++ 4.10).
1807 SCS.Second = ICK_Pointer_Conversion;
1808 SCS.IncompatibleObjC = IncompatibleObjC;
1809 FromType = FromType.getUnqualifiedType();
1810 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1811 InOverloadResolution, FromType)) {
1812 // Pointer to member conversions (4.11).
1813 SCS.Second = ICK_Pointer_Member;
1814 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1815 SCS.Second = SecondICK;
1816 FromType = ToType.getUnqualifiedType();
1817 } else if (!S.getLangOpts().CPlusPlus &&
1818 S.Context.typesAreCompatible(ToType, FromType)) {
1819 // Compatible conversions (Clang extension for C function overloading)
1820 SCS.Second = ICK_Compatible_Conversion;
1821 FromType = ToType.getUnqualifiedType();
1822 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1823 InOverloadResolution,
1824 SCS, CStyle)) {
1825 SCS.Second = ICK_TransparentUnionConversion;
1826 FromType = ToType;
1827 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1828 CStyle)) {
1829 // tryAtomicConversion has updated the standard conversion sequence
1830 // appropriately.
1831 return true;
1832 } else if (ToType->isEventT() &&
1833 From->isIntegerConstantExpr(S.getASTContext()) &&
1834 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1835 SCS.Second = ICK_Zero_Event_Conversion;
1836 FromType = ToType;
1837 } else if (ToType->isQueueT() &&
1838 From->isIntegerConstantExpr(S.getASTContext()) &&
1839 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1840 SCS.Second = ICK_Zero_Queue_Conversion;
1841 FromType = ToType;
1842 } else {
1843 // No second conversion required.
1844 SCS.Second = ICK_Identity;
1845 }
1846 SCS.setToType(1, FromType);
1847
1848 // The third conversion can be a function pointer conversion or a
1849 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1850 bool ObjCLifetimeConversion;
1851 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1852 // Function pointer conversions (removing 'noexcept') including removal of
1853 // 'noreturn' (Clang extension).
1854 SCS.Third = ICK_Function_Conversion;
1855 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1856 ObjCLifetimeConversion)) {
1857 SCS.Third = ICK_Qualification;
1858 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1859 FromType = ToType;
1860 } else {
1861 // No conversion required
1862 SCS.Third = ICK_Identity;
1863 }
1864
1865 // C++ [over.best.ics]p6:
1866 // [...] Any difference in top-level cv-qualification is
1867 // subsumed by the initialization itself and does not constitute
1868 // a conversion. [...]
1869 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1870 QualType CanonTo = S.Context.getCanonicalType(ToType);
1871 if (CanonFrom.getLocalUnqualifiedType()
1872 == CanonTo.getLocalUnqualifiedType() &&
1873 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1874 FromType = ToType;
1875 CanonFrom = CanonTo;
1876 }
1877
1878 SCS.setToType(2, FromType);
1879
1880 if (CanonFrom == CanonTo)
1881 return true;
1882
1883 // If we have not converted the argument type to the parameter type,
1884 // this is a bad conversion sequence, unless we're resolving an overload in C.
1885 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1886 return false;
1887
1888 ExprResult ER = ExprResult{From};
1889 Sema::AssignConvertType Conv =
1890 S.CheckSingleAssignmentConstraints(ToType, ER,
1891 /*Diagnose=*/false,
1892 /*DiagnoseCFAudited=*/false,
1893 /*ConvertRHS=*/false);
1894 ImplicitConversionKind SecondConv;
1895 switch (Conv) {
1896 case Sema::Compatible:
1897 SecondConv = ICK_C_Only_Conversion;
1898 break;
1899 // For our purposes, discarding qualifiers is just as bad as using an
1900 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1901 // qualifiers, as well.
1902 case Sema::CompatiblePointerDiscardsQualifiers:
1903 case Sema::IncompatiblePointer:
1904 case Sema::IncompatiblePointerSign:
1905 SecondConv = ICK_Incompatible_Pointer_Conversion;
1906 break;
1907 default:
1908 return false;
1909 }
1910
1911 // First can only be an lvalue conversion, so we pretend that this was the
1912 // second conversion. First should already be valid from earlier in the
1913 // function.
1914 SCS.Second = SecondConv;
1915 SCS.setToType(1, ToType);
1916
1917 // Third is Identity, because Second should rank us worse than any other
1918 // conversion. This could also be ICK_Qualification, but it's simpler to just
1919 // lump everything in with the second conversion, and we don't gain anything
1920 // from making this ICK_Qualification.
1921 SCS.Third = ICK_Identity;
1922 SCS.setToType(2, ToType);
1923 return true;
1924}
1925
1926static bool
1927IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1928 QualType &ToType,
1929 bool InOverloadResolution,
1930 StandardConversionSequence &SCS,
1931 bool CStyle) {
1932
1933 const RecordType *UT = ToType->getAsUnionType();
1934 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1935 return false;
1936 // The field to initialize within the transparent union.
1937 RecordDecl *UD = UT->getDecl();
1938 // It's compatible if the expression matches any of the fields.
1939 for (const auto *it : UD->fields()) {
1940 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1941 CStyle, /*ObjCWritebackConversion=*/false)) {
1942 ToType = it->getType();
1943 return true;
1944 }
1945 }
1946 return false;
1947}
1948
1949/// IsIntegralPromotion - Determines whether the conversion from the
1950/// expression From (whose potentially-adjusted type is FromType) to
1951/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1952/// sets PromotedType to the promoted type.
1953bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1954 const BuiltinType *To = ToType->getAs<BuiltinType>();
1955 // All integers are built-in.
1956 if (!To) {
1957 return false;
1958 }
1959
1960 // An rvalue of type char, signed char, unsigned char, short int, or
1961 // unsigned short int can be converted to an rvalue of type int if
1962 // int can represent all the values of the source type; otherwise,
1963 // the source rvalue can be converted to an rvalue of type unsigned
1964 // int (C++ 4.5p1).
1965 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1966 !FromType->isEnumeralType()) {
1967 if (// We can promote any signed, promotable integer type to an int
1968 (FromType->isSignedIntegerType() ||
1969 // We can promote any unsigned integer type whose size is
1970 // less than int to an int.
1971 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1972 return To->getKind() == BuiltinType::Int;
1973 }
1974
1975 return To->getKind() == BuiltinType::UInt;
1976 }
1977
1978 // C++11 [conv.prom]p3:
1979 // A prvalue of an unscoped enumeration type whose underlying type is not
1980 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1981 // following types that can represent all the values of the enumeration
1982 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1983 // unsigned int, long int, unsigned long int, long long int, or unsigned
1984 // long long int. If none of the types in that list can represent all the
1985 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1986 // type can be converted to an rvalue a prvalue of the extended integer type
1987 // with lowest integer conversion rank (4.13) greater than the rank of long
1988 // long in which all the values of the enumeration can be represented. If
1989 // there are two such extended types, the signed one is chosen.
1990 // C++11 [conv.prom]p4:
1991 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1992 // can be converted to a prvalue of its underlying type. Moreover, if
1993 // integral promotion can be applied to its underlying type, a prvalue of an
1994 // unscoped enumeration type whose underlying type is fixed can also be
1995 // converted to a prvalue of the promoted underlying type.
1996 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1997 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1998 // provided for a scoped enumeration.
1999 if (FromEnumType->getDecl()->isScoped())
2000 return false;
2001
2002 // We can perform an integral promotion to the underlying type of the enum,
2003 // even if that's not the promoted type. Note that the check for promoting
2004 // the underlying type is based on the type alone, and does not consider
2005 // the bitfield-ness of the actual source expression.
2006 if (FromEnumType->getDecl()->isFixed()) {
2007 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2008 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2009 IsIntegralPromotion(nullptr, Underlying, ToType);
2010 }
2011
2012 // We have already pre-calculated the promotion type, so this is trivial.
2013 if (ToType->isIntegerType() &&
2014 isCompleteType(From->getLocStart(), FromType))
2015 return Context.hasSameUnqualifiedType(
2016 ToType, FromEnumType->getDecl()->getPromotionType());
2017
2018 // C++ [conv.prom]p5:
2019 // If the bit-field has an enumerated type, it is treated as any other
2020 // value of that type for promotion purposes.
2021 //
2022 // ... so do not fall through into the bit-field checks below in C++.
2023 if (getLangOpts().CPlusPlus)
2024 return false;
2025 }
2026
2027 // C++0x [conv.prom]p2:
2028 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2029 // to an rvalue a prvalue of the first of the following types that can
2030 // represent all the values of its underlying type: int, unsigned int,
2031 // long int, unsigned long int, long long int, or unsigned long long int.
2032 // If none of the types in that list can represent all the values of its
2033 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2034 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2035 // type.
2036 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2037 ToType->isIntegerType()) {
2038 // Determine whether the type we're converting from is signed or
2039 // unsigned.
2040 bool FromIsSigned = FromType->isSignedIntegerType();
2041 uint64_t FromSize = Context.getTypeSize(FromType);
2042
2043 // The types we'll try to promote to, in the appropriate
2044 // order. Try each of these types.
2045 QualType PromoteTypes[6] = {
2046 Context.IntTy, Context.UnsignedIntTy,
2047 Context.LongTy, Context.UnsignedLongTy ,
2048 Context.LongLongTy, Context.UnsignedLongLongTy
2049 };
2050 for (int Idx = 0; Idx < 6; ++Idx) {
2051 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2052 if (FromSize < ToSize ||
2053 (FromSize == ToSize &&
2054 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2055 // We found the type that we can promote to. If this is the
2056 // type we wanted, we have a promotion. Otherwise, no
2057 // promotion.
2058 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2059 }
2060 }
2061 }
2062
2063 // An rvalue for an integral bit-field (9.6) can be converted to an
2064 // rvalue of type int if int can represent all the values of the
2065 // bit-field; otherwise, it can be converted to unsigned int if
2066 // unsigned int can represent all the values of the bit-field. If
2067 // the bit-field is larger yet, no integral promotion applies to
2068 // it. If the bit-field has an enumerated type, it is treated as any
2069 // other value of that type for promotion purposes (C++ 4.5p3).
2070 // FIXME: We should delay checking of bit-fields until we actually perform the
2071 // conversion.
2072 //
2073 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2074 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2075 // bit-fields and those whose underlying type is larger than int) for GCC
2076 // compatibility.
2077 if (From) {
2078 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2079 llvm::APSInt BitWidth;
2080 if (FromType->isIntegralType(Context) &&
2081 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2082 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2083 ToSize = Context.getTypeSize(ToType);
2084
2085 // Are we promoting to an int from a bitfield that fits in an int?
2086 if (BitWidth < ToSize ||
2087 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2088 return To->getKind() == BuiltinType::Int;
2089 }
2090
2091 // Are we promoting to an unsigned int from an unsigned bitfield
2092 // that fits into an unsigned int?
2093 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2094 return To->getKind() == BuiltinType::UInt;
2095 }
2096
2097 return false;
2098 }
2099 }
2100 }
2101
2102 // An rvalue of type bool can be converted to an rvalue of type int,
2103 // with false becoming zero and true becoming one (C++ 4.5p4).
2104 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2105 return true;
2106 }
2107
2108 return false;
2109}
2110
2111/// IsFloatingPointPromotion - Determines whether the conversion from
2112/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2113/// returns true and sets PromotedType to the promoted type.
2114bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2115 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2116 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2117 /// An rvalue of type float can be converted to an rvalue of type
2118 /// double. (C++ 4.6p1).
2119 if (FromBuiltin->getKind() == BuiltinType::Float &&
2120 ToBuiltin->getKind() == BuiltinType::Double)
2121 return true;
2122
2123 // C99 6.3.1.5p1:
2124 // When a float is promoted to double or long double, or a
2125 // double is promoted to long double [...].
2126 if (!getLangOpts().CPlusPlus &&
2127 (FromBuiltin->getKind() == BuiltinType::Float ||
2128 FromBuiltin->getKind() == BuiltinType::Double) &&
2129 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2130 ToBuiltin->getKind() == BuiltinType::Float128))
2131 return true;
2132
2133 // Half can be promoted to float.
2134 if (!getLangOpts().NativeHalfType &&
2135 FromBuiltin->getKind() == BuiltinType::Half &&
2136 ToBuiltin->getKind() == BuiltinType::Float)
2137 return true;
2138 }
2139
2140 return false;
2141}
2142
2143/// Determine if a conversion is a complex promotion.
2144///
2145/// A complex promotion is defined as a complex -> complex conversion
2146/// where the conversion between the underlying real types is a
2147/// floating-point or integral promotion.
2148bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2149 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2150 if (!FromComplex)
2151 return false;
2152
2153 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2154 if (!ToComplex)
2155 return false;
2156
2157 return IsFloatingPointPromotion(FromComplex->getElementType(),
2158 ToComplex->getElementType()) ||
2159 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2160 ToComplex->getElementType());
2161}
2162
2163/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2164/// the pointer type FromPtr to a pointer to type ToPointee, with the
2165/// same type qualifiers as FromPtr has on its pointee type. ToType,
2166/// if non-empty, will be a pointer to ToType that may or may not have
2167/// the right set of qualifiers on its pointee.
2168///
2169static QualType
2170BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2171 QualType ToPointee, QualType ToType,
2172 ASTContext &Context,
2173 bool StripObjCLifetime = false) {
2174 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2176, __extension__ __PRETTY_FUNCTION__))
2175 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2176, __extension__ __PRETTY_FUNCTION__))
2176 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2176, __extension__ __PRETTY_FUNCTION__))
;
2177
2178 /// Conversions to 'id' subsume cv-qualifier conversions.
2179 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2180 return ToType.getUnqualifiedType();
2181
2182 QualType CanonFromPointee
2183 = Context.getCanonicalType(FromPtr->getPointeeType());
2184 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2185 Qualifiers Quals = CanonFromPointee.getQualifiers();
2186
2187 if (StripObjCLifetime)
2188 Quals.removeObjCLifetime();
2189
2190 // Exact qualifier match -> return the pointer type we're converting to.
2191 if (CanonToPointee.getLocalQualifiers() == Quals) {
2192 // ToType is exactly what we need. Return it.
2193 if (!ToType.isNull())
2194 return ToType.getUnqualifiedType();
2195
2196 // Build a pointer to ToPointee. It has the right qualifiers
2197 // already.
2198 if (isa<ObjCObjectPointerType>(ToType))
2199 return Context.getObjCObjectPointerType(ToPointee);
2200 return Context.getPointerType(ToPointee);
2201 }
2202
2203 // Just build a canonical type that has the right qualifiers.
2204 QualType QualifiedCanonToPointee
2205 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2206
2207 if (isa<ObjCObjectPointerType>(ToType))
2208 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2209 return Context.getPointerType(QualifiedCanonToPointee);
2210}
2211
2212static bool isNullPointerConstantForConversion(Expr *Expr,
2213 bool InOverloadResolution,
2214 ASTContext &Context) {
2215 // Handle value-dependent integral null pointer constants correctly.
2216 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2217 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2218 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2219 return !InOverloadResolution;
2220
2221 return Expr->isNullPointerConstant(Context,
2222 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2223 : Expr::NPC_ValueDependentIsNull);
2224}
2225
2226/// IsPointerConversion - Determines whether the conversion of the
2227/// expression From, which has the (possibly adjusted) type FromType,
2228/// can be converted to the type ToType via a pointer conversion (C++
2229/// 4.10). If so, returns true and places the converted type (that
2230/// might differ from ToType in its cv-qualifiers at some level) into
2231/// ConvertedType.
2232///
2233/// This routine also supports conversions to and from block pointers
2234/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2235/// pointers to interfaces. FIXME: Once we've determined the
2236/// appropriate overloading rules for Objective-C, we may want to
2237/// split the Objective-C checks into a different routine; however,
2238/// GCC seems to consider all of these conversions to be pointer
2239/// conversions, so for now they live here. IncompatibleObjC will be
2240/// set if the conversion is an allowed Objective-C conversion that
2241/// should result in a warning.
2242bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2243 bool InOverloadResolution,
2244 QualType& ConvertedType,
2245 bool &IncompatibleObjC) {
2246 IncompatibleObjC = false;
2247 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2248 IncompatibleObjC))
2249 return true;
2250
2251 // Conversion from a null pointer constant to any Objective-C pointer type.
2252 if (ToType->isObjCObjectPointerType() &&
2253 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2254 ConvertedType = ToType;
2255 return true;
2256 }
2257
2258 // Blocks: Block pointers can be converted to void*.
2259 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2260 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2261 ConvertedType = ToType;
2262 return true;
2263 }
2264 // Blocks: A null pointer constant can be converted to a block
2265 // pointer type.
2266 if (ToType->isBlockPointerType() &&
2267 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2268 ConvertedType = ToType;
2269 return true;
2270 }
2271
2272 // If the left-hand-side is nullptr_t, the right side can be a null
2273 // pointer constant.
2274 if (ToType->isNullPtrType() &&
2275 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2276 ConvertedType = ToType;
2277 return true;
2278 }
2279
2280 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2281 if (!ToTypePtr)
2282 return false;
2283
2284 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2285 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2286 ConvertedType = ToType;
2287 return true;
2288 }
2289
2290 // Beyond this point, both types need to be pointers
2291 // , including objective-c pointers.
2292 QualType ToPointeeType = ToTypePtr->getPointeeType();
2293 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2294 !getLangOpts().ObjCAutoRefCount) {
2295 ConvertedType = BuildSimilarlyQualifiedPointerType(
2296 FromType->getAs<ObjCObjectPointerType>(),
2297 ToPointeeType,
2298 ToType, Context);
2299 return true;
2300 }
2301 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2302 if (!FromTypePtr)
2303 return false;
2304
2305 QualType FromPointeeType = FromTypePtr->getPointeeType();
2306
2307 // If the unqualified pointee types are the same, this can't be a
2308 // pointer conversion, so don't do all of the work below.
2309 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2310 return false;
2311
2312 // An rvalue of type "pointer to cv T," where T is an object type,
2313 // can be converted to an rvalue of type "pointer to cv void" (C++
2314 // 4.10p2).
2315 if (FromPointeeType->isIncompleteOrObjectType() &&
2316 ToPointeeType->isVoidType()) {
2317 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2318 ToPointeeType,
2319 ToType, Context,
2320 /*StripObjCLifetime=*/true);
2321 return true;
2322 }
2323
2324 // MSVC allows implicit function to void* type conversion.
2325 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2326 ToPointeeType->isVoidType()) {
2327 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2328 ToPointeeType,
2329 ToType, Context);
2330 return true;
2331 }
2332
2333 // When we're overloading in C, we allow a special kind of pointer
2334 // conversion for compatible-but-not-identical pointee types.
2335 if (!getLangOpts().CPlusPlus &&
2336 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2337 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2338 ToPointeeType,
2339 ToType, Context);
2340 return true;
2341 }
2342
2343 // C++ [conv.ptr]p3:
2344 //
2345 // An rvalue of type "pointer to cv D," where D is a class type,
2346 // can be converted to an rvalue of type "pointer to cv B," where
2347 // B is a base class (clause 10) of D. If B is an inaccessible
2348 // (clause 11) or ambiguous (10.2) base class of D, a program that
2349 // necessitates this conversion is ill-formed. The result of the
2350 // conversion is a pointer to the base class sub-object of the
2351 // derived class object. The null pointer value is converted to
2352 // the null pointer value of the destination type.
2353 //
2354 // Note that we do not check for ambiguity or inaccessibility
2355 // here. That is handled by CheckPointerConversion.
2356 if (getLangOpts().CPlusPlus &&
2357 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2358 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2359 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2360 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2361 ToPointeeType,
2362 ToType, Context);
2363 return true;
2364 }
2365
2366 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2367 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2368 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2369 ToPointeeType,
2370 ToType, Context);
2371 return true;
2372 }
2373
2374 return false;
2375}
2376
2377/// Adopt the given qualifiers for the given type.
2378static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2379 Qualifiers TQs = T.getQualifiers();
2380
2381 // Check whether qualifiers already match.
2382 if (TQs == Qs)
2383 return T;
2384
2385 if (Qs.compatiblyIncludes(TQs))
2386 return Context.getQualifiedType(T, Qs);
2387
2388 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2389}
2390
2391/// isObjCPointerConversion - Determines whether this is an
2392/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2393/// with the same arguments and return values.
2394bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2395 QualType& ConvertedType,
2396 bool &IncompatibleObjC) {
2397 if (!getLangOpts().ObjC1)
2398 return false;
2399
2400 // The set of qualifiers on the type we're converting from.
2401 Qualifiers FromQualifiers = FromType.getQualifiers();
2402
2403 // First, we handle all conversions on ObjC object pointer types.
2404 const ObjCObjectPointerType* ToObjCPtr =
2405 ToType->getAs<ObjCObjectPointerType>();
2406 const ObjCObjectPointerType *FromObjCPtr =
2407 FromType->getAs<ObjCObjectPointerType>();
2408
2409 if (ToObjCPtr && FromObjCPtr) {
2410 // If the pointee types are the same (ignoring qualifications),
2411 // then this is not a pointer conversion.
2412 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2413 FromObjCPtr->getPointeeType()))
2414 return false;
2415
2416 // Conversion between Objective-C pointers.
2417 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2418 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2419 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2420 if (getLangOpts().CPlusPlus && LHS && RHS &&
2421 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2422 FromObjCPtr->getPointeeType()))
2423 return false;
2424 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2425 ToObjCPtr->getPointeeType(),
2426 ToType, Context);
2427 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2428 return true;
2429 }
2430
2431 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2432 // Okay: this is some kind of implicit downcast of Objective-C
2433 // interfaces, which is permitted. However, we're going to
2434 // complain about it.
2435 IncompatibleObjC = true;
2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2437 ToObjCPtr->getPointeeType(),
2438 ToType, Context);
2439 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2440 return true;
2441 }
2442 }
2443 // Beyond this point, both types need to be C pointers or block pointers.
2444 QualType ToPointeeType;
2445 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2446 ToPointeeType = ToCPtr->getPointeeType();
2447 else if (const BlockPointerType *ToBlockPtr =
2448 ToType->getAs<BlockPointerType>()) {
2449 // Objective C++: We're able to convert from a pointer to any object
2450 // to a block pointer type.
2451 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2452 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2453 return true;
2454 }
2455 ToPointeeType = ToBlockPtr->getPointeeType();
2456 }
2457 else if (FromType->getAs<BlockPointerType>() &&
2458 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2459 // Objective C++: We're able to convert from a block pointer type to a
2460 // pointer to any object.
2461 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2462 return true;
2463 }
2464 else
2465 return false;
2466
2467 QualType FromPointeeType;
2468 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2469 FromPointeeType = FromCPtr->getPointeeType();
2470 else if (const BlockPointerType *FromBlockPtr =
2471 FromType->getAs<BlockPointerType>())
2472 FromPointeeType = FromBlockPtr->getPointeeType();
2473 else
2474 return false;
2475
2476 // If we have pointers to pointers, recursively check whether this
2477 // is an Objective-C conversion.
2478 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2479 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2480 IncompatibleObjC)) {
2481 // We always complain about this conversion.
2482 IncompatibleObjC = true;
2483 ConvertedType = Context.getPointerType(ConvertedType);
2484 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2485 return true;
2486 }
2487 // Allow conversion of pointee being objective-c pointer to another one;
2488 // as in I* to id.
2489 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2490 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2491 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2492 IncompatibleObjC)) {
2493
2494 ConvertedType = Context.getPointerType(ConvertedType);
2495 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2496 return true;
2497 }
2498
2499 // If we have pointers to functions or blocks, check whether the only
2500 // differences in the argument and result types are in Objective-C
2501 // pointer conversions. If so, we permit the conversion (but
2502 // complain about it).
2503 const FunctionProtoType *FromFunctionType
2504 = FromPointeeType->getAs<FunctionProtoType>();
2505 const FunctionProtoType *ToFunctionType
2506 = ToPointeeType->getAs<FunctionProtoType>();
2507 if (FromFunctionType && ToFunctionType) {
2508 // If the function types are exactly the same, this isn't an
2509 // Objective-C pointer conversion.
2510 if (Context.getCanonicalType(FromPointeeType)
2511 == Context.getCanonicalType(ToPointeeType))
2512 return false;
2513
2514 // Perform the quick checks that will tell us whether these
2515 // function types are obviously different.
2516 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2517 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2518 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2519 return false;
2520
2521 bool HasObjCConversion = false;
2522 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2523 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2524 // Okay, the types match exactly. Nothing to do.
2525 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2526 ToFunctionType->getReturnType(),
2527 ConvertedType, IncompatibleObjC)) {
2528 // Okay, we have an Objective-C pointer conversion.
2529 HasObjCConversion = true;
2530 } else {
2531 // Function types are too different. Abort.
2532 return false;
2533 }
2534
2535 // Check argument types.
2536 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2537 ArgIdx != NumArgs; ++ArgIdx) {
2538 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2539 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2540 if (Context.getCanonicalType(FromArgType)
2541 == Context.getCanonicalType(ToArgType)) {
2542 // Okay, the types match exactly. Nothing to do.
2543 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2544 ConvertedType, IncompatibleObjC)) {
2545 // Okay, we have an Objective-C pointer conversion.
2546 HasObjCConversion = true;
2547 } else {
2548 // Argument types are too different. Abort.
2549 return false;
2550 }
2551 }
2552
2553 if (HasObjCConversion) {
2554 // We had an Objective-C conversion. Allow this pointer
2555 // conversion, but complain about it.
2556 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2557 IncompatibleObjC = true;
2558 return true;
2559 }
2560 }
2561
2562 return false;
2563}
2564
2565/// Determine whether this is an Objective-C writeback conversion,
2566/// used for parameter passing when performing automatic reference counting.
2567///
2568/// \param FromType The type we're converting form.
2569///
2570/// \param ToType The type we're converting to.
2571///
2572/// \param ConvertedType The type that will be produced after applying
2573/// this conversion.
2574bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2575 QualType &ConvertedType) {
2576 if (!getLangOpts().ObjCAutoRefCount ||
2577 Context.hasSameUnqualifiedType(FromType, ToType))
2578 return false;
2579
2580 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2581 QualType ToPointee;
2582 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2583 ToPointee = ToPointer->getPointeeType();
2584 else
2585 return false;
2586
2587 Qualifiers ToQuals = ToPointee.getQualifiers();
2588 if (!ToPointee->isObjCLifetimeType() ||
2589 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2590 !ToQuals.withoutObjCLifetime().empty())
2591 return false;
2592
2593 // Argument must be a pointer to __strong to __weak.
2594 QualType FromPointee;
2595 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2596 FromPointee = FromPointer->getPointeeType();
2597 else
2598 return false;
2599
2600 Qualifiers FromQuals = FromPointee.getQualifiers();
2601 if (!FromPointee->isObjCLifetimeType() ||
2602 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2603 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2604 return false;
2605
2606 // Make sure that we have compatible qualifiers.
2607 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2608 if (!ToQuals.compatiblyIncludes(FromQuals))
2609 return false;
2610
2611 // Remove qualifiers from the pointee type we're converting from; they
2612 // aren't used in the compatibility check belong, and we'll be adding back
2613 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2614 FromPointee = FromPointee.getUnqualifiedType();
2615
2616 // The unqualified form of the pointee types must be compatible.
2617 ToPointee = ToPointee.getUnqualifiedType();
2618 bool IncompatibleObjC;
2619 if (Context.typesAreCompatible(FromPointee, ToPointee))
2620 FromPointee = ToPointee;
2621 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2622 IncompatibleObjC))
2623 return false;
2624
2625 /// Construct the type we're converting to, which is a pointer to
2626 /// __autoreleasing pointee.
2627 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2628 ConvertedType = Context.getPointerType(FromPointee);
2629 return true;
2630}
2631
2632bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2633 QualType& ConvertedType) {
2634 QualType ToPointeeType;
2635 if (const BlockPointerType *ToBlockPtr =
2636 ToType->getAs<BlockPointerType>())
2637 ToPointeeType = ToBlockPtr->getPointeeType();
2638 else
2639 return false;
2640
2641 QualType FromPointeeType;
2642 if (const BlockPointerType *FromBlockPtr =
2643 FromType->getAs<BlockPointerType>())
2644 FromPointeeType = FromBlockPtr->getPointeeType();
2645 else
2646 return false;
2647 // We have pointer to blocks, check whether the only
2648 // differences in the argument and result types are in Objective-C
2649 // pointer conversions. If so, we permit the conversion.
2650
2651 const FunctionProtoType *FromFunctionType
2652 = FromPointeeType->getAs<FunctionProtoType>();
2653 const FunctionProtoType *ToFunctionType
2654 = ToPointeeType->getAs<FunctionProtoType>();
2655
2656 if (!FromFunctionType || !ToFunctionType)
2657 return false;
2658
2659 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2660 return true;
2661
2662 // Perform the quick checks that will tell us whether these
2663 // function types are obviously different.
2664 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2665 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2666 return false;
2667
2668 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2669 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2670 if (FromEInfo != ToEInfo)
2671 return false;
2672
2673 bool IncompatibleObjC = false;
2674 if (Context.hasSameType(FromFunctionType->getReturnType(),
2675 ToFunctionType->getReturnType())) {
2676 // Okay, the types match exactly. Nothing to do.
2677 } else {
2678 QualType RHS = FromFunctionType->getReturnType();
2679 QualType LHS = ToFunctionType->getReturnType();
2680 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2681 !RHS.hasQualifiers() && LHS.hasQualifiers())
2682 LHS = LHS.getUnqualifiedType();
2683
2684 if (Context.hasSameType(RHS,LHS)) {
2685 // OK exact match.
2686 } else if (isObjCPointerConversion(RHS, LHS,
2687 ConvertedType, IncompatibleObjC)) {
2688 if (IncompatibleObjC)
2689 return false;
2690 // Okay, we have an Objective-C pointer conversion.
2691 }
2692 else
2693 return false;
2694 }
2695
2696 // Check argument types.
2697 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2698 ArgIdx != NumArgs; ++ArgIdx) {
2699 IncompatibleObjC = false;
2700 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2701 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2702 if (Context.hasSameType(FromArgType, ToArgType)) {
2703 // Okay, the types match exactly. Nothing to do.
2704 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2705 ConvertedType, IncompatibleObjC)) {
2706 if (IncompatibleObjC)
2707 return false;
2708 // Okay, we have an Objective-C pointer conversion.
2709 } else
2710 // Argument types are too different. Abort.
2711 return false;
2712 }
2713
2714 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2715 bool CanUseToFPT, CanUseFromFPT;
2716 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2717 CanUseToFPT, CanUseFromFPT,
2718 NewParamInfos))
2719 return false;
2720
2721 ConvertedType = ToType;
2722 return true;
2723}
2724
2725enum {
2726 ft_default,
2727 ft_different_class,
2728 ft_parameter_arity,
2729 ft_parameter_mismatch,
2730 ft_return_type,
2731 ft_qualifer_mismatch,
2732 ft_noexcept
2733};
2734
2735/// Attempts to get the FunctionProtoType from a Type. Handles
2736/// MemberFunctionPointers properly.
2737static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2738 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2739 return FPT;
2740
2741 if (auto *MPT = FromType->getAs<MemberPointerType>())
2742 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2743
2744 return nullptr;
2745}
2746
2747/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2748/// function types. Catches different number of parameter, mismatch in
2749/// parameter types, and different return types.
2750void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2751 QualType FromType, QualType ToType) {
2752 // If either type is not valid, include no extra info.
2753 if (FromType.isNull() || ToType.isNull()) {
2754 PDiag << ft_default;
2755 return;
2756 }
2757
2758 // Get the function type from the pointers.
2759 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2760 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2761 *ToMember = ToType->getAs<MemberPointerType>();
2762 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2763 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2764 << QualType(FromMember->getClass(), 0);
2765 return;
2766 }
2767 FromType = FromMember->getPointeeType();
2768 ToType = ToMember->getPointeeType();
2769 }
2770
2771 if (FromType->isPointerType())
2772 FromType = FromType->getPointeeType();
2773 if (ToType->isPointerType())
2774 ToType = ToType->getPointeeType();
2775
2776 // Remove references.
2777 FromType = FromType.getNonReferenceType();
2778 ToType = ToType.getNonReferenceType();
2779
2780 // Don't print extra info for non-specialized template functions.
2781 if (FromType->isInstantiationDependentType() &&
2782 !FromType->getAs<TemplateSpecializationType>()) {
2783 PDiag << ft_default;
2784 return;
2785 }
2786
2787 // No extra info for same types.
2788 if (Context.hasSameType(FromType, ToType)) {
2789 PDiag << ft_default;
2790 return;
2791 }
2792
2793 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2794 *ToFunction = tryGetFunctionProtoType(ToType);
2795
2796 // Both types need to be function types.
2797 if (!FromFunction || !ToFunction) {
2798 PDiag << ft_default;
2799 return;
2800 }
2801
2802 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2803 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2804 << FromFunction->getNumParams();
2805 return;
2806 }
2807
2808 // Handle different parameter types.
2809 unsigned ArgPos;
2810 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2811 PDiag << ft_parameter_mismatch << ArgPos + 1
2812 << ToFunction->getParamType(ArgPos)
2813 << FromFunction->getParamType(ArgPos);
2814 return;
2815 }
2816
2817 // Handle different return type.
2818 if (!Context.hasSameType(FromFunction->getReturnType(),
2819 ToFunction->getReturnType())) {
2820 PDiag << ft_return_type << ToFunction->getReturnType()
2821 << FromFunction->getReturnType();
2822 return;
2823 }
2824
2825 unsigned FromQuals = FromFunction->getTypeQuals(),
2826 ToQuals = ToFunction->getTypeQuals();
2827 if (FromQuals != ToQuals) {
2828 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2829 return;
2830 }
2831
2832 // Handle exception specification differences on canonical type (in C++17
2833 // onwards).
2834 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2835 ->isNothrow() !=
2836 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2837 ->isNothrow()) {
2838 PDiag << ft_noexcept;
2839 return;
2840 }
2841
2842 // Unable to find a difference, so add no extra info.
2843 PDiag << ft_default;
2844}
2845
2846/// FunctionParamTypesAreEqual - This routine checks two function proto types
2847/// for equality of their argument types. Caller has already checked that
2848/// they have same number of arguments. If the parameters are different,
2849/// ArgPos will have the parameter index of the first different parameter.
2850bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2851 const FunctionProtoType *NewType,
2852 unsigned *ArgPos) {
2853 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2854 N = NewType->param_type_begin(),
2855 E = OldType->param_type_end();
2856 O && (O != E); ++O, ++N) {
2857 if (!Context.hasSameType(O->getUnqualifiedType(),
2858 N->getUnqualifiedType())) {
2859 if (ArgPos)
2860 *ArgPos = O - OldType->param_type_begin();
2861 return false;
2862 }
2863 }
2864 return true;
2865}
2866
2867/// CheckPointerConversion - Check the pointer conversion from the
2868/// expression From to the type ToType. This routine checks for
2869/// ambiguous or inaccessible derived-to-base pointer
2870/// conversions for which IsPointerConversion has already returned
2871/// true. It returns true and produces a diagnostic if there was an
2872/// error, or returns false otherwise.
2873bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2874 CastKind &Kind,
2875 CXXCastPath& BasePath,
2876 bool IgnoreBaseAccess,
2877 bool Diagnose) {
2878 QualType FromType = From->getType();
2879 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2880
2881 Kind = CK_BitCast;
2882
2883 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2884 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2885 Expr::NPCK_ZeroExpression) {
2886 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2887 DiagRuntimeBehavior(From->getExprLoc(), From,
2888 PDiag(diag::warn_impcast_bool_to_null_pointer)
2889 << ToType << From->getSourceRange());
2890 else if (!isUnevaluatedContext())
2891 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2892 << ToType << From->getSourceRange();
2893 }
2894 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2895 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2896 QualType FromPointeeType = FromPtrType->getPointeeType(),
2897 ToPointeeType = ToPtrType->getPointeeType();
2898
2899 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2900 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2901 // We must have a derived-to-base conversion. Check an
2902 // ambiguous or inaccessible conversion.
2903 unsigned InaccessibleID = 0;
2904 unsigned AmbigiousID = 0;
2905 if (Diagnose) {
2906 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2907 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2908 }
2909 if (CheckDerivedToBaseConversion(
2910 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2911 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2912 &BasePath, IgnoreBaseAccess))
2913 return true;
2914
2915 // The conversion was successful.
2916 Kind = CK_DerivedToBase;
2917 }
2918
2919 if (Diagnose && !IsCStyleOrFunctionalCast &&
2920 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2921 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2922, __extension__ __PRETTY_FUNCTION__))
2922 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2922, __extension__ __PRETTY_FUNCTION__))
;
2923 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2924 << From->getSourceRange();
2925 }
2926 }
2927 } else if (const ObjCObjectPointerType *ToPtrType =
2928 ToType->getAs<ObjCObjectPointerType>()) {
2929 if (const ObjCObjectPointerType *FromPtrType =
2930 FromType->getAs<ObjCObjectPointerType>()) {
2931 // Objective-C++ conversions are always okay.
2932 // FIXME: We should have a different class of conversions for the
2933 // Objective-C++ implicit conversions.
2934 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2935 return false;
2936 } else if (FromType->isBlockPointerType()) {
2937 Kind = CK_BlockPointerToObjCPointerCast;
2938 } else {
2939 Kind = CK_CPointerToObjCPointerCast;
2940 }
2941 } else if (ToType->isBlockPointerType()) {
2942 if (!FromType->isBlockPointerType())
2943 Kind = CK_AnyPointerToBlockPointerCast;
2944 }
2945
2946 // We shouldn't fall into this case unless it's valid for other
2947 // reasons.
2948 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2949 Kind = CK_NullToPointer;
2950
2951 return false;
2952}
2953
2954/// IsMemberPointerConversion - Determines whether the conversion of the
2955/// expression From, which has the (possibly adjusted) type FromType, can be
2956/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2957/// If so, returns true and places the converted type (that might differ from
2958/// ToType in its cv-qualifiers at some level) into ConvertedType.
2959bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2960 QualType ToType,
2961 bool InOverloadResolution,
2962 QualType &ConvertedType) {
2963 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2964 if (!ToTypePtr)
2965 return false;
2966
2967 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2968 if (From->isNullPointerConstant(Context,
2969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2970 : Expr::NPC_ValueDependentIsNull)) {
2971 ConvertedType = ToType;
2972 return true;
2973 }
2974
2975 // Otherwise, both types have to be member pointers.
2976 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2977 if (!FromTypePtr)
2978 return false;
2979
2980 // A pointer to member of B can be converted to a pointer to member of D,
2981 // where D is derived from B (C++ 4.11p2).
2982 QualType FromClass(FromTypePtr->getClass(), 0);
2983 QualType ToClass(ToTypePtr->getClass(), 0);
2984
2985 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2986 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2987 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2988 ToClass.getTypePtr());
2989 return true;
2990 }
2991
2992 return false;
2993}
2994
2995/// CheckMemberPointerConversion - Check the member pointer conversion from the
2996/// expression From to the type ToType. This routine checks for ambiguous or
2997/// virtual or inaccessible base-to-derived member pointer conversions
2998/// for which IsMemberPointerConversion has already returned true. It returns
2999/// true and produces a diagnostic if there was an error, or returns false
3000/// otherwise.
3001bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3002 CastKind &Kind,
3003 CXXCastPath &BasePath,
3004 bool IgnoreBaseAccess) {
3005 QualType FromType = From->getType();
3006 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3007 if (!FromPtrType) {
3008 // This must be a null pointer to member pointer conversion
3009 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3011, __extension__ __PRETTY_FUNCTION__))
3010 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3011, __extension__ __PRETTY_FUNCTION__))
3011 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3011, __extension__ __PRETTY_FUNCTION__))
;
3012 Kind = CK_NullToMemberPointer;
3013 return false;
3014 }
3015
3016 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3017 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
3018 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
;
3019
3020 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3021 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3022
3023 // FIXME: What about dependent types?
3024 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3024, __extension__ __PRETTY_FUNCTION__))
;
3025 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3025, __extension__ __PRETTY_FUNCTION__))
;
3026
3027 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3028 /*DetectVirtual=*/true);
3029 bool DerivationOkay =
3030 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
3031 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3032, __extension__ __PRETTY_FUNCTION__))
3032 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3032, __extension__ __PRETTY_FUNCTION__))
;
3033 (void)DerivationOkay;
3034
3035 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3036 getUnqualifiedType())) {
3037 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3038 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3039 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3040 return true;
3041 }
3042
3043 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3044 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3045 << FromClass << ToClass << QualType(VBase, 0)
3046 << From->getSourceRange();
3047 return true;
3048 }
3049
3050 if (!IgnoreBaseAccess)
3051 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3052 Paths.front(),
3053 diag::err_downcast_from_inaccessible_base);
3054
3055 // Must be a base to derived member conversion.
3056 BuildBasePathArray(Paths, BasePath);
3057 Kind = CK_BaseToDerivedMemberPointer;
3058 return false;
3059}
3060
3061/// Determine whether the lifetime conversion between the two given
3062/// qualifiers sets is nontrivial.
3063static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3064 Qualifiers ToQuals) {
3065 // Converting anything to const __unsafe_unretained is trivial.
3066 if (ToQuals.hasConst() &&
3067 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3068 return false;
3069
3070 return true;
3071}
3072
3073/// IsQualificationConversion - Determines whether the conversion from
3074/// an rvalue of type FromType to ToType is a qualification conversion
3075/// (C++ 4.4).
3076///
3077/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3078/// when the qualification conversion involves a change in the Objective-C
3079/// object lifetime.
3080bool
3081Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3082 bool CStyle, bool &ObjCLifetimeConversion) {
3083 FromType = Context.getCanonicalType(FromType);
3084 ToType = Context.getCanonicalType(ToType);
3085 ObjCLifetimeConversion = false;
3086
3087 // If FromType and ToType are the same type, this is not a
3088 // qualification conversion.
3089 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3090 return false;
3091
3092 // (C++ 4.4p4):
3093 // A conversion can add cv-qualifiers at levels other than the first
3094 // in multi-level pointers, subject to the following rules: [...]
3095 bool PreviousToQualsIncludeConst = true;
3096 bool UnwrappedAnyPointer = false;
3097 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3098 // Within each iteration of the loop, we check the qualifiers to
3099 // determine if this still looks like a qualification
3100 // conversion. Then, if all is well, we unwrap one more level of
3101 // pointers or pointers-to-members and do it all again
3102 // until there are no more pointers or pointers-to-members left to
3103 // unwrap.
3104 UnwrappedAnyPointer = true;
3105
3106 Qualifiers FromQuals = FromType.getQualifiers();
3107 Qualifiers ToQuals = ToType.getQualifiers();
3108
3109 // Ignore __unaligned qualifier if this type is void.
3110 if (ToType.getUnqualifiedType()->isVoidType())
3111 FromQuals.removeUnaligned();
3112
3113 // Objective-C ARC:
3114 // Check Objective-C lifetime conversions.
3115 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3116 UnwrappedAnyPointer) {
3117 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3118 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3119 ObjCLifetimeConversion = true;
3120 FromQuals.removeObjCLifetime();
3121 ToQuals.removeObjCLifetime();
3122 } else {
3123 // Qualification conversions cannot cast between different
3124 // Objective-C lifetime qualifiers.
3125 return false;
3126 }
3127 }
3128
3129 // Allow addition/removal of GC attributes but not changing GC attributes.
3130 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3131 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3132 FromQuals.removeObjCGCAttr();
3133 ToQuals.removeObjCGCAttr();
3134 }
3135
3136 // -- for every j > 0, if const is in cv 1,j then const is in cv
3137 // 2,j, and similarly for volatile.
3138 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3139 return false;
3140
3141 // -- if the cv 1,j and cv 2,j are different, then const is in
3142 // every cv for 0 < k < j.
3143 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3144 && !PreviousToQualsIncludeConst)
3145 return false;
3146
3147 // Keep track of whether all prior cv-qualifiers in the "to" type
3148 // include const.
3149 PreviousToQualsIncludeConst
3150 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3151 }
3152
3153 // Allows address space promotion by language rules implemented in
3154 // Type::Qualifiers::isAddressSpaceSupersetOf.
3155 Qualifiers FromQuals = FromType.getQualifiers();
3156 Qualifiers ToQuals = ToType.getQualifiers();
3157 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3158 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3159 return false;
3160 }
3161
3162 // We are left with FromType and ToType being the pointee types
3163 // after unwrapping the original FromType and ToType the same number
3164 // of types. If we unwrapped any pointers, and if FromType and
3165 // ToType have the same unqualified type (since we checked
3166 // qualifiers above), then this is a qualification conversion.
3167 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3168}
3169
3170/// - Determine whether this is a conversion from a scalar type to an
3171/// atomic type.
3172///
3173/// If successful, updates \c SCS's second and third steps in the conversion
3174/// sequence to finish the conversion.
3175static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3176 bool InOverloadResolution,
3177 StandardConversionSequence &SCS,
3178 bool CStyle) {
3179 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3180 if (!ToAtomic)
3181 return false;
3182
3183 StandardConversionSequence InnerSCS;
3184 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3185 InOverloadResolution, InnerSCS,
3186 CStyle, /*AllowObjCWritebackConversion=*/false))
3187 return false;
3188
3189 SCS.Second = InnerSCS.Second;
3190 SCS.setToType(1, InnerSCS.getToType(1));
3191 SCS.Third = InnerSCS.Third;
3192 SCS.QualificationIncludesObjCLifetime
3193 = InnerSCS.QualificationIncludesObjCLifetime;
3194 SCS.setToType(2, InnerSCS.getToType(2));
3195 return true;
3196}
3197
3198static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3199 CXXConstructorDecl *Constructor,
3200 QualType Type) {
3201 const FunctionProtoType *CtorType =
3202 Constructor->getType()->getAs<FunctionProtoType>();
3203 if (CtorType->getNumParams() > 0) {
3204 QualType FirstArg = CtorType->getParamType(0);
3205 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3206 return true;
3207 }
3208 return false;
3209}
3210
3211static OverloadingResult
3212IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3213 CXXRecordDecl *To,
3214 UserDefinedConversionSequence &User,
3215 OverloadCandidateSet &CandidateSet,
3216 bool AllowExplicit) {
3217 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3218 for (auto *D : S.LookupConstructors(To)) {
3219 auto Info = getConstructorInfo(D);
3220 if (!Info)
3221 continue;
3222
3223 bool Usable = !Info.Constructor->isInvalidDecl() &&
3224 S.isInitListConstructor(Info.Constructor) &&
3225 (AllowExplicit || !Info.Constructor->isExplicit());
3226 if (Usable) {
3227 // If the first argument is (a reference to) the target type,
3228 // suppress conversions.
3229 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3230 S.Context, Info.Constructor, ToType);
3231 if (Info.ConstructorTmpl)
3232 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3233 /*ExplicitArgs*/ nullptr, From,
3234 CandidateSet, SuppressUserConversions);
3235 else
3236 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3237 CandidateSet, SuppressUserConversions);
3238 }
3239 }
3240
3241 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3242
3243 OverloadCandidateSet::iterator Best;
3244 switch (auto Result =
3245 CandidateSet.BestViableFunction(S, From->getLocStart(),
3246 Best)) {
3247 case OR_Deleted:
3248 case OR_Success: {
3249 // Record the standard conversion we used and the conversion function.
3250 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3251 QualType ThisType = Constructor->getThisType(S.Context);
3252 // Initializer lists don't have conversions as such.
3253 User.Before.setAsIdentityConversion();
3254 User.HadMultipleCandidates = HadMultipleCandidates;
3255 User.ConversionFunction = Constructor;
3256 User.FoundConversionFunction = Best->FoundDecl;
3257 User.After.setAsIdentityConversion();
3258 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3259 User.After.setAllToTypes(ToType);
3260 return Result;
3261 }
3262
3263 case OR_No_Viable_Function:
3264 return OR_No_Viable_Function;
3265 case OR_Ambiguous:
3266 return OR_Ambiguous;
3267 }
3268
3269 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3269)
;
3270}
3271
3272/// Determines whether there is a user-defined conversion sequence
3273/// (C++ [over.ics.user]) that converts expression From to the type
3274/// ToType. If such a conversion exists, User will contain the
3275/// user-defined conversion sequence that performs such a conversion
3276/// and this routine will return true. Otherwise, this routine returns
3277/// false and User is unspecified.
3278///
3279/// \param AllowExplicit true if the conversion should consider C++0x
3280/// "explicit" conversion functions as well as non-explicit conversion
3281/// functions (C++0x [class.conv.fct]p2).
3282///
3283/// \param AllowObjCConversionOnExplicit true if the conversion should
3284/// allow an extra Objective-C pointer conversion on uses of explicit
3285/// constructors. Requires \c AllowExplicit to also be set.
3286static OverloadingResult
3287IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3288 UserDefinedConversionSequence &User,
3289 OverloadCandidateSet &CandidateSet,
3290 bool AllowExplicit,
3291 bool AllowObjCConversionOnExplicit) {
3292 assert(AllowExplicit || !AllowObjCConversionOnExplicit)(static_cast <bool> (AllowExplicit || !AllowObjCConversionOnExplicit
) ? void (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3292, __extension__ __PRETTY_FUNCTION__))
;
3293 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3294
3295 // Whether we will only visit constructors.
3296 bool ConstructorsOnly = false;
3297
3298 // If the type we are conversion to is a class type, enumerate its
3299 // constructors.
3300 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3301 // C++ [over.match.ctor]p1:
3302 // When objects of class type are direct-initialized (8.5), or
3303 // copy-initialized from an expression of the same or a
3304 // derived class type (8.5), overload resolution selects the
3305 // constructor. [...] For copy-initialization, the candidate
3306 // functions are all the converting constructors (12.3.1) of
3307 // that class. The argument list is the expression-list within
3308 // the parentheses of the initializer.
3309 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3310 (From->getType()->getAs<RecordType>() &&
3311 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3312 ConstructorsOnly = true;
3313
3314 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3315 // We're not going to find any constructors.
3316 } else if (CXXRecordDecl *ToRecordDecl
3317 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3318
3319 Expr **Args = &From;
3320 unsigned NumArgs = 1;
3321 bool ListInitializing = false;
3322 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3323 // But first, see if there is an init-list-constructor that will work.
3324 OverloadingResult Result = IsInitializerListConstructorConversion(
3325 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3326 if (Result != OR_No_Viable_Function)
3327 return Result;
3328 // Never mind.
3329 CandidateSet.clear(
3330 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3331
3332 // If we're list-initializing, we pass the individual elements as
3333 // arguments, not the entire list.
3334 Args = InitList->getInits();
3335 NumArgs = InitList->getNumInits();
3336 ListInitializing = true;
3337 }
3338
3339 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3340 auto Info = getConstructorInfo(D);
3341 if (!Info)
3342 continue;
3343
3344 bool Usable = !Info.Constructor->isInvalidDecl();
3345 if (ListInitializing)
3346 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3347 else
3348 Usable = Usable &&
3349 Info.Constructor->isConvertingConstructor(AllowExplicit);
3350 if (Usable) {
3351 bool SuppressUserConversions = !ConstructorsOnly;
3352 if (SuppressUserConversions && ListInitializing) {
3353 SuppressUserConversions = false;
3354 if (NumArgs == 1) {
3355 // If the first argument is (a reference to) the target type,
3356 // suppress conversions.
3357 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3358 S.Context, Info.Constructor, ToType);
3359 }
3360 }
3361 if (Info.ConstructorTmpl)
3362 S.AddTemplateOverloadCandidate(
3363 Info.ConstructorTmpl, Info.FoundDecl,
3364 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3365 CandidateSet, SuppressUserConversions);
3366 else
3367 // Allow one user-defined conversion when user specifies a
3368 // From->ToType conversion via an static cast (c-style, etc).
3369 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3370 llvm::makeArrayRef(Args, NumArgs),
3371 CandidateSet, SuppressUserConversions);
3372 }
3373 }
3374 }
3375 }
3376
3377 // Enumerate conversion functions, if we're allowed to.
3378 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3379 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3380 // No conversion functions from incomplete types.
3381 } else if (const RecordType *FromRecordType
3382 = From->getType()->getAs<RecordType>()) {
3383 if (CXXRecordDecl *FromRecordDecl
3384 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3385 // Add all of the conversion functions as candidates.
3386 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3387 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3388 DeclAccessPair FoundDecl = I.getPair();
3389 NamedDecl *D = FoundDecl.getDecl();
3390 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3391 if (isa<UsingShadowDecl>(D))
3392 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3393
3394 CXXConversionDecl *Conv;
3395 FunctionTemplateDecl *ConvTemplate;
3396 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3397 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3398 else
3399 Conv = cast<CXXConversionDecl>(D);
3400
3401 if (AllowExplicit || !Conv->isExplicit()) {
3402 if (ConvTemplate)
3403 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3404 ActingContext, From, ToType,
3405 CandidateSet,
3406 AllowObjCConversionOnExplicit);
3407 else
3408 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3409 From, ToType, CandidateSet,
3410 AllowObjCConversionOnExplicit);
3411 }
3412 }
3413 }
3414 }
3415
3416 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3417
3418 OverloadCandidateSet::iterator Best;
3419 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3420 Best)) {
3421 case OR_Success:
3422 case OR_Deleted:
3423 // Record the standard conversion we used and the conversion function.
3424 if (CXXConstructorDecl *Constructor
3425 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3426 // C++ [over.ics.user]p1:
3427 // If the user-defined conversion is specified by a
3428 // constructor (12.3.1), the initial standard conversion
3429 // sequence converts the source type to the type required by
3430 // the argument of the constructor.
3431 //
3432 QualType ThisType = Constructor->getThisType(S.Context);
3433 if (isa<InitListExpr>(From)) {
3434 // Initializer lists don't have conversions as such.
3435 User.Before.setAsIdentityConversion();
3436 } else {
3437 if (Best->Conversions[0].isEllipsis())
3438 User.EllipsisConversion = true;
3439 else {
3440 User.Before = Best->Conversions[0].Standard;
3441 User.EllipsisConversion = false;
3442 }
3443 }
3444 User.HadMultipleCandidates = HadMultipleCandidates;
3445 User.ConversionFunction = Constructor;
3446 User.FoundConversionFunction = Best->FoundDecl;
3447 User.After.setAsIdentityConversion();
3448 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3449 User.After.setAllToTypes(ToType);
3450 return Result;
3451 }
3452 if (CXXConversionDecl *Conversion
3453 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3454 // C++ [over.ics.user]p1:
3455 //
3456 // [...] If the user-defined conversion is specified by a
3457 // conversion function (12.3.2), the initial standard
3458 // conversion sequence converts the source type to the
3459 // implicit object parameter of the conversion function.
3460 User.Before = Best->Conversions[0].Standard;
3461 User.HadMultipleCandidates = HadMultipleCandidates;
3462 User.ConversionFunction = Conversion;
3463 User.FoundConversionFunction = Best->FoundDecl;
3464 User.EllipsisConversion = false;
3465
3466 // C++ [over.ics.user]p2:
3467 // The second standard conversion sequence converts the
3468 // result of the user-defined conversion to the target type
3469 // for the sequence. Since an implicit conversion sequence
3470 // is an initialization, the special rules for
3471 // initialization by user-defined conversion apply when
3472 // selecting the best user-defined conversion for a
3473 // user-defined conversion sequence (see 13.3.3 and
3474 // 13.3.3.1).
3475 User.After = Best->FinalConversion;
3476 return Result;
3477 }
3478 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3478)
;
3479
3480 case OR_No_Viable_Function:
3481 return OR_No_Viable_Function;
3482
3483 case OR_Ambiguous:
3484 return OR_Ambiguous;
3485 }
3486
3487 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3487)
;
3488}
3489
3490bool
3491Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3492 ImplicitConversionSequence ICS;
3493 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3494 OverloadCandidateSet::CSK_Normal);
3495 OverloadingResult OvResult =
3496 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3497 CandidateSet, false, false);
3498 if (OvResult == OR_Ambiguous)
3499 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3500 << From->getType() << ToType << From->getSourceRange();
3501 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3502 if (!RequireCompleteType(From->getLocStart(), ToType,
3503 diag::err_typecheck_nonviable_condition_incomplete,
3504 From->getType(), From->getSourceRange()))
3505 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3506 << false << From->getType() << From->getSourceRange() << ToType;
3507 } else
3508 return false;
3509 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3510 return true;
3511}
3512
3513/// Compare the user-defined conversion functions or constructors
3514/// of two user-defined conversion sequences to determine whether any ordering
3515/// is possible.
3516static ImplicitConversionSequence::CompareKind
3517compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3518 FunctionDecl *Function2) {
3519 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3520 return ImplicitConversionSequence::Indistinguishable;
3521
3522 // Objective-C++:
3523 // If both conversion functions are implicitly-declared conversions from
3524 // a lambda closure type to a function pointer and a block pointer,
3525 // respectively, always prefer the conversion to a function pointer,
3526 // because the function pointer is more lightweight and is more likely
3527 // to keep code working.
3528 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3529 if (!Conv1)
3530 return ImplicitConversionSequence::Indistinguishable;
3531
3532 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3533 if (!Conv2)
3534 return ImplicitConversionSequence::Indistinguishable;
3535
3536 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3537 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3538 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3539 if (Block1 != Block2)
3540 return Block1 ? ImplicitConversionSequence::Worse
3541 : ImplicitConversionSequence::Better;
3542 }
3543
3544 return ImplicitConversionSequence::Indistinguishable;
3545}
3546
3547static bool hasDeprecatedStringLiteralToCharPtrConversion(
3548 const ImplicitConversionSequence &ICS) {
3549 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3550 (ICS.isUserDefined() &&
3551 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3552}
3553
3554/// CompareImplicitConversionSequences - Compare two implicit
3555/// conversion sequences to determine whether one is better than the
3556/// other or if they are indistinguishable (C++ 13.3.3.2).
3557static ImplicitConversionSequence::CompareKind
3558CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3559 const ImplicitConversionSequence& ICS1,
3560 const ImplicitConversionSequence& ICS2)
3561{
3562 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3563 // conversion sequences (as defined in 13.3.3.1)
3564 // -- a standard conversion sequence (13.3.3.1.1) is a better
3565 // conversion sequence than a user-defined conversion sequence or
3566 // an ellipsis conversion sequence, and
3567 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3568 // conversion sequence than an ellipsis conversion sequence
3569 // (13.3.3.1.3).
3570 //
3571 // C++0x [over.best.ics]p10:
3572 // For the purpose of ranking implicit conversion sequences as
3573 // described in 13.3.3.2, the ambiguous conversion sequence is
3574 // treated as a user-defined sequence that is indistinguishable
3575 // from any other user-defined conversion sequence.
3576
3577 // String literal to 'char *' conversion has been deprecated in C++03. It has
3578 // been removed from C++11. We still accept this conversion, if it happens at
3579 // the best viable function. Otherwise, this conversion is considered worse
3580 // than ellipsis conversion. Consider this as an extension; this is not in the
3581 // standard. For example:
3582 //
3583 // int &f(...); // #1
3584 // void f(char*); // #2
3585 // void g() { int &r = f("foo"); }
3586 //
3587 // In C++03, we pick #2 as the best viable function.
3588 // In C++11, we pick #1 as the best viable function, because ellipsis
3589 // conversion is better than string-literal to char* conversion (since there
3590 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3591 // convert arguments, #2 would be the best viable function in C++11.
3592 // If the best viable function has this conversion, a warning will be issued
3593 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3594
3595 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3596 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3597 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3598 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3599 ? ImplicitConversionSequence::Worse
3600 : ImplicitConversionSequence::Better;
3601
3602 if (ICS1.getKindRank() < ICS2.getKindRank())
3603 return ImplicitConversionSequence::Better;
3604 if (ICS2.getKindRank() < ICS1.getKindRank())
3605 return ImplicitConversionSequence::Worse;
3606
3607 // The following checks require both conversion sequences to be of
3608 // the same kind.
3609 if (ICS1.getKind() != ICS2.getKind())
3610 return ImplicitConversionSequence::Indistinguishable;
3611
3612 ImplicitConversionSequence::CompareKind Result =
3613 ImplicitConversionSequence::Indistinguishable;
3614
3615 // Two implicit conversion sequences of the same form are
3616 // indistinguishable conversion sequences unless one of the
3617 // following rules apply: (C++ 13.3.3.2p3):
3618
3619 // List-initialization sequence L1 is a better conversion sequence than
3620 // list-initialization sequence L2 if:
3621 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3622 // if not that,
3623 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3624 // and N1 is smaller than N2.,
3625 // even if one of the other rules in this paragraph would otherwise apply.
3626 if (!ICS1.isBad()) {
3627 if (ICS1.isStdInitializerListElement() &&
3628 !ICS2.isStdInitializerListElement())
3629 return ImplicitConversionSequence::Better;
3630 if (!ICS1.isStdInitializerListElement() &&
3631 ICS2.isStdInitializerListElement())
3632 return ImplicitConversionSequence::Worse;
3633 }
3634
3635 if (ICS1.isStandard())
3636 // Standard conversion sequence S1 is a better conversion sequence than
3637 // standard conversion sequence S2 if [...]
3638 Result = CompareStandardConversionSequences(S, Loc,
3639 ICS1.Standard, ICS2.Standard);
3640 else if (ICS1.isUserDefined()) {
3641 // User-defined conversion sequence U1 is a better conversion
3642 // sequence than another user-defined conversion sequence U2 if
3643 // they contain the same user-defined conversion function or
3644 // constructor and if the second standard conversion sequence of
3645 // U1 is better than the second standard conversion sequence of
3646 // U2 (C++ 13.3.3.2p3).
3647 if (ICS1.UserDefined.ConversionFunction ==
3648 ICS2.UserDefined.ConversionFunction)
3649 Result = CompareStandardConversionSequences(S, Loc,
3650 ICS1.UserDefined.After,
3651 ICS2.UserDefined.After);
3652 else
3653 Result = compareConversionFunctions(S,
3654 ICS1.UserDefined.ConversionFunction,
3655 ICS2.UserDefined.ConversionFunction);
3656 }
3657
3658 return Result;
3659}
3660
3661// Per 13.3.3.2p3, compare the given standard conversion sequences to
3662// determine if one is a proper subset of the other.
3663static ImplicitConversionSequence::CompareKind
3664compareStandardConversionSubsets(ASTContext &Context,
3665 const StandardConversionSequence& SCS1,
3666 const StandardConversionSequence& SCS2) {
3667 ImplicitConversionSequence::CompareKind Result
3668 = ImplicitConversionSequence::Indistinguishable;
3669
3670 // the identity conversion sequence is considered to be a subsequence of
3671 // any non-identity conversion sequence
3672 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3673 return ImplicitConversionSequence::Better;
3674 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3675 return ImplicitConversionSequence::Worse;
3676
3677 if (SCS1.Second != SCS2.Second) {
3678 if (SCS1.Second == ICK_Identity)
3679 Result = ImplicitConversionSequence::Better;
3680 else if (SCS2.Second == ICK_Identity)
3681 Result = ImplicitConversionSequence::Worse;
3682 else
3683 return ImplicitConversionSequence::Indistinguishable;
3684 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3685 return ImplicitConversionSequence::Indistinguishable;
3686
3687 if (SCS1.Third == SCS2.Third) {
3688 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3689 : ImplicitConversionSequence::Indistinguishable;
3690 }
3691
3692 if (SCS1.Third == ICK_Identity)
3693 return Result == ImplicitConversionSequence::Worse
3694 ? ImplicitConversionSequence::Indistinguishable
3695 : ImplicitConversionSequence::Better;
3696
3697 if (SCS2.Third == ICK_Identity)
3698 return Result == ImplicitConversionSequence::Better
3699 ? ImplicitConversionSequence::Indistinguishable
3700 : ImplicitConversionSequence::Worse;
3701
3702 return ImplicitConversionSequence::Indistinguishable;
3703}
3704
3705/// Determine whether one of the given reference bindings is better
3706/// than the other based on what kind of bindings they are.
3707static bool
3708isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3709 const StandardConversionSequence &SCS2) {
3710 // C++0x [over.ics.rank]p3b4:
3711 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3712 // implicit object parameter of a non-static member function declared
3713 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3714 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3715 // lvalue reference to a function lvalue and S2 binds an rvalue
3716 // reference*.
3717 //
3718 // FIXME: Rvalue references. We're going rogue with the above edits,
3719 // because the semantics in the current C++0x working paper (N3225 at the
3720 // time of this writing) break the standard definition of std::forward
3721 // and std::reference_wrapper when dealing with references to functions.
3722 // Proposed wording changes submitted to CWG for consideration.
3723 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3724 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3725 return false;
3726
3727 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3728 SCS2.IsLvalueReference) ||
3729 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3730 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3731}
3732
3733/// CompareStandardConversionSequences - Compare two standard
3734/// conversion sequences to determine whether one is better than the
3735/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3736static ImplicitConversionSequence::CompareKind
3737CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3738 const StandardConversionSequence& SCS1,
3739 const StandardConversionSequence& SCS2)
3740{
3741 // Standard conversion sequence S1 is a better conversion sequence
3742 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3743
3744 // -- S1 is a proper subsequence of S2 (comparing the conversion
3745 // sequences in the canonical form defined by 13.3.3.1.1,
3746 // excluding any Lvalue Transformation; the identity conversion
3747 // sequence is considered to be a subsequence of any
3748 // non-identity conversion sequence) or, if not that,
3749 if (ImplicitConversionSequence::CompareKind CK
3750 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3751 return CK;
3752
3753 // -- the rank of S1 is better than the rank of S2 (by the rules
3754 // defined below), or, if not that,
3755 ImplicitConversionRank Rank1 = SCS1.getRank();
3756 ImplicitConversionRank Rank2 = SCS2.getRank();
3757 if (Rank1 < Rank2)
3758 return ImplicitConversionSequence::Better;
3759 else if (Rank2 < Rank1)
3760 return ImplicitConversionSequence::Worse;
3761
3762 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3763 // are indistinguishable unless one of the following rules
3764 // applies:
3765
3766 // A conversion that is not a conversion of a pointer, or
3767 // pointer to member, to bool is better than another conversion
3768 // that is such a conversion.
3769 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3770 return SCS2.isPointerConversionToBool()
3771 ? ImplicitConversionSequence::Better
3772 : ImplicitConversionSequence::Worse;
3773
3774 // C++ [over.ics.rank]p4b2:
3775 //
3776 // If class B is derived directly or indirectly from class A,
3777 // conversion of B* to A* is better than conversion of B* to
3778 // void*, and conversion of A* to void* is better than conversion
3779 // of B* to void*.
3780 bool SCS1ConvertsToVoid
3781 = SCS1.isPointerConversionToVoidPointer(S.Context);
3782 bool SCS2ConvertsToVoid
3783 = SCS2.isPointerConversionToVoidPointer(S.Context);
3784 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3785 // Exactly one of the conversion sequences is a conversion to
3786 // a void pointer; it's the worse conversion.
3787 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3788 : ImplicitConversionSequence::Worse;
3789 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3790 // Neither conversion sequence converts to a void pointer; compare
3791 // their derived-to-base conversions.
3792 if (ImplicitConversionSequence::CompareKind DerivedCK
3793 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3794 return DerivedCK;
3795 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3796 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3797 // Both conversion sequences are conversions to void
3798 // pointers. Compare the source types to determine if there's an
3799 // inheritance relationship in their sources.
3800 QualType FromType1 = SCS1.getFromType();
3801 QualType FromType2 = SCS2.getFromType();
3802
3803 // Adjust the types we're converting from via the array-to-pointer
3804 // conversion, if we need to.
3805 if (SCS1.First == ICK_Array_To_Pointer)
3806 FromType1 = S.Context.getArrayDecayedType(FromType1);
3807 if (SCS2.First == ICK_Array_To_Pointer)
3808 FromType2 = S.Context.getArrayDecayedType(FromType2);
3809
3810 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3811 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3812
3813 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3814 return ImplicitConversionSequence::Better;
3815 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3816 return ImplicitConversionSequence::Worse;
3817
3818 // Objective-C++: If one interface is more specific than the
3819 // other, it is the better one.
3820 const ObjCObjectPointerType* FromObjCPtr1
3821 = FromType1->getAs<ObjCObjectPointerType>();
3822 const ObjCObjectPointerType* FromObjCPtr2
3823 = FromType2->getAs<ObjCObjectPointerType>();
3824 if (FromObjCPtr1 && FromObjCPtr2) {
3825 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3826 FromObjCPtr2);
3827 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3828 FromObjCPtr1);
3829 if (AssignLeft != AssignRight) {
3830 return AssignLeft? ImplicitConversionSequence::Better
3831 : ImplicitConversionSequence::Worse;
3832 }
3833 }
3834 }
3835
3836 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3837 // bullet 3).
3838 if (ImplicitConversionSequence::CompareKind QualCK
3839 = CompareQualificationConversions(S, SCS1, SCS2))
3840 return QualCK;
3841
3842 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3843 // Check for a better reference binding based on the kind of bindings.
3844 if (isBetterReferenceBindingKind(SCS1, SCS2))
3845 return ImplicitConversionSequence::Better;
3846 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3847 return ImplicitConversionSequence::Worse;
3848
3849 // C++ [over.ics.rank]p3b4:
3850 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3851 // which the references refer are the same type except for
3852 // top-level cv-qualifiers, and the type to which the reference
3853 // initialized by S2 refers is more cv-qualified than the type
3854 // to which the reference initialized by S1 refers.
3855 QualType T1 = SCS1.getToType(2);
3856 QualType T2 = SCS2.getToType(2);
3857 T1 = S.Context.getCanonicalType(T1);
3858 T2 = S.Context.getCanonicalType(T2);
3859 Qualifiers T1Quals, T2Quals;
3860 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3861 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3862 if (UnqualT1 == UnqualT2) {
3863 // Objective-C++ ARC: If the references refer to objects with different
3864 // lifetimes, prefer bindings that don't change lifetime.
3865 if (SCS1.ObjCLifetimeConversionBinding !=
3866 SCS2.ObjCLifetimeConversionBinding) {
3867 return SCS1.ObjCLifetimeConversionBinding
3868 ? ImplicitConversionSequence::Worse
3869 : ImplicitConversionSequence::Better;
3870 }
3871
3872 // If the type is an array type, promote the element qualifiers to the
3873 // type for comparison.
3874 if (isa<ArrayType>(T1) && T1Quals)
3875 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3876 if (isa<ArrayType>(T2) && T2Quals)
3877 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3878 if (T2.isMoreQualifiedThan(T1))
3879 return ImplicitConversionSequence::Better;
3880 else if (T1.isMoreQualifiedThan(T2))
3881 return ImplicitConversionSequence::Worse;
3882 }
3883 }
3884
3885 // In Microsoft mode, prefer an integral conversion to a
3886 // floating-to-integral conversion if the integral conversion
3887 // is between types of the same size.
3888 // For example:
3889 // void f(float);
3890 // void f(int);
3891 // int main {
3892 // long a;
3893 // f(a);
3894 // }
3895 // Here, MSVC will call f(int) instead of generating a compile error
3896 // as clang will do in standard mode.
3897 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3898 SCS2.Second == ICK_Floating_Integral &&
3899 S.Context.getTypeSize(SCS1.getFromType()) ==
3900 S.Context.getTypeSize(SCS1.getToType(2)))
3901 return ImplicitConversionSequence::Better;
3902
3903 return ImplicitConversionSequence::Indistinguishable;
3904}
3905
3906/// CompareQualificationConversions - Compares two standard conversion
3907/// sequences to determine whether they can be ranked based on their
3908/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3909static ImplicitConversionSequence::CompareKind
3910CompareQualificationConversions(Sema &S,
3911 const StandardConversionSequence& SCS1,
3912 const StandardConversionSequence& SCS2) {
3913 // C++ 13.3.3.2p3:
3914 // -- S1 and S2 differ only in their qualification conversion and
3915 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3916 // cv-qualification signature of type T1 is a proper subset of
3917 // the cv-qualification signature of type T2, and S1 is not the
3918 // deprecated string literal array-to-pointer conversion (4.2).
3919 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3920 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3921 return ImplicitConversionSequence::Indistinguishable;
3922
3923 // FIXME: the example in the standard doesn't use a qualification
3924 // conversion (!)
3925 QualType T1 = SCS1.getToType(2);
3926 QualType T2 = SCS2.getToType(2);
3927 T1 = S.Context.getCanonicalType(T1);
3928 T2 = S.Context.getCanonicalType(T2);
3929 Qualifiers T1Quals, T2Quals;
3930 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3931 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3932
3933 // If the types are the same, we won't learn anything by unwrapped
3934 // them.
3935 if (UnqualT1 == UnqualT2)
3936 return ImplicitConversionSequence::Indistinguishable;
3937
3938 // If the type is an array type, promote the element qualifiers to the type
3939 // for comparison.
3940 if (isa<ArrayType>(T1) && T1Quals)
3941 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3942 if (isa<ArrayType>(T2) && T2Quals)
3943 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3944
3945 ImplicitConversionSequence::CompareKind Result
3946 = ImplicitConversionSequence::Indistinguishable;
3947
3948 // Objective-C++ ARC:
3949 // Prefer qualification conversions not involving a change in lifetime
3950 // to qualification conversions that do not change lifetime.
3951 if (SCS1.QualificationIncludesObjCLifetime !=
3952 SCS2.QualificationIncludesObjCLifetime) {
3953 Result = SCS1.QualificationIncludesObjCLifetime
3954 ? ImplicitConversionSequence::Worse
3955 : ImplicitConversionSequence::Better;
3956 }
3957
3958 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
3959 // Within each iteration of the loop, we check the qualifiers to
3960 // determine if this still looks like a qualification
3961 // conversion. Then, if all is well, we unwrap one more level of
3962 // pointers or pointers-to-members and do it all again
3963 // until there are no more pointers or pointers-to-members left
3964 // to unwrap. This essentially mimics what
3965 // IsQualificationConversion does, but here we're checking for a
3966 // strict subset of qualifiers.
3967 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3968 // The qualifiers are the same, so this doesn't tell us anything
3969 // about how the sequences rank.
3970 ;
3971 else if (T2.isMoreQualifiedThan(T1)) {
3972 // T1 has fewer qualifiers, so it could be the better sequence.
3973 if (Result == ImplicitConversionSequence::Worse)
3974 // Neither has qualifiers that are a subset of the other's
3975 // qualifiers.
3976 return ImplicitConversionSequence::Indistinguishable;
3977
3978 Result = ImplicitConversionSequence::Better;
3979 } else if (T1.isMoreQualifiedThan(T2)) {
3980 // T2 has fewer qualifiers, so it could be the better sequence.
3981 if (Result == ImplicitConversionSequence::Better)
3982 // Neither has qualifiers that are a subset of the other's
3983 // qualifiers.
3984 return ImplicitConversionSequence::Indistinguishable;
3985
3986 Result = ImplicitConversionSequence::Worse;
3987 } else {
3988 // Qualifiers are disjoint.
3989 return ImplicitConversionSequence::Indistinguishable;
3990 }
3991
3992 // If the types after this point are equivalent, we're done.
3993 if (S.Context.hasSameUnqualifiedType(T1, T2))
3994 break;
3995 }
3996
3997 // Check that the winning standard conversion sequence isn't using
3998 // the deprecated string literal array to pointer conversion.
3999 switch (Result) {
4000 case ImplicitConversionSequence::Better:
4001 if (SCS1.DeprecatedStringLiteralToCharPtr)
4002 Result = ImplicitConversionSequence::Indistinguishable;
4003 break;
4004
4005 case ImplicitConversionSequence::Indistinguishable:
4006 break;
4007
4008 case ImplicitConversionSequence::Worse:
4009 if (SCS2.DeprecatedStringLiteralToCharPtr)
4010 Result = ImplicitConversionSequence::Indistinguishable;
4011 break;
4012 }
4013
4014 return Result;
4015}
4016
4017/// CompareDerivedToBaseConversions - Compares two standard conversion
4018/// sequences to determine whether they can be ranked based on their
4019/// various kinds of derived-to-base conversions (C++
4020/// [over.ics.rank]p4b3). As part of these checks, we also look at
4021/// conversions between Objective-C interface types.
4022static ImplicitConversionSequence::CompareKind
4023CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4024 const StandardConversionSequence& SCS1,
4025 const StandardConversionSequence& SCS2) {
4026 QualType FromType1 = SCS1.getFromType();
4027 QualType ToType1 = SCS1.getToType(1);
4028 QualType FromType2 = SCS2.getFromType();
4029 QualType ToType2 = SCS2.getToType(1);
4030
4031 // Adjust the types we're converting from via the array-to-pointer
4032 // conversion, if we need to.
4033 if (SCS1.First == ICK_Array_To_Pointer)
4034 FromType1 = S.Context.getArrayDecayedType(FromType1);
4035 if (SCS2.First == ICK_Array_To_Pointer)
4036 FromType2 = S.Context.getArrayDecayedType(FromType2);
4037
4038 // Canonicalize all of the types.
4039 FromType1 = S.Context.getCanonicalType(FromType1);
4040 ToType1 = S.Context.getCanonicalType(ToType1);
4041 FromType2 = S.Context.getCanonicalType(FromType2);
4042 ToType2 = S.Context.getCanonicalType(ToType2);
4043
4044 // C++ [over.ics.rank]p4b3:
4045 //
4046 // If class B is derived directly or indirectly from class A and
4047 // class C is derived directly or indirectly from B,
4048 //
4049 // Compare based on pointer conversions.
4050 if (SCS1.Second == ICK_Pointer_Conversion &&
4051 SCS2.Second == ICK_Pointer_Conversion &&
4052 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4053 FromType1->isPointerType() && FromType2->isPointerType() &&
4054 ToType1->isPointerType() && ToType2->isPointerType()) {
4055 QualType FromPointee1
4056 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4057 QualType ToPointee1
4058 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4059 QualType FromPointee2
4060 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4061 QualType ToPointee2
4062 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4063
4064 // -- conversion of C* to B* is better than conversion of C* to A*,
4065 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4066 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4067 return ImplicitConversionSequence::Better;
4068 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4069 return ImplicitConversionSequence::Worse;
4070 }
4071
4072 // -- conversion of B* to A* is better than conversion of C* to A*,
4073 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4074 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4075 return ImplicitConversionSequence::Better;
4076 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4077 return ImplicitConversionSequence::Worse;
4078 }
4079 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4080 SCS2.Second == ICK_Pointer_Conversion) {
4081 const ObjCObjectPointerType *FromPtr1
4082 = FromType1->getAs<ObjCObjectPointerType>();
4083 const ObjCObjectPointerType *FromPtr2
4084 = FromType2->getAs<ObjCObjectPointerType>();
4085 const ObjCObjectPointerType *ToPtr1
4086 = ToType1->getAs<ObjCObjectPointerType>();
4087 const ObjCObjectPointerType *ToPtr2
4088 = ToType2->getAs<ObjCObjectPointerType>();
4089
4090 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4091 // Apply the same conversion ranking rules for Objective-C pointer types
4092 // that we do for C++ pointers to class types. However, we employ the
4093 // Objective-C pseudo-subtyping relationship used for assignment of
4094 // Objective-C pointer types.
4095 bool FromAssignLeft
4096 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4097 bool FromAssignRight
4098 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4099 bool ToAssignLeft
4100 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4101 bool ToAssignRight
4102 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4103
4104 // A conversion to an a non-id object pointer type or qualified 'id'
4105 // type is better than a conversion to 'id'.
4106 if (ToPtr1->isObjCIdType() &&
4107 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4108 return ImplicitConversionSequence::Worse;
4109 if (ToPtr2->isObjCIdType() &&
4110 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4111 return ImplicitConversionSequence::Better;
4112
4113 // A conversion to a non-id object pointer type is better than a
4114 // conversion to a qualified 'id' type
4115 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4116 return ImplicitConversionSequence::Worse;
4117 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4118 return ImplicitConversionSequence::Better;
4119
4120 // A conversion to an a non-Class object pointer type or qualified 'Class'
4121 // type is better than a conversion to 'Class'.
4122 if (ToPtr1->isObjCClassType() &&
4123 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4124 return ImplicitConversionSequence::Worse;
4125 if (ToPtr2->isObjCClassType() &&
4126 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4127 return ImplicitConversionSequence::Better;
4128
4129 // A conversion to a non-Class object pointer type is better than a
4130 // conversion to a qualified 'Class' type.
4131 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4132 return ImplicitConversionSequence::Worse;
4133 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4134 return ImplicitConversionSequence::Better;
4135
4136 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4137 if (S.Context.hasSameType(FromType1, FromType2) &&
4138 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4139 (ToAssignLeft != ToAssignRight)) {
4140 if (FromPtr1->isSpecialized()) {
4141 // "conversion of B<A> * to B * is better than conversion of B * to
4142 // C *.
4143 bool IsFirstSame =
4144 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4145 bool IsSecondSame =
4146 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4147 if (IsFirstSame) {
4148 if (!IsSecondSame)
4149 return ImplicitConversionSequence::Better;
4150 } else if (IsSecondSame)
4151 return ImplicitConversionSequence::Worse;
4152 }
4153 return ToAssignLeft? ImplicitConversionSequence::Worse
4154 : ImplicitConversionSequence::Better;
4155 }
4156
4157 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4158 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4159 (FromAssignLeft != FromAssignRight))
4160 return FromAssignLeft? ImplicitConversionSequence::Better
4161 : ImplicitConversionSequence::Worse;
4162 }
4163 }
4164
4165 // Ranking of member-pointer types.
4166 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4167 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4168 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4169 const MemberPointerType * FromMemPointer1 =
4170 FromType1->getAs<MemberPointerType>();
4171 const MemberPointerType * ToMemPointer1 =
4172 ToType1->getAs<MemberPointerType>();
4173 const MemberPointerType * FromMemPointer2 =
4174 FromType2->getAs<MemberPointerType>();
4175 const MemberPointerType * ToMemPointer2 =
4176 ToType2->getAs<MemberPointerType>();
4177 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4178 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4179 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4180 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4181 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4182 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4183 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4184 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4185 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4186 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4187 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4188 return ImplicitConversionSequence::Worse;
4189 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4190 return ImplicitConversionSequence::Better;
4191 }
4192 // conversion of B::* to C::* is better than conversion of A::* to C::*
4193 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4194 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4195 return ImplicitConversionSequence::Better;
4196 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4197 return ImplicitConversionSequence::Worse;
4198 }
4199 }
4200
4201 if (SCS1.Second == ICK_Derived_To_Base) {
4202 // -- conversion of C to B is better than conversion of C to A,
4203 // -- binding of an expression of type C to a reference of type
4204 // B& is better than binding an expression of type C to a
4205 // reference of type A&,
4206 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4207 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4208 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4209 return ImplicitConversionSequence::Better;
4210 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4211 return ImplicitConversionSequence::Worse;
4212 }
4213
4214 // -- conversion of B to A is better than conversion of C to A.
4215 // -- binding of an expression of type B to a reference of type
4216 // A& is better than binding an expression of type C to a
4217 // reference of type A&,
4218 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4219 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4220 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4221 return ImplicitConversionSequence::Better;
4222 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4223 return ImplicitConversionSequence::Worse;
4224 }
4225 }
4226
4227 return ImplicitConversionSequence::Indistinguishable;
4228}
4229
4230/// Determine whether the given type is valid, e.g., it is not an invalid
4231/// C++ class.
4232static bool isTypeValid(QualType T) {
4233 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4234 return !Record->isInvalidDecl();
4235
4236 return true;
4237}
4238
4239/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4240/// determine whether they are reference-related,
4241/// reference-compatible, reference-compatible with added
4242/// qualification, or incompatible, for use in C++ initialization by
4243/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4244/// type, and the first type (T1) is the pointee type of the reference
4245/// type being initialized.
4246Sema::ReferenceCompareResult
4247Sema::CompareReferenceRelationship(SourceLocation Loc,
4248 QualType OrigT1, QualType OrigT2,
4249 bool &DerivedToBase,
4250 bool &ObjCConversion,
4251 bool &ObjCLifetimeConversion) {
4252 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4253, __extension__ __PRETTY_FUNCTION__))
4253 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4253, __extension__ __PRETTY_FUNCTION__))
;
4254 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4254, __extension__ __PRETTY_FUNCTION__))
;
4255
4256 QualType T1 = Context.getCanonicalType(OrigT1);
4257 QualType T2 = Context.getCanonicalType(OrigT2);
4258 Qualifiers T1Quals, T2Quals;
4259 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4260 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4261
4262 // C++ [dcl.init.ref]p4:
4263 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4264 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4265 // T1 is a base class of T2.
4266 DerivedToBase = false;
4267 ObjCConversion = false;
4268 ObjCLifetimeConversion = false;
4269 QualType ConvertedT2;
4270 if (UnqualT1 == UnqualT2) {
4271 // Nothing to do.
4272 } else if (isCompleteType(Loc, OrigT2) &&
4273 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4274 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4275 DerivedToBase = true;
4276 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4277 UnqualT2->isObjCObjectOrInterfaceType() &&
4278 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4279 ObjCConversion = true;
4280 else if (UnqualT2->isFunctionType() &&
4281 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4282 // C++1z [dcl.init.ref]p4:
4283 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4284 // function" and T1 is "function"
4285 //
4286 // We extend this to also apply to 'noreturn', so allow any function
4287 // conversion between function types.
4288 return Ref_Compatible;
4289 else
4290 return Ref_Incompatible;
4291
4292 // At this point, we know that T1 and T2 are reference-related (at
4293 // least).
4294
4295 // If the type is an array type, promote the element qualifiers to the type
4296 // for comparison.
4297 if (isa<ArrayType>(T1) && T1Quals)
4298 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4299 if (isa<ArrayType>(T2) && T2Quals)
4300 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4301
4302 // C++ [dcl.init.ref]p4:
4303 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4304 // reference-related to T2 and cv1 is the same cv-qualification
4305 // as, or greater cv-qualification than, cv2. For purposes of
4306 // overload resolution, cases for which cv1 is greater
4307 // cv-qualification than cv2 are identified as
4308 // reference-compatible with added qualification (see 13.3.3.2).
4309 //
4310 // Note that we also require equivalence of Objective-C GC and address-space
4311 // qualifiers when performing these computations, so that e.g., an int in
4312 // address space 1 is not reference-compatible with an int in address
4313 // space 2.
4314 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4315 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4316 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4317 ObjCLifetimeConversion = true;
4318
4319 T1Quals.removeObjCLifetime();
4320 T2Quals.removeObjCLifetime();
4321 }
4322
4323 // MS compiler ignores __unaligned qualifier for references; do the same.
4324 T1Quals.removeUnaligned();
4325 T2Quals.removeUnaligned();
4326
4327 if (T1Quals.compatiblyIncludes(T2Quals))
4328 return Ref_Compatible;
4329 else
4330 return Ref_Related;
4331}
4332
4333/// Look for a user-defined conversion to a value reference-compatible
4334/// with DeclType. Return true if something definite is found.
4335static bool
4336FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4337 QualType DeclType, SourceLocation DeclLoc,
4338 Expr *Init, QualType T2, bool AllowRvalues,
4339 bool AllowExplicit) {
4340 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4340, __extension__ __PRETTY_FUNCTION__))
;
4341 CXXRecordDecl *T2RecordDecl
4342 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4343
4344 OverloadCandidateSet CandidateSet(
4345 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4346 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4347 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4348 NamedDecl *D = *I;
4349 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4350 if (isa<UsingShadowDecl>(D))
4351 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4352
4353 FunctionTemplateDecl *ConvTemplate
4354 = dyn_cast<FunctionTemplateDecl>(D);
4355 CXXConversionDecl *Conv;
4356 if (ConvTemplate)
4357 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4358 else
4359 Conv = cast<CXXConversionDecl>(D);
4360
4361 // If this is an explicit conversion, and we're not allowed to consider
4362 // explicit conversions, skip it.
4363 if (!AllowExplicit && Conv->isExplicit())
4364 continue;
4365
4366 if (AllowRvalues) {
4367 bool DerivedToBase = false;
4368 bool ObjCConversion = false;
4369 bool ObjCLifetimeConversion = false;
4370
4371 // If we are initializing an rvalue reference, don't permit conversion
4372 // functions that return lvalues.
4373 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4374 const ReferenceType *RefType
4375 = Conv->getConversionType()->getAs<LValueReferenceType>();
4376 if (RefType && !RefType->getPointeeType()->isFunctionType())
4377 continue;
4378 }
4379
4380 if (!ConvTemplate &&
4381 S.CompareReferenceRelationship(
4382 DeclLoc,
4383 Conv->getConversionType().getNonReferenceType()
4384 .getUnqualifiedType(),
4385 DeclType.getNonReferenceType().getUnqualifiedType(),
4386 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4387 Sema::Ref_Incompatible)
4388 continue;
4389 } else {
4390 // If the conversion function doesn't return a reference type,
4391 // it can't be considered for this conversion. An rvalue reference
4392 // is only acceptable if its referencee is a function type.
4393
4394 const ReferenceType *RefType =
4395 Conv->getConversionType()->getAs<ReferenceType>();
4396 if (!RefType ||
4397 (!RefType->isLValueReferenceType() &&
4398 !RefType->getPointeeType()->isFunctionType()))
4399 continue;
4400 }
4401
4402 if (ConvTemplate)
4403 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4404 Init, DeclType, CandidateSet,
4405 /*AllowObjCConversionOnExplicit=*/false);
4406 else
4407 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4408 DeclType, CandidateSet,
4409 /*AllowObjCConversionOnExplicit=*/false);
4410 }
4411
4412 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4413
4414 OverloadCandidateSet::iterator Best;
4415 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4416 case OR_Success:
4417 // C++ [over.ics.ref]p1:
4418 //
4419 // [...] If the parameter binds directly to the result of
4420 // applying a conversion function to the argument
4421 // expression, the implicit conversion sequence is a
4422 // user-defined conversion sequence (13.3.3.1.2), with the
4423 // second standard conversion sequence either an identity
4424 // conversion or, if the conversion function returns an
4425 // entity of a type that is a derived class of the parameter
4426 // type, a derived-to-base Conversion.
4427 if (!Best->FinalConversion.DirectBinding)
4428 return false;
4429
4430 ICS.setUserDefined();
4431 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4432 ICS.UserDefined.After = Best->FinalConversion;
4433 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4434 ICS.UserDefined.ConversionFunction = Best->Function;
4435 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4436 ICS.UserDefined.EllipsisConversion = false;
4437 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4439, __extension__ __PRETTY_FUNCTION__))
4438 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4439, __extension__ __PRETTY_FUNCTION__))
4439 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4439, __extension__ __PRETTY_FUNCTION__))
;
4440 return true;
4441
4442 case OR_Ambiguous:
4443 ICS.setAmbiguous();
4444 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4445 Cand != CandidateSet.end(); ++Cand)
4446 if (Cand->Viable)
4447 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4448 return true;
4449
4450 case OR_No_Viable_Function:
4451 case OR_Deleted:
4452 // There was no suitable conversion, or we found a deleted
4453 // conversion; continue with other checks.
4454 return false;
4455 }
4456
4457 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4457)
;
4458}
4459
4460/// Compute an implicit conversion sequence for reference
4461/// initialization.
4462static ImplicitConversionSequence
4463TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4464 SourceLocation DeclLoc,
4465 bool SuppressUserConversions,
4466 bool AllowExplicit) {
4467 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4467, __extension__ __PRETTY_FUNCTION__))
;
4468
4469 // Most paths end in a failed conversion.
4470 ImplicitConversionSequence ICS;
4471 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4472
4473 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4474 QualType T2 = Init->getType();
4475
4476 // If the initializer is the address of an overloaded function, try
4477 // to resolve the overloaded function. If all goes well, T2 is the
4478 // type of the resulting function.
4479 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4480 DeclAccessPair Found;
4481 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4482 false, Found))
4483 T2 = Fn->getType();
4484 }
4485
4486 // Compute some basic properties of the types and the initializer.
4487 bool isRValRef = DeclType->isRValueReferenceType();
4488 bool DerivedToBase = false;
4489 bool ObjCConversion = false;
4490 bool ObjCLifetimeConversion = false;
4491 Expr::Classification InitCategory = Init->Classify(S.Context);
4492 Sema::ReferenceCompareResult RefRelationship
4493 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4494 ObjCConversion, ObjCLifetimeConversion);
4495
4496
4497 // C++0x [dcl.init.ref]p5:
4498 // A reference to type "cv1 T1" is initialized by an expression
4499 // of type "cv2 T2" as follows:
4500
4501 // -- If reference is an lvalue reference and the initializer expression
4502 if (!isRValRef) {
4503 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4504 // reference-compatible with "cv2 T2," or
4505 //
4506 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4507 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4508 // C++ [over.ics.ref]p1:
4509 // When a parameter of reference type binds directly (8.5.3)
4510 // to an argument expression, the implicit conversion sequence
4511 // is the identity conversion, unless the argument expression
4512 // has a type that is a derived class of the parameter type,
4513 // in which case the implicit conversion sequence is a
4514 // derived-to-base Conversion (13.3.3.1).
4515 ICS.setStandard();
4516 ICS.Standard.First = ICK_Identity;
4517 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4518 : ObjCConversion? ICK_Compatible_Conversion
4519 : ICK_Identity;
4520 ICS.Standard.Third = ICK_Identity;
4521 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4522 ICS.Standard.setToType(0, T2);
4523 ICS.Standard.setToType(1, T1);
4524 ICS.Standard.setToType(2, T1);
4525 ICS.Standard.ReferenceBinding = true;
4526 ICS.Standard.DirectBinding = true;
4527 ICS.Standard.IsLvalueReference = !isRValRef;
4528 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4529 ICS.Standard.BindsToRvalue = false;
4530 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4531 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4532 ICS.Standard.CopyConstructor = nullptr;
4533 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4534
4535 // Nothing more to do: the inaccessibility/ambiguity check for
4536 // derived-to-base conversions is suppressed when we're
4537 // computing the implicit conversion sequence (C++
4538 // [over.best.ics]p2).
4539 return ICS;
4540 }
4541
4542 // -- has a class type (i.e., T2 is a class type), where T1 is
4543 // not reference-related to T2, and can be implicitly
4544 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4545 // is reference-compatible with "cv3 T3" 92) (this
4546 // conversion is selected by enumerating the applicable
4547 // conversion functions (13.3.1.6) and choosing the best
4548 // one through overload resolution (13.3)),
4549 if (!SuppressUserConversions && T2->isRecordType() &&
4550 S.isCompleteType(DeclLoc, T2) &&
4551 RefRelationship == Sema::Ref_Incompatible) {
4552 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4553 Init, T2, /*AllowRvalues=*/false,
4554 AllowExplicit))
4555 return ICS;
4556 }
4557 }
4558
4559 // -- Otherwise, the reference shall be an lvalue reference to a
4560 // non-volatile const type (i.e., cv1 shall be const), or the reference
4561 // shall be an rvalue reference.
4562 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4563 return ICS;
4564
4565 // -- If the initializer expression
4566 //
4567 // -- is an xvalue, class prvalue, array prvalue or function
4568 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4569 if (RefRelationship == Sema::Ref_Compatible &&
4570 (InitCategory.isXValue() ||
4571 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4572 (InitCategory.isLValue() && T2->isFunctionType()))) {
4573 ICS.setStandard();
4574 ICS.Standard.First = ICK_Identity;
4575 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4576 : ObjCConversion? ICK_Compatible_Conversion
4577 : ICK_Identity;
4578 ICS.Standard.Third = ICK_Identity;
4579 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4580 ICS.Standard.setToType(0, T2);
4581 ICS.Standard.setToType(1, T1);
4582 ICS.Standard.setToType(2, T1);
4583 ICS.Standard.ReferenceBinding = true;
4584 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4585 // binding unless we're binding to a class prvalue.
4586 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4587 // allow the use of rvalue references in C++98/03 for the benefit of
4588 // standard library implementors; therefore, we need the xvalue check here.
4589 ICS.Standard.DirectBinding =
4590 S.getLangOpts().CPlusPlus11 ||
4591 !(InitCategory.isPRValue() || T2->isRecordType());
4592 ICS.Standard.IsLvalueReference = !isRValRef;
4593 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4594 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4595 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4596 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4597 ICS.Standard.CopyConstructor = nullptr;
4598 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4599 return ICS;
4600 }
4601
4602 // -- has a class type (i.e., T2 is a class type), where T1 is not
4603 // reference-related to T2, and can be implicitly converted to
4604 // an xvalue, class prvalue, or function lvalue of type
4605 // "cv3 T3", where "cv1 T1" is reference-compatible with
4606 // "cv3 T3",
4607 //
4608 // then the reference is bound to the value of the initializer
4609 // expression in the first case and to the result of the conversion
4610 // in the second case (or, in either case, to an appropriate base
4611 // class subobject).
4612 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4613 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4614 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4615 Init, T2, /*AllowRvalues=*/true,
4616 AllowExplicit)) {
4617 // In the second case, if the reference is an rvalue reference
4618 // and the second standard conversion sequence of the
4619 // user-defined conversion sequence includes an lvalue-to-rvalue
4620 // conversion, the program is ill-formed.
4621 if (ICS.isUserDefined() && isRValRef &&
4622 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4623 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4624
4625 return ICS;
4626 }
4627
4628 // A temporary of function type cannot be created; don't even try.
4629 if (T1->isFunctionType())
4630 return ICS;
4631
4632 // -- Otherwise, a temporary of type "cv1 T1" is created and
4633 // initialized from the initializer expression using the
4634 // rules for a non-reference copy initialization (8.5). The
4635 // reference is then bound to the temporary. If T1 is
4636 // reference-related to T2, cv1 must be the same
4637 // cv-qualification as, or greater cv-qualification than,
4638 // cv2; otherwise, the program is ill-formed.
4639 if (RefRelationship == Sema::Ref_Related) {
4640 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4641 // we would be reference-compatible or reference-compatible with
4642 // added qualification. But that wasn't the case, so the reference
4643 // initialization fails.
4644 //
4645 // Note that we only want to check address spaces and cvr-qualifiers here.
4646 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4647 Qualifiers T1Quals = T1.getQualifiers();
4648 Qualifiers T2Quals = T2.getQualifiers();
4649 T1Quals.removeObjCGCAttr();
4650 T1Quals.removeObjCLifetime();
4651 T2Quals.removeObjCGCAttr();
4652 T2Quals.removeObjCLifetime();
4653 // MS compiler ignores __unaligned qualifier for references; do the same.
4654 T1Quals.removeUnaligned();
4655 T2Quals.removeUnaligned();
4656 if (!T1Quals.compatiblyIncludes(T2Quals))
4657 return ICS;
4658 }
4659
4660 // If at least one of the types is a class type, the types are not
4661 // related, and we aren't allowed any user conversions, the
4662 // reference binding fails. This case is important for breaking
4663 // recursion, since TryImplicitConversion below will attempt to
4664 // create a temporary through the use of a copy constructor.
4665 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4666 (T1->isRecordType() || T2->isRecordType()))
4667 return ICS;
4668
4669 // If T1 is reference-related to T2 and the reference is an rvalue
4670 // reference, the initializer expression shall not be an lvalue.
4671 if (RefRelationship >= Sema::Ref_Related &&
4672 isRValRef && Init->Classify(S.Context).isLValue())
4673 return ICS;
4674
4675 // C++ [over.ics.ref]p2:
4676 // When a parameter of reference type is not bound directly to
4677 // an argument expression, the conversion sequence is the one
4678 // required to convert the argument expression to the
4679 // underlying type of the reference according to
4680 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4681 // to copy-initializing a temporary of the underlying type with
4682 // the argument expression. Any difference in top-level
4683 // cv-qualification is subsumed by the initialization itself
4684 // and does not constitute a conversion.
4685 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4686 /*AllowExplicit=*/false,
4687 /*InOverloadResolution=*/false,
4688 /*CStyle=*/false,
4689 /*AllowObjCWritebackConversion=*/false,
4690 /*AllowObjCConversionOnExplicit=*/false);
4691
4692 // Of course, that's still a reference binding.
4693 if (ICS.isStandard()) {
4694 ICS.Standard.ReferenceBinding = true;
4695 ICS.Standard.IsLvalueReference = !isRValRef;
4696 ICS.Standard.BindsToFunctionLvalue = false;
4697 ICS.Standard.BindsToRvalue = true;
4698 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4699 ICS.Standard.ObjCLifetimeConversionBinding = false;
4700 } else if (ICS.isUserDefined()) {
4701 const ReferenceType *LValRefType =
4702 ICS.UserDefined.ConversionFunction->getReturnType()
4703 ->getAs<LValueReferenceType>();
4704
4705 // C++ [over.ics.ref]p3:
4706 // Except for an implicit object parameter, for which see 13.3.1, a
4707 // standard conversion sequence cannot be formed if it requires [...]
4708 // binding an rvalue reference to an lvalue other than a function
4709 // lvalue.
4710 // Note that the function case is not possible here.
4711 if (DeclType->isRValueReferenceType() && LValRefType) {
4712 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4713 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4714 // reference to an rvalue!
4715 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4716 return ICS;
4717 }
4718
4719 ICS.UserDefined.After.ReferenceBinding = true;
4720 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4721 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4722 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4723 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4724 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4725 }
4726
4727 return ICS;
4728}
4729
4730static ImplicitConversionSequence
4731TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4732 bool SuppressUserConversions,
4733 bool InOverloadResolution,
4734 bool AllowObjCWritebackConversion,
4735 bool AllowExplicit = false);
4736
4737/// TryListConversion - Try to copy-initialize a value of type ToType from the
4738/// initializer list From.
4739static ImplicitConversionSequence
4740TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4741 bool SuppressUserConversions,
4742 bool InOverloadResolution,
4743 bool AllowObjCWritebackConversion) {
4744 // C++11 [over.ics.list]p1:
4745 // When an argument is an initializer list, it is not an expression and
4746 // special rules apply for converting it to a parameter type.
4747
4748 ImplicitConversionSequence Result;
4749 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4750
4751 // We need a complete type for what follows. Incomplete types can never be
4752 // initialized from init lists.
4753 if (!S.isCompleteType(From->getLocStart(), ToType))
4754 return Result;
4755
4756 // Per DR1467:
4757 // If the parameter type is a class X and the initializer list has a single
4758 // element of type cv U, where U is X or a class derived from X, the
4759 // implicit conversion sequence is the one required to convert the element
4760 // to the parameter type.
4761 //
4762 // Otherwise, if the parameter type is a character array [... ]
4763 // and the initializer list has a single element that is an
4764 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4765 // implicit conversion sequence is the identity conversion.
4766 if (From->getNumInits() == 1) {
4767 if (ToType->isRecordType()) {
4768 QualType InitType = From->getInit(0)->getType();
4769 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4770 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4771 return TryCopyInitialization(S, From->getInit(0), ToType,
4772 SuppressUserConversions,
4773 InOverloadResolution,
4774 AllowObjCWritebackConversion);
4775 }
4776 // FIXME: Check the other conditions here: array of character type,
4777 // initializer is a string literal.
4778 if (ToType->isArrayType()) {
4779 InitializedEntity Entity =
4780 InitializedEntity::InitializeParameter(S.Context, ToType,
4781 /*Consumed=*/false);
4782 if (S.CanPerformCopyInitialization(Entity, From)) {
4783 Result.setStandard();
4784 Result.Standard.setAsIdentityConversion();
4785 Result.Standard.setFromType(ToType);
4786 Result.Standard.setAllToTypes(ToType);
4787 return Result;
4788 }
4789 }
4790 }
4791
4792 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4793 // C++11 [over.ics.list]p2:
4794 // If the parameter type is std::initializer_list<X> or "array of X" and
4795 // all the elements can be implicitly converted to X, the implicit
4796 // conversion sequence is the worst conversion necessary to convert an
4797 // element of the list to X.
4798 //
4799 // C++14 [over.ics.list]p3:
4800 // Otherwise, if the parameter type is "array of N X", if the initializer
4801 // list has exactly N elements or if it has fewer than N elements and X is
4802 // default-constructible, and if all the elements of the initializer list
4803 // can be implicitly converted to X, the implicit conversion sequence is
4804 // the worst conversion necessary to convert an element of the list to X.
4805 //
4806 // FIXME: We're missing a lot of these checks.
4807 bool toStdInitializerList = false;
4808 QualType X;
4809 if (ToType->isArrayType())
4810 X = S.Context.getAsArrayType(ToType)->getElementType();
4811 else
4812 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4813 if (!X.isNull()) {
4814 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4815 Expr *Init = From->getInit(i);
4816 ImplicitConversionSequence ICS =
4817 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4818 InOverloadResolution,
4819 AllowObjCWritebackConversion);
4820 // If a single element isn't convertible, fail.
4821 if (ICS.isBad()) {
4822 Result = ICS;
4823 break;
4824 }
4825 // Otherwise, look for the worst conversion.
4826 if (Result.isBad() ||
4827 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4828 Result) ==
4829 ImplicitConversionSequence::Worse)
4830 Result = ICS;
4831 }
4832
4833 // For an empty list, we won't have computed any conversion sequence.
4834 // Introduce the identity conversion sequence.
4835 if (From->getNumInits() == 0) {
4836 Result.setStandard();
4837 Result.Standard.setAsIdentityConversion();
4838 Result.Standard.setFromType(ToType);
4839 Result.Standard.setAllToTypes(ToType);
4840 }
4841
4842 Result.setStdInitializerListElement(toStdInitializerList);
4843 return Result;
4844 }
4845
4846 // C++14 [over.ics.list]p4:
4847 // C++11 [over.ics.list]p3:
4848 // Otherwise, if the parameter is a non-aggregate class X and overload
4849 // resolution chooses a single best constructor [...] the implicit
4850 // conversion sequence is a user-defined conversion sequence. If multiple
4851 // constructors are viable but none is better than the others, the
4852 // implicit conversion sequence is a user-defined conversion sequence.
4853 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4854 // This function can deal with initializer lists.
4855 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4856 /*AllowExplicit=*/false,
4857 InOverloadResolution, /*CStyle=*/false,
4858 AllowObjCWritebackConversion,
4859 /*AllowObjCConversionOnExplicit=*/false);
4860 }
4861
4862 // C++14 [over.ics.list]p5:
4863 // C++11 [over.ics.list]p4:
4864 // Otherwise, if the parameter has an aggregate type which can be
4865 // initialized from the initializer list [...] the implicit conversion
4866 // sequence is a user-defined conversion sequence.
4867 if (ToType->isAggregateType()) {
4868 // Type is an aggregate, argument is an init list. At this point it comes
4869 // down to checking whether the initialization works.
4870 // FIXME: Find out whether this parameter is consumed or not.
4871 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4872 // need to call into the initialization code here; overload resolution
4873 // should not be doing that.
4874 InitializedEntity Entity =
4875 InitializedEntity::InitializeParameter(S.Context, ToType,
4876 /*Consumed=*/false);
4877 if (S.CanPerformCopyInitialization(Entity, From)) {
4878 Result.setUserDefined();
4879 Result.UserDefined.Before.setAsIdentityConversion();
4880 // Initializer lists don't have a type.
4881 Result.UserDefined.Before.setFromType(QualType());
4882 Result.UserDefined.Before.setAllToTypes(QualType());
4883
4884 Result.UserDefined.After.setAsIdentityConversion();
4885 Result.UserDefined.After.setFromType(ToType);
4886 Result.UserDefined.After.setAllToTypes(ToType);
4887 Result.UserDefined.ConversionFunction = nullptr;
4888 }
4889 return Result;
4890 }
4891
4892 // C++14 [over.ics.list]p6:
4893 // C++11 [over.ics.list]p5:
4894 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4895 if (ToType->isReferenceType()) {
4896 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4897 // mention initializer lists in any way. So we go by what list-
4898 // initialization would do and try to extrapolate from that.
4899
4900 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4901
4902 // If the initializer list has a single element that is reference-related
4903 // to the parameter type, we initialize the reference from that.
4904 if (From->getNumInits() == 1) {
4905 Expr *Init = From->getInit(0);
4906
4907 QualType T2 = Init->getType();
4908
4909 // If the initializer is the address of an overloaded function, try
4910 // to resolve the overloaded function. If all goes well, T2 is the
4911 // type of the resulting function.
4912 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4913 DeclAccessPair Found;
4914 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4915 Init, ToType, false, Found))
4916 T2 = Fn->getType();
4917 }
4918
4919 // Compute some basic properties of the types and the initializer.
4920 bool dummy1 = false;
4921 bool dummy2 = false;
4922 bool dummy3 = false;
4923 Sema::ReferenceCompareResult RefRelationship
4924 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4925 dummy2, dummy3);
4926
4927 if (RefRelationship >= Sema::Ref_Related) {
4928 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4929 SuppressUserConversions,
4930 /*AllowExplicit=*/false);
4931 }
4932 }
4933
4934 // Otherwise, we bind the reference to a temporary created from the
4935 // initializer list.
4936 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4937 InOverloadResolution,
4938 AllowObjCWritebackConversion);
4939 if (Result.isFailure())
4940 return Result;
4941 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4942, __extension__ __PRETTY_FUNCTION__))
4942 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4942, __extension__ __PRETTY_FUNCTION__))
;
4943
4944 // Can we even bind to a temporary?
4945 if (ToType->isRValueReferenceType() ||
4946 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4947 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4948 Result.UserDefined.After;
4949 SCS.ReferenceBinding = true;
4950 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4951 SCS.BindsToRvalue = true;
4952 SCS.BindsToFunctionLvalue = false;
4953 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4954 SCS.ObjCLifetimeConversionBinding = false;
4955 } else
4956 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4957 From, ToType);
4958 return Result;
4959 }
4960
4961 // C++14 [over.ics.list]p7:
4962 // C++11 [over.ics.list]p6:
4963 // Otherwise, if the parameter type is not a class:
4964 if (!ToType->isRecordType()) {
4965 // - if the initializer list has one element that is not itself an
4966 // initializer list, the implicit conversion sequence is the one
4967 // required to convert the element to the parameter type.
4968 unsigned NumInits = From->getNumInits();
4969 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4970 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4971 SuppressUserConversions,
4972 InOverloadResolution,
4973 AllowObjCWritebackConversion);
4974 // - if the initializer list has no elements, the implicit conversion
4975 // sequence is the identity conversion.
4976 else if (NumInits == 0) {
4977 Result.setStandard();
4978 Result.Standard.setAsIdentityConversion();
4979 Result.Standard.setFromType(ToType);
4980 Result.Standard.setAllToTypes(ToType);
4981 }
4982 return Result;
4983 }
4984
4985 // C++14 [over.ics.list]p8:
4986 // C++11 [over.ics.list]p7:
4987 // In all cases other than those enumerated above, no conversion is possible
4988 return Result;
4989}
4990
4991/// TryCopyInitialization - Try to copy-initialize a value of type
4992/// ToType from the expression From. Return the implicit conversion
4993/// sequence required to pass this argument, which may be a bad
4994/// conversion sequence (meaning that the argument cannot be passed to
4995/// a parameter of this type). If @p SuppressUserConversions, then we
4996/// do not permit any user-defined conversion sequences.
4997static ImplicitConversionSequence
4998TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4999 bool SuppressUserConversions,
5000 bool InOverloadResolution,
5001 bool AllowObjCWritebackConversion,
5002 bool AllowExplicit) {
5003 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5004 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5005 InOverloadResolution,AllowObjCWritebackConversion);
5006
5007 if (ToType->isReferenceType())
5008 return TryReferenceInit(S, From, ToType,
5009 /*FIXME:*/From->getLocStart(),
5010 SuppressUserConversions,
5011 AllowExplicit);
5012
5013 return TryImplicitConversion(S, From, ToType,
5014 SuppressUserConversions,
5015 /*AllowExplicit=*/false,
5016 InOverloadResolution,
5017 /*CStyle=*/false,
5018 AllowObjCWritebackConversion,
5019 /*AllowObjCConversionOnExplicit=*/false);
5020}
5021
5022static bool TryCopyInitialization(const CanQualType FromQTy,
5023 const CanQualType ToQTy,
5024 Sema &S,
5025 SourceLocation Loc,
5026 ExprValueKind FromVK) {
5027 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5028 ImplicitConversionSequence ICS =
5029 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5030
5031 return !ICS.isBad();
5032}
5033
5034/// TryObjectArgumentInitialization - Try to initialize the object
5035/// parameter of the given member function (@c Method) from the
5036/// expression @p From.
5037static ImplicitConversionSequence
5038TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5039 Expr::Classification FromClassification,
5040 CXXMethodDecl *Method,
5041 CXXRecordDecl *ActingContext) {
5042 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5043 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5044 // const volatile object.
5045 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
5046 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
5047 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
5048
5049 // Set up the conversion sequence as a "bad" conversion, to allow us
5050 // to exit early.
5051 ImplicitConversionSequence ICS;
5052
5053 // We need to have an object of class type.
5054 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5055 FromType = PT->getPointeeType();
5056
5057 // When we had a pointer, it's implicitly dereferenced, so we
5058 // better have an lvalue.
5059 assert(FromClassification.isLValue())(static_cast <bool> (FromClassification.isLValue()) ? void
(0) : __assert_fail ("FromClassification.isLValue()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5059, __extension__ __PRETTY_FUNCTION__))
;
5060 }
5061
5062 assert(FromType->isRecordType())(static_cast <bool> (FromType->isRecordType()) ? void
(0) : __assert_fail ("FromType->isRecordType()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5062, __extension__ __PRETTY_FUNCTION__))
;
5063
5064 // C++0x [over.match.funcs]p4:
5065 // For non-static member functions, the type of the implicit object
5066 // parameter is
5067 //
5068 // - "lvalue reference to cv X" for functions declared without a
5069 // ref-qualifier or with the & ref-qualifier
5070 // - "rvalue reference to cv X" for functions declared with the &&
5071 // ref-qualifier
5072 //
5073 // where X is the class of which the function is a member and cv is the
5074 // cv-qualification on the member function declaration.
5075 //
5076 // However, when finding an implicit conversion sequence for the argument, we
5077 // are not allowed to perform user-defined conversions
5078 // (C++ [over.match.funcs]p5). We perform a simplified version of
5079 // reference binding here, that allows class rvalues to bind to
5080 // non-constant references.
5081
5082 // First check the qualifiers.
5083 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5084 if (ImplicitParamType.getCVRQualifiers()
5085 != FromTypeCanon.getLocalCVRQualifiers() &&
5086 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5087 ICS.setBad(BadConversionSequence::bad_qualifiers,
5088 FromType, ImplicitParamType);
5089 return ICS;
5090 }
5091
5092 // Check that we have either the same type or a derived type. It
5093 // affects the conversion rank.
5094 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5095 ImplicitConversionKind SecondKind;
5096 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5097 SecondKind = ICK_Identity;
5098 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5099 SecondKind = ICK_Derived_To_Base;
5100 else {
5101 ICS.setBad(BadConversionSequence::unrelated_class,
5102 FromType, ImplicitParamType);
5103 return ICS;
5104 }
5105
5106 // Check the ref-qualifier.
5107 switch (Method->getRefQualifier()) {
5108 case RQ_None:
5109 // Do nothing; we don't care about lvalueness or rvalueness.
5110 break;
5111
5112 case RQ_LValue:
5113 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5114 // non-const lvalue reference cannot bind to an rvalue
5115 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5116 ImplicitParamType);
5117 return ICS;
5118 }
5119 break;
5120
5121 case RQ_RValue:
5122 if (!FromClassification.isRValue()) {
5123 // rvalue reference cannot bind to an lvalue
5124 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5125 ImplicitParamType);
5126 return ICS;
5127 }
5128 break;
5129 }
5130
5131 // Success. Mark this as a reference binding.
5132 ICS.setStandard();
5133 ICS.Standard.setAsIdentityConversion();
5134 ICS.Standard.Second = SecondKind;
5135 ICS.Standard.setFromType(FromType);
5136 ICS.Standard.setAllToTypes(ImplicitParamType);
5137 ICS.Standard.ReferenceBinding = true;
5138 ICS.Standard.DirectBinding = true;
5139 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5140 ICS.Standard.BindsToFunctionLvalue = false;
5141 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5142 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5143 = (Method->getRefQualifier() == RQ_None);
5144 return ICS;
5145}
5146
5147/// PerformObjectArgumentInitialization - Perform initialization of
5148/// the implicit object parameter for the given Method with the given
5149/// expression.
5150ExprResult
5151Sema::PerformObjectArgumentInitialization(Expr *From,
5152 NestedNameSpecifier *Qualifier,
5153 NamedDecl *FoundDecl,
5154 CXXMethodDecl *Method) {
5155 QualType FromRecordType, DestType;
5156 QualType ImplicitParamRecordType =
5157 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5158
5159 Expr::Classification FromClassification;
5160 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5161 FromRecordType = PT->getPointeeType();
5162 DestType = Method->getThisType(Context);
5163 FromClassification = Expr::Classification::makeSimpleLValue();
5164 } else {
5165 FromRecordType = From->getType();
5166 DestType = ImplicitParamRecordType;
5167 FromClassification = From->Classify(Context);
5168
5169 // When performing member access on an rvalue, materialize a temporary.
5170 if (From->isRValue()) {
5171 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5172 Method->getRefQualifier() !=
5173 RefQualifierKind::RQ_RValue);
5174 }
5175 }
5176
5177 // Note that we always use the true parent context when performing
5178 // the actual argument initialization.
5179 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5180 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5181 Method->getParent());
5182 if (ICS.isBad()) {
5183 switch (ICS.Bad.Kind) {
5184 case BadConversionSequence::bad_qualifiers: {
5185 Qualifiers FromQs = FromRecordType.getQualifiers();
5186 Qualifiers ToQs = DestType.getQualifiers();
5187 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5188 if (CVR) {
5189 Diag(From->getLocStart(),
5190 diag::err_member_function_call_bad_cvr)
5191 << Method->getDeclName() << FromRecordType << (CVR - 1)
5192 << From->getSourceRange();
5193 Diag(Method->getLocation(), diag::note_previous_decl)
5194 << Method->getDeclName();
5195 return ExprError();
5196 }
5197 break;
5198 }
5199
5200 case BadConversionSequence::lvalue_ref_to_rvalue:
5201 case BadConversionSequence::rvalue_ref_to_lvalue: {
5202 bool IsRValueQualified =
5203 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5204 Diag(From->getLocStart(), diag::err_member_function_call_bad_ref)
5205 << Method->getDeclName() << FromClassification.isRValue()
5206 << IsRValueQualified;
5207 Diag(Method->getLocation(), diag::note_previous_decl)
5208 << Method->getDeclName();
5209 return ExprError();
5210 }
5211
5212 case BadConversionSequence::no_conversion:
5213 case BadConversionSequence::unrelated_class:
5214 break;
5215 }
5216
5217 return Diag(From->getLocStart(),
5218 diag::err_member_function_call_bad_type)
5219 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5220 }
5221
5222 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5223 ExprResult FromRes =
5224 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5225 if (FromRes.isInvalid())
5226 return ExprError();
5227 From = FromRes.get();
5228 }
5229
5230 if (!Context.hasSameType(From->getType(), DestType))
5231 From = ImpCastExprToType(From, DestType, CK_NoOp,
5232 From->getValueKind()).get();
5233 return From;
5234}
5235
5236/// TryContextuallyConvertToBool - Attempt to contextually convert the
5237/// expression From to bool (C++0x [conv]p3).
5238static ImplicitConversionSequence
5239TryContextuallyConvertToBool(Sema &S, Expr *From) {
5240 return TryImplicitConversion(S, From, S.Context.BoolTy,
5241 /*SuppressUserConversions=*/false,
5242 /*AllowExplicit=*/true,
5243 /*InOverloadResolution=*/false,
5244 /*CStyle=*/false,
5245 /*AllowObjCWritebackConversion=*/false,
5246 /*AllowObjCConversionOnExplicit=*/false);
5247}
5248
5249/// PerformContextuallyConvertToBool - Perform a contextual conversion
5250/// of the expression From to bool (C++0x [conv]p3).
5251ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5252 if (checkPlaceholderForOverload(*this, From))
5253 return ExprError();
5254
5255 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5256 if (!ICS.isBad())
5257 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5258
5259 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5260 return Diag(From->getLocStart(),
5261 diag::err_typecheck_bool_condition)
5262 << From->getType() << From->getSourceRange();
5263 return ExprError();
5264}
5265
5266/// Check that the specified conversion is permitted in a converted constant
5267/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5268/// is acceptable.
5269static bool CheckConvertedConstantConversions(Sema &S,
5270 StandardConversionSequence &SCS) {
5271 // Since we know that the target type is an integral or unscoped enumeration
5272 // type, most conversion kinds are impossible. All possible First and Third
5273 // conversions are fine.
5274 switch (SCS.Second) {
5275 case ICK_Identity:
5276 case ICK_Function_Conversion:
5277 case ICK_Integral_Promotion:
5278 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5279 case ICK_Zero_Queue_Conversion:
5280 return true;
5281
5282 case ICK_Boolean_Conversion:
5283 // Conversion from an integral or unscoped enumeration type to bool is
5284 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5285 // conversion, so we allow it in a converted constant expression.
5286 //
5287 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5288 // a lot of popular code. We should at least add a warning for this
5289 // (non-conforming) extension.
5290 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5291 SCS.getToType(2)->isBooleanType();
5292
5293 case ICK_Pointer_Conversion:
5294 case ICK_Pointer_Member:
5295 // C++1z: null pointer conversions and null member pointer conversions are
5296 // only permitted if the source type is std::nullptr_t.
5297 return SCS.getFromType()->isNullPtrType();
5298
5299 case ICK_Floating_Promotion:
5300 case ICK_Complex_Promotion:
5301 case ICK_Floating_Conversion:
5302 case ICK_Complex_Conversion:
5303 case ICK_Floating_Integral:
5304 case ICK_Compatible_Conversion:
5305 case ICK_Derived_To_Base:
5306 case ICK_Vector_Conversion:
5307 case ICK_Vector_Splat:
5308 case ICK_Complex_Real:
5309 case ICK_Block_Pointer_Conversion:
5310 case ICK_TransparentUnionConversion:
5311 case ICK_Writeback_Conversion:
5312 case ICK_Zero_Event_Conversion:
5313 case ICK_C_Only_Conversion:
5314 case ICK_Incompatible_Pointer_Conversion:
5315 return false;
5316
5317 case ICK_Lvalue_To_Rvalue:
5318 case ICK_Array_To_Pointer:
5319 case ICK_Function_To_Pointer:
5320 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5320)
;
5321
5322 case ICK_Qualification:
5323 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5323)
;
5324
5325 case ICK_Num_Conversion_Kinds:
5326 break;
5327 }
5328
5329 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5329)
;
5330}
5331
5332/// CheckConvertedConstantExpression - Check that the expression From is a
5333/// converted constant expression of type T, perform the conversion and produce
5334/// the converted expression, per C++11 [expr.const]p3.
5335static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5336 QualType T, APValue &Value,
5337 Sema::CCEKind CCE,
5338 bool RequireInt) {
5339 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5340, __extension__ __PRETTY_FUNCTION__))
5340 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5340, __extension__ __PRETTY_FUNCTION__))
;
5341
5342 if (checkPlaceholderForOverload(S, From))
5343 return ExprError();
5344
5345 // C++1z [expr.const]p3:
5346 // A converted constant expression of type T is an expression,
5347 // implicitly converted to type T, where the converted
5348 // expression is a constant expression and the implicit conversion
5349 // sequence contains only [... list of conversions ...].
5350 // C++1z [stmt.if]p2:
5351 // If the if statement is of the form if constexpr, the value of the
5352 // condition shall be a contextually converted constant expression of type
5353 // bool.
5354 ImplicitConversionSequence ICS =
5355 CCE == Sema::CCEK_ConstexprIf
5356 ? TryContextuallyConvertToBool(S, From)
5357 : TryCopyInitialization(S, From, T,
5358 /*SuppressUserConversions=*/false,
5359 /*InOverloadResolution=*/false,
5360 /*AllowObjcWritebackConversion=*/false,
5361 /*AllowExplicit=*/false);
5362 StandardConversionSequence *SCS = nullptr;
5363 switch (ICS.getKind()) {
5364 case ImplicitConversionSequence::StandardConversion:
5365 SCS = &ICS.Standard;
5366 break;
5367 case ImplicitConversionSequence::UserDefinedConversion:
5368 // We are converting to a non-class type, so the Before sequence
5369 // must be trivial.
5370 SCS = &ICS.UserDefined.After;
5371 break;
5372 case ImplicitConversionSequence::AmbiguousConversion:
5373 case ImplicitConversionSequence::BadConversion:
5374 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5375 return S.Diag(From->getLocStart(),
5376 diag::err_typecheck_converted_constant_expression)
5377 << From->getType() << From->getSourceRange() << T;
5378 return ExprError();
5379
5380 case ImplicitConversionSequence::EllipsisConversion:
5381 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5381)
;
5382 }
5383
5384 // Check that we would only use permitted conversions.
5385 if (!CheckConvertedConstantConversions(S, *SCS)) {
5386 return S.Diag(From->getLocStart(),
5387 diag::err_typecheck_converted_constant_expression_disallowed)
5388 << From->getType() << From->getSourceRange() << T;
5389 }
5390 // [...] and where the reference binding (if any) binds directly.
5391 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5392 return S.Diag(From->getLocStart(),
5393 diag::err_typecheck_converted_constant_expression_indirect)
5394 << From->getType() << From->getSourceRange() << T;
5395 }
5396
5397 ExprResult Result =
5398 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5399 if (Result.isInvalid())
5400 return Result;
5401
5402 // Check for a narrowing implicit conversion.
5403 APValue PreNarrowingValue;
5404 QualType PreNarrowingType;
5405 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5406 PreNarrowingType)) {
5407 case NK_Dependent_Narrowing:
5408 // Implicit conversion to a narrower type, but the expression is
5409 // value-dependent so we can't tell whether it's actually narrowing.
5410 case NK_Variable_Narrowing:
5411 // Implicit conversion to a narrower type, and the value is not a constant
5412 // expression. We'll diagnose this in a moment.
5413 case NK_Not_Narrowing:
5414 break;
5415
5416 case NK_Constant_Narrowing:
5417 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5418 << CCE << /*Constant*/1
5419 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5420 break;
5421
5422 case NK_Type_Narrowing:
5423 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5424 << CCE << /*Constant*/0 << From->getType() << T;
5425 break;
5426 }
5427
5428 if (Result.get()->isValueDependent()) {
5429 Value = APValue();
5430 return Result;
5431 }
5432
5433 // Check the expression is a constant expression.
5434 SmallVector<PartialDiagnosticAt, 8> Notes;
5435 Expr::EvalResult Eval;
5436 Eval.Diag = &Notes;
5437 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5438 ? Expr::EvaluateForMangling
5439 : Expr::EvaluateForCodeGen;
5440
5441 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5442 (RequireInt && !Eval.Val.isInt())) {
5443 // The expression can't be folded, so we can't keep it at this position in
5444 // the AST.
5445 Result = ExprError();
5446 } else {
5447 Value = Eval.Val;
5448
5449 if (Notes.empty()) {
5450 // It's a constant expression.
5451 return Result;
5452 }
5453 }
5454
5455 // It's not a constant expression. Produce an appropriate diagnostic.
5456 if (Notes.size() == 1 &&
5457 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5458 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5459 else {
5460 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5461 << CCE << From->getSourceRange();
5462 for (unsigned I = 0; I < Notes.size(); ++I)
5463 S.Diag(Notes[I].first, Notes[I].second);
5464 }
5465 return ExprError();
5466}
5467
5468ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5469 APValue &Value, CCEKind CCE) {
5470 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5471}
5472
5473ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5474 llvm::APSInt &Value,
5475 CCEKind CCE) {
5476 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5476, __extension__ __PRETTY_FUNCTION__))
;
5477
5478 APValue V;
5479 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5480 if (!R.isInvalid() && !R.get()->isValueDependent())
5481 Value = V.getInt();
5482 return R;
5483}
5484
5485
5486/// dropPointerConversions - If the given standard conversion sequence
5487/// involves any pointer conversions, remove them. This may change
5488/// the result type of the conversion sequence.
5489static void dropPointerConversion(StandardConversionSequence &SCS) {
5490 if (SCS.Second == ICK_Pointer_Conversion) {
5491 SCS.Second = ICK_Identity;
5492 SCS.Third = ICK_Identity;
5493 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5494 }
5495}
5496
5497/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5498/// convert the expression From to an Objective-C pointer type.
5499static ImplicitConversionSequence
5500TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5501 // Do an implicit conversion to 'id'.
5502 QualType Ty = S.Context.getObjCIdType();
5503 ImplicitConversionSequence ICS
5504 = TryImplicitConversion(S, From, Ty,
5505 // FIXME: Are these flags correct?
5506 /*SuppressUserConversions=*/false,
5507 /*AllowExplicit=*/true,
5508 /*InOverloadResolution=*/false,
5509 /*CStyle=*/false,
5510 /*AllowObjCWritebackConversion=*/false,
5511 /*AllowObjCConversionOnExplicit=*/true);
5512
5513 // Strip off any final conversions to 'id'.
5514 switch (ICS.getKind()) {
5515 case ImplicitConversionSequence::BadConversion:
5516 case ImplicitConversionSequence::AmbiguousConversion:
5517 case ImplicitConversionSequence::EllipsisConversion:
5518 break;
5519
5520 case ImplicitConversionSequence::UserDefinedConversion:
5521 dropPointerConversion(ICS.UserDefined.After);
5522 break;
5523
5524 case ImplicitConversionSequence::StandardConversion:
5525 dropPointerConversion(ICS.Standard);
5526 break;
5527 }
5528
5529 return ICS;
5530}
5531
5532/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5533/// conversion of the expression From to an Objective-C pointer type.
5534/// Returns a valid but null ExprResult if no conversion sequence exists.
5535ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5536 if (checkPlaceholderForOverload(*this, From))
5537 return ExprError();
5538
5539 QualType Ty = Context.getObjCIdType();
5540 ImplicitConversionSequence ICS =
5541 TryContextuallyConvertToObjCPointer(*this, From);
5542 if (!ICS.isBad())
5543 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5544 return ExprResult();
5545}
5546
5547/// Determine whether the provided type is an integral type, or an enumeration
5548/// type of a permitted flavor.
5549bool Sema::ICEConvertDiagnoser::match(QualType T) {
5550 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5551 : T->isIntegralOrUnscopedEnumerationType();
5552}
5553
5554static ExprResult
5555diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5556 Sema::ContextualImplicitConverter &Converter,
5557 QualType T, UnresolvedSetImpl &ViableConversions) {
5558
5559 if (Converter.Suppress)
5560 return ExprError();
5561
5562 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5563 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5564 CXXConversionDecl *Conv =
5565 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5566 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5567 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5568 }
5569 return From;
5570}
5571
5572static bool
5573diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5574 Sema::ContextualImplicitConverter &Converter,
5575 QualType T, bool HadMultipleCandidates,
5576 UnresolvedSetImpl &ExplicitConversions) {
5577 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5578 DeclAccessPair Found = ExplicitConversions[0];
5579 CXXConversionDecl *Conversion =
5580 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5581
5582 // The user probably meant to invoke the given explicit
5583 // conversion; use it.
5584 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5585 std::string TypeStr;
5586 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5587
5588 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5589 << FixItHint::CreateInsertion(From->getLocStart(),
5590 "static_cast<" + TypeStr + ">(")
5591 << FixItHint::CreateInsertion(
5592 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5593 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5594
5595 // If we aren't in a SFINAE context, build a call to the
5596 // explicit conversion function.
5597 if (SemaRef.isSFINAEContext())
5598 return true;
5599
5600 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5601 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5602 HadMultipleCandidates);
5603 if (Result.isInvalid())
5604 return true;
5605 // Record usage of conversion in an implicit cast.
5606 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5607 CK_UserDefinedConversion, Result.get(),
5608 nullptr, Result.get()->getValueKind());
5609 }
5610 return false;
5611}
5612
5613static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5614 Sema::ContextualImplicitConverter &Converter,
5615 QualType T, bool HadMultipleCandidates,
5616 DeclAccessPair &Found) {
5617 CXXConversionDecl *Conversion =
5618 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5619 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5620
5621 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5622 if (!Converter.SuppressConversion) {
5623 if (SemaRef.isSFINAEContext())
5624 return true;
5625
5626 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5627 << From->getSourceRange();
5628 }
5629
5630 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5631 HadMultipleCandidates);
5632 if (Result.isInvalid())
5633 return true;
5634 // Record usage of conversion in an implicit cast.
5635 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5636 CK_UserDefinedConversion, Result.get(),
5637 nullptr, Result.get()->getValueKind());
5638 return false;
5639}
5640
5641static ExprResult finishContextualImplicitConversion(
5642 Sema &SemaRef, SourceLocation Loc, Expr *From,
5643 Sema::ContextualImplicitConverter &Converter) {
5644 if (!Converter.match(From->getType()) && !Converter.Suppress)
5645 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5646 << From->getSourceRange();
5647
5648 return SemaRef.DefaultLvalueConversion(From);
5649}
5650
5651static void
5652collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5653 UnresolvedSetImpl &ViableConversions,
5654 OverloadCandidateSet &CandidateSet) {
5655 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5656 DeclAccessPair FoundDecl = ViableConversions[I];
5657 NamedDecl *D = FoundDecl.getDecl();
5658 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5659 if (isa<UsingShadowDecl>(D))
5660 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5661
5662 CXXConversionDecl *Conv;
5663 FunctionTemplateDecl *ConvTemplate;
5664 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5665 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5666 else
5667 Conv = cast<CXXConversionDecl>(D);
5668
5669 if (ConvTemplate)
5670 SemaRef.AddTemplateConversionCandidate(
5671 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5672 /*AllowObjCConversionOnExplicit=*/false);
5673 else
5674 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5675 ToType, CandidateSet,
5676 /*AllowObjCConversionOnExplicit=*/false);
5677 }
5678}
5679
5680/// Attempt to convert the given expression to a type which is accepted
5681/// by the given converter.
5682///
5683/// This routine will attempt to convert an expression of class type to a
5684/// type accepted by the specified converter. In C++11 and before, the class
5685/// must have a single non-explicit conversion function converting to a matching
5686/// type. In C++1y, there can be multiple such conversion functions, but only
5687/// one target type.
5688///
5689/// \param Loc The source location of the construct that requires the
5690/// conversion.
5691///
5692/// \param From The expression we're converting from.
5693///
5694/// \param Converter Used to control and diagnose the conversion process.
5695///
5696/// \returns The expression, converted to an integral or enumeration type if
5697/// successful.
5698ExprResult Sema::PerformContextualImplicitConversion(
5699 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5700 // We can't perform any more checking for type-dependent expressions.
5701 if (From->isTypeDependent())
5702 return From;
5703
5704 // Process placeholders immediately.
5705 if (From->hasPlaceholderType()) {
5706 ExprResult result = CheckPlaceholderExpr(From);
5707 if (result.isInvalid())
5708 return result;
5709 From = result.get();
5710 }
5711
5712 // If the expression already has a matching type, we're golden.
5713 QualType T = From->getType();
5714 if (Converter.match(T))
5715 return DefaultLvalueConversion(From);
5716
5717 // FIXME: Check for missing '()' if T is a function type?
5718
5719 // We can only perform contextual implicit conversions on objects of class
5720 // type.
5721 const RecordType *RecordTy = T->getAs<RecordType>();
5722 if (!RecordTy || !getLangOpts().CPlusPlus) {
5723 if (!Converter.Suppress)
5724 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5725 return From;
5726 }
5727
5728 // We must have a complete class type.
5729 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5730 ContextualImplicitConverter &Converter;
5731 Expr *From;
5732
5733 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5734 : Converter(Converter), From(From) {}
5735
5736 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5737 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5738 }
5739 } IncompleteDiagnoser(Converter, From);
5740
5741 if (Converter.Suppress ? !isCompleteType(Loc, T)
5742 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5743 return From;
5744
5745 // Look for a conversion to an integral or enumeration type.
5746 UnresolvedSet<4>
5747 ViableConversions; // These are *potentially* viable in C++1y.
5748 UnresolvedSet<4> ExplicitConversions;
5749 const auto &Conversions =
5750 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5751
5752 bool HadMultipleCandidates =
5753 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5754
5755 // To check that there is only one target type, in C++1y:
5756 QualType ToType;
5757 bool HasUniqueTargetType = true;
5758
5759 // Collect explicit or viable (potentially in C++1y) conversions.
5760 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5761 NamedDecl *D = (*I)->getUnderlyingDecl();
5762 CXXConversionDecl *Conversion;
5763 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5764 if (ConvTemplate) {
5765 if (getLangOpts().CPlusPlus14)
5766 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5767 else
5768 continue; // C++11 does not consider conversion operator templates(?).
5769 } else
5770 Conversion = cast<CXXConversionDecl>(D);
5771
5772 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5774, __extension__ __PRETTY_FUNCTION__))
5773 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5774, __extension__ __PRETTY_FUNCTION__))
5774 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5774, __extension__ __PRETTY_FUNCTION__))
;
5775
5776 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5777 if (Converter.match(CurToType) || ConvTemplate) {
5778
5779 if (Conversion->isExplicit()) {
5780 // FIXME: For C++1y, do we need this restriction?
5781 // cf. diagnoseNoViableConversion()
5782 if (!ConvTemplate)
5783 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5784 } else {
5785 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5786 if (ToType.isNull())
5787 ToType = CurToType.getUnqualifiedType();
5788 else if (HasUniqueTargetType &&
5789 (CurToType.getUnqualifiedType() != ToType))
5790 HasUniqueTargetType = false;
5791 }
5792 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5793 }
5794 }
5795 }
5796
5797 if (getLangOpts().CPlusPlus14) {
5798 // C++1y [conv]p6:
5799 // ... An expression e of class type E appearing in such a context
5800 // is said to be contextually implicitly converted to a specified
5801 // type T and is well-formed if and only if e can be implicitly
5802 // converted to a type T that is determined as follows: E is searched
5803 // for conversion functions whose return type is cv T or reference to
5804 // cv T such that T is allowed by the context. There shall be
5805 // exactly one such T.
5806
5807 // If no unique T is found:
5808 if (ToType.isNull()) {
5809 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5810 HadMultipleCandidates,
5811 ExplicitConversions))
5812 return ExprError();
5813 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5814 }
5815
5816 // If more than one unique Ts are found:
5817 if (!HasUniqueTargetType)
5818 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5819 ViableConversions);
5820
5821 // If one unique T is found:
5822 // First, build a candidate set from the previously recorded
5823 // potentially viable conversions.
5824 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5825 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5826 CandidateSet);
5827
5828 // Then, perform overload resolution over the candidate set.
5829 OverloadCandidateSet::iterator Best;
5830 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5831 case OR_Success: {
5832 // Apply this conversion.
5833 DeclAccessPair Found =
5834 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5835 if (recordConversion(*this, Loc, From, Converter, T,
5836 HadMultipleCandidates, Found))
5837 return ExprError();
5838 break;
5839 }
5840 case OR_Ambiguous:
5841 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5842 ViableConversions);
5843 case OR_No_Viable_Function:
5844 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5845 HadMultipleCandidates,
5846 ExplicitConversions))
5847 return ExprError();
5848 LLVM_FALLTHROUGH[[clang::fallthrough]];
5849 case OR_Deleted:
5850 // We'll complain below about a non-integral condition type.
5851 break;
5852 }
5853 } else {
5854 switch (ViableConversions.size()) {
5855 case 0: {
5856 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5857 HadMultipleCandidates,
5858 ExplicitConversions))
5859 return ExprError();
5860
5861 // We'll complain below about a non-integral condition type.
5862 break;
5863 }
5864 case 1: {
5865 // Apply this conversion.
5866 DeclAccessPair Found = ViableConversions[0];
5867 if (recordConversion(*this, Loc, From, Converter, T,
5868 HadMultipleCandidates, Found))
5869 return ExprError();
5870 break;
5871 }
5872 default:
5873 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5874 ViableConversions);
5875 }
5876 }
5877
5878 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5879}
5880
5881/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5882/// an acceptable non-member overloaded operator for a call whose
5883/// arguments have types T1 (and, if non-empty, T2). This routine
5884/// implements the check in C++ [over.match.oper]p3b2 concerning
5885/// enumeration types.
5886static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5887 FunctionDecl *Fn,
5888 ArrayRef<Expr *> Args) {
5889 QualType T1 = Args[0]->getType();
5890 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5891
5892 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5893 return true;
5894
5895 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5896 return true;
5897
5898 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5899 if (Proto->getNumParams() < 1)
5900 return false;
5901
5902 if (T1->isEnumeralType()) {
5903 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5904 if (Context.hasSameUnqualifiedType(T1, ArgType))
5905 return true;
5906 }
5907
5908 if (Proto->getNumParams() < 2)
5909 return false;
5910
5911 if (!T2.isNull() && T2->isEnumeralType()) {
5912 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5913 if (Context.hasSameUnqualifiedType(T2, ArgType))
5914 return true;
5915 }
5916
5917 return false;
5918}
5919
5920/// AddOverloadCandidate - Adds the given function to the set of
5921/// candidate functions, using the given function call arguments. If
5922/// @p SuppressUserConversions, then don't allow user-defined
5923/// conversions via constructors or conversion operators.
5924///
5925/// \param PartialOverloading true if we are performing "partial" overloading
5926/// based on an incomplete set of function arguments. This feature is used by
5927/// code completion.
5928void
5929Sema::AddOverloadCandidate(FunctionDecl *Function,
5930 DeclAccessPair FoundDecl,
5931 ArrayRef<Expr *> Args,
5932 OverloadCandidateSet &CandidateSet,
5933 bool SuppressUserConversions,
5934 bool PartialOverloading,
5935 bool AllowExplicit,
5936 ConversionSequenceList EarlyConversions) {
5937 const FunctionProtoType *Proto
5938 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5939 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5939, __extension__ __PRETTY_FUNCTION__))
;
5940 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5941, __extension__ __PRETTY_FUNCTION__))
5941 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5941, __extension__ __PRETTY_FUNCTION__))
;
5942
5943 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5944 if (!isa<CXXConstructorDecl>(Method)) {
5945 // If we get here, it's because we're calling a member function
5946 // that is named without a member access expression (e.g.,
5947 // "this->f") that was either written explicitly or created
5948 // implicitly. This can happen with a qualified call to a member
5949 // function, e.g., X::f(). We use an empty type for the implied
5950 // object argument (C++ [over.call.func]p3), and the acting context
5951 // is irrelevant.
5952 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
5953 Expr::Classification::makeSimpleLValue(), Args,
5954 CandidateSet, SuppressUserConversions,
5955 PartialOverloading, EarlyConversions);
5956 return;
5957 }
5958 // We treat a constructor like a non-member function, since its object
5959 // argument doesn't participate in overload resolution.
5960 }
5961
5962 if (!CandidateSet.isNewCandidate(Function))
5963 return;
5964
5965 // C++ [over.match.oper]p3:
5966 // if no operand has a class type, only those non-member functions in the
5967 // lookup set that have a first parameter of type T1 or "reference to
5968 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5969 // is a right operand) a second parameter of type T2 or "reference to
5970 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5971 // candidate functions.
5972 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5973 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5974 return;
5975
5976 // C++11 [class.copy]p11: [DR1402]
5977 // A defaulted move constructor that is defined as deleted is ignored by
5978 // overload resolution.
5979 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5980 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5981 Constructor->isMoveConstructor())
5982 return;
5983
5984 // Overload resolution is always an unevaluated context.
5985 EnterExpressionEvaluationContext Unevaluated(
5986 *this, Sema::ExpressionEvaluationContext::Unevaluated);
5987
5988 // Add this candidate
5989 OverloadCandidate &Candidate =
5990 CandidateSet.addCandidate(Args.size(), EarlyConversions);
5991 Candidate.FoundDecl = FoundDecl;
5992 Candidate.Function = Function;
5993 Candidate.Viable = true;
5994 Candidate.IsSurrogate = false;
5995 Candidate.IgnoreObjectArgument = false;
5996 Candidate.ExplicitCallArguments = Args.size();
5997
5998 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
5999 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6000 Candidate.Viable = false;
6001 Candidate.FailureKind = ovl_non_default_multiversion_function;
6002 return;
6003 }
6004
6005 if (Constructor) {
6006 // C++ [class.copy]p3:
6007 // A member function template is never instantiated to perform the copy
6008 // of a class object to an object of its class type.
6009 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6010 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6011 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6012 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
6013 ClassType))) {
6014 Candidate.Viable = false;
6015 Candidate.FailureKind = ovl_fail_illegal_constructor;
6016 return;
6017 }
6018
6019 // C++ [over.match.funcs]p8: (proposed DR resolution)
6020 // A constructor inherited from class type C that has a first parameter
6021 // of type "reference to P" (including such a constructor instantiated
6022 // from a template) is excluded from the set of candidate functions when
6023 // constructing an object of type cv D if the argument list has exactly
6024 // one argument and D is reference-related to P and P is reference-related
6025 // to C.
6026 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6027 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6028 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6029 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6030 QualType C = Context.getRecordType(Constructor->getParent());
6031 QualType D = Context.getRecordType(Shadow->getParent());
6032 SourceLocation Loc = Args.front()->getExprLoc();
6033 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6034 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6035 Candidate.Viable = false;
6036 Candidate.FailureKind = ovl_fail_inhctor_slice;
6037 return;
6038 }
6039 }
6040 }
6041
6042 unsigned NumParams = Proto->getNumParams();
6043
6044 // (C++ 13.3.2p2): A candidate function having fewer than m
6045 // parameters is viable only if it has an ellipsis in its parameter
6046 // list (8.3.5).
6047 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6048 !Proto->isVariadic()) {
6049 Candidate.Viable = false;
6050 Candidate.FailureKind = ovl_fail_too_many_arguments;
6051 return;
6052 }
6053
6054 // (C++ 13.3.2p2): A candidate function having more than m parameters
6055 // is viable only if the (m+1)st parameter has a default argument
6056 // (8.3.6). For the purposes of overload resolution, the
6057 // parameter list is truncated on the right, so that there are
6058 // exactly m parameters.
6059 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6060 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6061 // Not enough arguments.
6062 Candidate.Viable = false;
6063 Candidate.FailureKind = ovl_fail_too_few_arguments;
6064 return;
6065 }
6066
6067 // (CUDA B.1): Check for invalid calls between targets.
6068 if (getLangOpts().CUDA)
6069 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6070 // Skip the check for callers that are implicit members, because in this
6071 // case we may not yet know what the member's target is; the target is
6072 // inferred for the member automatically, based on the bases and fields of
6073 // the class.
6074 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6075 Candidate.Viable = false;
6076 Candidate.FailureKind = ovl_fail_bad_target;
6077 return;
6078 }
6079
6080 // Determine the implicit conversion sequences for each of the
6081 // arguments.
6082 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6083 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6084 // We already formed a conversion sequence for this parameter during
6085 // template argument deduction.
6086 } else if (ArgIdx < NumParams) {
6087 // (C++ 13.3.2p3): for F to be a viable function, there shall
6088 // exist for each argument an implicit conversion sequence
6089 // (13.3.3.1) that converts that argument to the corresponding
6090 // parameter of F.
6091 QualType ParamType = Proto->getParamType(ArgIdx);
6092 Candidate.Conversions[ArgIdx]
6093 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6094 SuppressUserConversions,
6095 /*InOverloadResolution=*/true,
6096 /*AllowObjCWritebackConversion=*/
6097 getLangOpts().ObjCAutoRefCount,
6098 AllowExplicit);
6099 if (Candidate.Conversions[ArgIdx].isBad()) {
6100 Candidate.Viable = false;
6101 Candidate.FailureKind = ovl_fail_bad_conversion;
6102 return;
6103 }
6104 } else {
6105 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6106 // argument for which there is no corresponding parameter is
6107 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6108 Candidate.Conversions[ArgIdx].setEllipsis();
6109 }
6110 }
6111
6112 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6113 Candidate.Viable = false;
6114 Candidate.FailureKind = ovl_fail_enable_if;
6115 Candidate.DeductionFailure.Data = FailedAttr;
6116 return;
6117 }
6118
6119 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6120 Candidate.Viable = false;
6121 Candidate.FailureKind = ovl_fail_ext_disabled;
6122 return;
6123 }
6124}
6125
6126ObjCMethodDecl *
6127Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6128 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6129 if (Methods.size() <= 1)
6130 return nullptr;
6131
6132 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6133 bool Match = true;
6134 ObjCMethodDecl *Method = Methods[b];
6135 unsigned NumNamedArgs = Sel.getNumArgs();
6136 // Method might have more arguments than selector indicates. This is due
6137 // to addition of c-style arguments in method.
6138 if (Method->param_size() > NumNamedArgs)
6139 NumNamedArgs = Method->param_size();
6140 if (Args.size() < NumNamedArgs)
6141 continue;
6142
6143 for (unsigned i = 0; i < NumNamedArgs; i++) {
6144 // We can't do any type-checking on a type-dependent argument.
6145 if (Args[i]->isTypeDependent()) {
6146 Match = false;
6147 break;
6148 }
6149
6150 ParmVarDecl *param = Method->parameters()[i];
6151 Expr *argExpr = Args[i];
6152 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6152, __extension__ __PRETTY_FUNCTION__))
;
6153
6154 // Strip the unbridged-cast placeholder expression off unless it's
6155 // a consumed argument.
6156 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6157 !param->hasAttr<CFConsumedAttr>())
6158 argExpr = stripARCUnbridgedCast(argExpr);
6159
6160 // If the parameter is __unknown_anytype, move on to the next method.
6161 if (param->getType() == Context.UnknownAnyTy) {
6162 Match = false;
6163 break;
6164 }
6165
6166 ImplicitConversionSequence ConversionState
6167 = TryCopyInitialization(*this, argExpr, param->getType(),
6168 /*SuppressUserConversions*/false,
6169 /*InOverloadResolution=*/true,
6170 /*AllowObjCWritebackConversion=*/
6171 getLangOpts().ObjCAutoRefCount,
6172 /*AllowExplicit*/false);
6173 // This function looks for a reasonably-exact match, so we consider
6174 // incompatible pointer conversions to be a failure here.
6175 if (ConversionState.isBad() ||
6176 (ConversionState.isStandard() &&
6177 ConversionState.Standard.Second ==
6178 ICK_Incompatible_Pointer_Conversion)) {
6179 Match = false;
6180 break;
6181 }
6182 }
6183 // Promote additional arguments to variadic methods.
6184 if (Match && Method->isVariadic()) {
6185 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6186 if (Args[i]->isTypeDependent()) {
6187 Match = false;
6188 break;
6189 }
6190 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6191 nullptr);
6192 if (Arg.isInvalid()) {
6193 Match = false;
6194 break;
6195 }
6196 }
6197 } else {
6198 // Check for extra arguments to non-variadic methods.
6199 if (Args.size() != NumNamedArgs)
6200 Match = false;
6201 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6202 // Special case when selectors have no argument. In this case, select
6203 // one with the most general result type of 'id'.
6204 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6205 QualType ReturnT = Methods[b]->getReturnType();
6206 if (ReturnT->isObjCIdType())
6207 return Methods[b];
6208 }
6209 }
6210 }
6211
6212 if (Match)
6213 return Method;
6214 }
6215 return nullptr;
6216}
6217
6218// specific_attr_iterator iterates over enable_if attributes in reverse, and
6219// enable_if is order-sensitive. As a result, we need to reverse things
6220// sometimes. Size of 4 elements is arbitrary.
6221static SmallVector<EnableIfAttr *, 4>
6222getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6223 SmallVector<EnableIfAttr *, 4> Result;
6224 if (!Function->hasAttrs())
6225 return Result;
6226
6227 const auto &FuncAttrs = Function->getAttrs();
6228 for (Attr *Attr : FuncAttrs)
6229 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6230 Result.push_back(EnableIf);
6231
6232 std::reverse(Result.begin(), Result.end());
6233 return Result;
6234}
6235
6236static bool
6237convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6238 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6239 bool MissingImplicitThis, Expr *&ConvertedThis,
6240 SmallVectorImpl<Expr *> &ConvertedArgs) {
6241 if (ThisArg) {
6242 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6243 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6244, __extension__ __PRETTY_FUNCTION__))
6244 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6244, __extension__ __PRETTY_FUNCTION__))
;
6245 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6245, __extension__ __PRETTY_FUNCTION__))
;
6246 ExprResult R = S.PerformObjectArgumentInitialization(
6247 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6248 if (R.isInvalid())
6249 return false;
6250 ConvertedThis = R.get();
6251 } else {
6252 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6253 (void)MD;
6254 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6256, __extension__ __PRETTY_FUNCTION__))
6255 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6256, __extension__ __PRETTY_FUNCTION__))
6256 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6256, __extension__ __PRETTY_FUNCTION__))
;
6257 }
6258 ConvertedThis = nullptr;
6259 }
6260
6261 // Ignore any variadic arguments. Converting them is pointless, since the
6262 // user can't refer to them in the function condition.
6263 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6264
6265 // Convert the arguments.
6266 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6267 ExprResult R;
6268 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6269 S.Context, Function->getParamDecl(I)),
6270 SourceLocation(), Args[I]);
6271
6272 if (R.isInvalid())
6273 return false;
6274
6275 ConvertedArgs.push_back(R.get());
6276 }
6277
6278 if (Trap.hasErrorOccurred())
6279 return false;
6280
6281 // Push default arguments if needed.
6282 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6283 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6284 ParmVarDecl *P = Function->getParamDecl(i);
6285 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6286 ? P->getUninstantiatedDefaultArg()
6287 : P->getDefaultArg();
6288 // This can only happen in code completion, i.e. when PartialOverloading
6289 // is true.
6290 if (!DefArg)
6291 return false;
6292 ExprResult R =
6293 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6294 S.Context, Function->getParamDecl(i)),
6295 SourceLocation(), DefArg);
6296 if (R.isInvalid())
6297 return false;
6298 ConvertedArgs.push_back(R.get());
6299 }
6300
6301 if (Trap.hasErrorOccurred())
6302 return false;
6303 }
6304 return true;
6305}
6306
6307EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6308 bool MissingImplicitThis) {
6309 SmallVector<EnableIfAttr *, 4> EnableIfAttrs =
6310 getOrderedEnableIfAttrs(Function);
6311 if (EnableIfAttrs.empty())
6312 return nullptr;
6313
6314 SFINAETrap Trap(*this);
6315 SmallVector<Expr *, 16> ConvertedArgs;
6316 // FIXME: We should look into making enable_if late-parsed.
6317 Expr *DiscardedThis;
6318 if (!convertArgsForAvailabilityChecks(
6319 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6320 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6321 return EnableIfAttrs[0];
6322
6323 for (auto *EIA : EnableIfAttrs) {
6324 APValue Result;
6325 // FIXME: This doesn't consider value-dependent cases, because doing so is
6326 // very difficult. Ideally, we should handle them more gracefully.
6327 if (!EIA->getCond()->EvaluateWithSubstitution(
6328 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6329 return EIA;
6330
6331 if (!Result.isInt() || !Result.getInt().getBoolValue())
6332 return EIA;
6333 }
6334 return nullptr;
6335}
6336
6337template <typename CheckFn>
6338static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6339 bool ArgDependent, SourceLocation Loc,
6340 CheckFn &&IsSuccessful) {
6341 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6342 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6343 if (ArgDependent == DIA->getArgDependent())
6344 Attrs.push_back(DIA);
6345 }
6346
6347 // Common case: No diagnose_if attributes, so we can quit early.
6348 if (Attrs.empty())
6349 return false;
6350
6351 auto WarningBegin = std::stable_partition(
6352 Attrs.begin(), Attrs.end(),
6353 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6354
6355 // Note that diagnose_if attributes are late-parsed, so they appear in the
6356 // correct order (unlike enable_if attributes).
6357 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6358 IsSuccessful);
6359 if (ErrAttr != WarningBegin) {
6360 const DiagnoseIfAttr *DIA = *ErrAttr;
6361 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6362 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6363 << DIA->getParent() << DIA->getCond()->getSourceRange();
6364 return true;
6365 }
6366
6367 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6368 if (IsSuccessful(DIA)) {
6369 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6370 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6371 << DIA->getParent() << DIA->getCond()->getSourceRange();
6372 }
6373
6374 return false;
6375}
6376
6377bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6378 const Expr *ThisArg,
6379 ArrayRef<const Expr *> Args,
6380 SourceLocation Loc) {
6381 return diagnoseDiagnoseIfAttrsWith(
6382 *this, Function, /*ArgDependent=*/true, Loc,
6383 [&](const DiagnoseIfAttr *DIA) {
6384 APValue Result;
6385 // It's sane to use the same Args for any redecl of this function, since
6386 // EvaluateWithSubstitution only cares about the position of each
6387 // argument in the arg list, not the ParmVarDecl* it maps to.
6388 if (!DIA->getCond()->EvaluateWithSubstitution(
6389 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6390 return false;
6391 return Result.isInt() && Result.getInt().getBoolValue();
6392 });
6393}
6394
6395bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6396 SourceLocation Loc) {
6397 return diagnoseDiagnoseIfAttrsWith(
6398 *this, ND, /*ArgDependent=*/false, Loc,
6399 [&](const DiagnoseIfAttr *DIA) {
6400 bool Result;
6401 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6402 Result;
6403 });
6404}
6405
6406/// Add all of the function declarations in the given function set to
6407/// the overload candidate set.
6408void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6409 ArrayRef<Expr *> Args,
6410 OverloadCandidateSet &CandidateSet,
6411 TemplateArgumentListInfo *ExplicitTemplateArgs,
6412 bool SuppressUserConversions,
6413 bool PartialOverloading,
6414 bool FirstArgumentIsBase) {
6415 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6416 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6417 ArrayRef<Expr *> FunctionArgs = Args;
6418
6419 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6420 FunctionDecl *FD =
6421 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6422
6423 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6424 QualType ObjectType;
6425 Expr::Classification ObjectClassification;
6426 if (Args.size() > 0) {
6427 if (Expr *E = Args[0]) {
6428 // Use the explicit base to restrict the lookup:
6429 ObjectType = E->getType();
6430 ObjectClassification = E->Classify(Context);
6431 } // .. else there is an implicit base.
6432 FunctionArgs = Args.slice(1);
6433 }
6434 if (FunTmpl) {
6435 AddMethodTemplateCandidate(
6436 FunTmpl, F.getPair(),
6437 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6438 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6439 FunctionArgs, CandidateSet, SuppressUserConversions,
6440 PartialOverloading);
6441 } else {
6442 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6443 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6444 ObjectClassification, FunctionArgs, CandidateSet,
6445 SuppressUserConversions, PartialOverloading);
6446 }
6447 } else {
6448 // This branch handles both standalone functions and static methods.
6449
6450 // Slice the first argument (which is the base) when we access
6451 // static method as non-static.
6452 if (Args.size() > 0 &&
6453 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6454 !isa<CXXConstructorDecl>(FD)))) {
6455 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6455, __extension__ __PRETTY_FUNCTION__))
;
6456 FunctionArgs = Args.slice(1);
6457 }
6458 if (FunTmpl) {
6459 AddTemplateOverloadCandidate(
6460 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6461 CandidateSet, SuppressUserConversions, PartialOverloading);
6462 } else {
6463 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6464 SuppressUserConversions, PartialOverloading);
6465 }
6466 }
6467 }
6468}
6469
6470/// AddMethodCandidate - Adds a named decl (which is some kind of
6471/// method) as a method candidate to the given overload set.
6472void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6473 QualType ObjectType,
6474 Expr::Classification ObjectClassification,
6475 ArrayRef<Expr *> Args,
6476 OverloadCandidateSet& CandidateSet,
6477 bool SuppressUserConversions) {
6478 NamedDecl *Decl = FoundDecl.getDecl();
6479 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6480
6481 if (isa<UsingShadowDecl>(Decl))
6482 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6483
6484 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6485 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6486, __extension__ __PRETTY_FUNCTION__))
6486 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6486, __extension__ __PRETTY_FUNCTION__))
;
6487 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6488 /*ExplicitArgs*/ nullptr, ObjectType,
6489 ObjectClassification, Args, CandidateSet,
6490 SuppressUserConversions);
6491 } else {
6492 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6493 ObjectType, ObjectClassification, Args, CandidateSet,
6494 SuppressUserConversions);
6495 }
6496}
6497
6498/// AddMethodCandidate - Adds the given C++ member function to the set
6499/// of candidate functions, using the given function call arguments
6500/// and the object argument (@c Object). For example, in a call
6501/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6502/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6503/// allow user-defined conversions via constructors or conversion
6504/// operators.
6505void
6506Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6507 CXXRecordDecl *ActingContext, QualType ObjectType,
6508 Expr::Classification ObjectClassification,
6509 ArrayRef<Expr *> Args,
6510 OverloadCandidateSet &CandidateSet,
6511 bool SuppressUserConversions,
6512 bool PartialOverloading,
6513 ConversionSequenceList EarlyConversions) {
6514 const FunctionProtoType *Proto
6515 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6516 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6516, __extension__ __PRETTY_FUNCTION__))
;
6517 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6518, __extension__ __PRETTY_FUNCTION__))
6518 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6518, __extension__ __PRETTY_FUNCTION__))
;
6519
6520 if (!CandidateSet.isNewCandidate(Method))
6521 return;
6522
6523 // C++11 [class.copy]p23: [DR1402]
6524 // A defaulted move assignment operator that is defined as deleted is
6525 // ignored by overload resolution.
6526 if (Method->isDefaulted() && Method->isDeleted() &&
6527 Method->isMoveAssignmentOperator())
6528 return;
6529
6530 // Overload resolution is always an unevaluated context.
6531 EnterExpressionEvaluationContext Unevaluated(
6532 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6533
6534 // Add this candidate
6535 OverloadCandidate &Candidate =
6536 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6537 Candidate.FoundDecl = FoundDecl;
6538 Candidate.Function = Method;
6539 Candidate.IsSurrogate = false;
6540 Candidate.IgnoreObjectArgument = false;
6541 Candidate.ExplicitCallArguments = Args.size();
6542
6543 unsigned NumParams = Proto->getNumParams();
6544
6545 // (C++ 13.3.2p2): A candidate function having fewer than m
6546 // parameters is viable only if it has an ellipsis in its parameter
6547 // list (8.3.5).
6548 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6549 !Proto->isVariadic()) {
6550 Candidate.Viable = false;
6551 Candidate.FailureKind = ovl_fail_too_many_arguments;
6552 return;
6553 }
6554
6555 // (C++ 13.3.2p2): A candidate function having more than m parameters
6556 // is viable only if the (m+1)st parameter has a default argument
6557 // (8.3.6). For the purposes of overload resolution, the
6558 // parameter list is truncated on the right, so that there are
6559 // exactly m parameters.
6560 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6561 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6562 // Not enough arguments.
6563 Candidate.Viable = false;
6564 Candidate.FailureKind = ovl_fail_too_few_arguments;
6565 return;
6566 }
6567
6568 Candidate.Viable = true;
6569
6570 if (Method->isStatic() || ObjectType.isNull())
6571 // The implicit object argument is ignored.
6572 Candidate.IgnoreObjectArgument = true;
6573 else {
6574 // Determine the implicit conversion sequence for the object
6575 // parameter.
6576 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6577 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6578 Method, ActingContext);
6579 if (Candidate.Conversions[0].isBad()) {
6580 Candidate.Viable = false;
6581 Candidate.FailureKind = ovl_fail_bad_conversion;
6582 return;
6583 }
6584 }
6585
6586 // (CUDA B.1): Check for invalid calls between targets.
6587 if (getLangOpts().CUDA)
6588 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6589 if (!IsAllowedCUDACall(Caller, Method)) {
6590 Candidate.Viable = false;
6591 Candidate.FailureKind = ovl_fail_bad_target;
6592 return;
6593 }
6594
6595 // Determine the implicit conversion sequences for each of the
6596 // arguments.
6597 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6598 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6599 // We already formed a conversion sequence for this parameter during
6600 // template argument deduction.
6601 } else if (ArgIdx < NumParams) {
6602 // (C++ 13.3.2p3): for F to be a viable function, there shall
6603 // exist for each argument an implicit conversion sequence
6604 // (13.3.3.1) that converts that argument to the corresponding
6605 // parameter of F.
6606 QualType ParamType = Proto->getParamType(ArgIdx);
6607 Candidate.Conversions[ArgIdx + 1]
6608 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6609 SuppressUserConversions,
6610 /*InOverloadResolution=*/true,
6611 /*AllowObjCWritebackConversion=*/
6612 getLangOpts().ObjCAutoRefCount);
6613 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6614 Candidate.Viable = false;
6615 Candidate.FailureKind = ovl_fail_bad_conversion;
6616 return;
6617 }
6618 } else {
6619 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6620 // argument for which there is no corresponding parameter is
6621 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6622 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6623 }
6624 }
6625
6626 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6627 Candidate.Viable = false;
6628 Candidate.FailureKind = ovl_fail_enable_if;
6629 Candidate.DeductionFailure.Data = FailedAttr;
6630 return;
6631 }
6632
6633 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6634 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6635 Candidate.Viable = false;
6636 Candidate.FailureKind = ovl_non_default_multiversion_function;
6637 }
6638}
6639
6640/// Add a C++ member function template as a candidate to the candidate
6641/// set, using template argument deduction to produce an appropriate member
6642/// function template specialization.
6643void
6644Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6645 DeclAccessPair FoundDecl,
6646 CXXRecordDecl *ActingContext,
6647 TemplateArgumentListInfo *ExplicitTemplateArgs,
6648 QualType ObjectType,
6649 Expr::Classification ObjectClassification,
6650 ArrayRef<Expr *> Args,
6651 OverloadCandidateSet& CandidateSet,
6652 bool SuppressUserConversions,
6653 bool PartialOverloading) {
6654 if (!CandidateSet.isNewCandidate(MethodTmpl))
6655 return;
6656
6657 // C++ [over.match.funcs]p7:
6658 // In each case where a candidate is a function template, candidate
6659 // function template specializations are generated using template argument
6660 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6661 // candidate functions in the usual way.113) A given name can refer to one
6662 // or more function templates and also to a set of overloaded non-template
6663 // functions. In such a case, the candidate functions generated from each
6664 // function template are combined with the set of non-template candidate
6665 // functions.
6666 TemplateDeductionInfo Info(CandidateSet.getLocation());
6667 FunctionDecl *Specialization = nullptr;
6668 ConversionSequenceList Conversions;
6669 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6670 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6671 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6672 return CheckNonDependentConversions(
6673 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6674 SuppressUserConversions, ActingContext, ObjectType,
6675 ObjectClassification);
6676 })) {
6677 OverloadCandidate &Candidate =
6678 CandidateSet.addCandidate(Conversions.size(), Conversions);
6679 Candidate.FoundDecl = FoundDecl;
6680 Candidate.Function = MethodTmpl->getTemplatedDecl();
6681 Candidate.Viable = false;
6682 Candidate.IsSurrogate = false;
6683 Candidate.IgnoreObjectArgument =
6684 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6685 ObjectType.isNull();
6686 Candidate.ExplicitCallArguments = Args.size();
6687 if (Result == TDK_NonDependentConversionFailure)
6688 Candidate.FailureKind = ovl_fail_bad_conversion;
6689 else {
6690 Candidate.FailureKind = ovl_fail_bad_deduction;
6691 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6692 Info);
6693 }
6694 return;
6695 }
6696
6697 // Add the function template specialization produced by template argument
6698 // deduction as a candidate.
6699 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6699, __extension__ __PRETTY_FUNCTION__))
;
6700 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6701, __extension__ __PRETTY_FUNCTION__))
6701 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6701, __extension__ __PRETTY_FUNCTION__))
;
6702 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6703 ActingContext, ObjectType, ObjectClassification, Args,
6704 CandidateSet, SuppressUserConversions, PartialOverloading,
6705 Conversions);
6706}
6707
6708/// Add a C++ function template specialization as a candidate
6709/// in the candidate set, using template argument deduction to produce
6710/// an appropriate function template specialization.
6711void
6712Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6713 DeclAccessPair FoundDecl,
6714 TemplateArgumentListInfo *ExplicitTemplateArgs,
6715 ArrayRef<Expr *> Args,
6716 OverloadCandidateSet& CandidateSet,
6717 bool SuppressUserConversions,
6718 bool PartialOverloading) {
6719 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6720 return;
6721
6722 // C++ [over.match.funcs]p7:
6723 // In each case where a candidate is a function template, candidate
6724 // function template specializations are generated using template argument
6725 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6726 // candidate functions in the usual way.113) A given name can refer to one
6727 // or more function templates and also to a set of overloaded non-template
6728 // functions. In such a case, the candidate functions generated from each
6729 // function template are combined with the set of non-template candidate
6730 // functions.
6731 TemplateDeductionInfo Info(CandidateSet.getLocation());
6732 FunctionDecl *Specialization = nullptr;
6733 ConversionSequenceList Conversions;
6734 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6735 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6736 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6737 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6738 Args, CandidateSet, Conversions,
6739 SuppressUserConversions);
6740 })) {
6741 OverloadCandidate &Candidate =
6742 CandidateSet.addCandidate(Conversions.size(), Conversions);
6743 Candidate.FoundDecl = FoundDecl;
6744 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6745 Candidate.Viable = false;
6746 Candidate.IsSurrogate = false;
6747 // Ignore the object argument if there is one, since we don't have an object
6748 // type.
6749 Candidate.IgnoreObjectArgument =
6750 isa<CXXMethodDecl>(Candidate.Function) &&
6751 !isa<CXXConstructorDecl>(Candidate.Function);
6752 Candidate.ExplicitCallArguments = Args.size();
6753 if (Result == TDK_NonDependentConversionFailure)
6754 Candidate.FailureKind = ovl_fail_bad_conversion;
6755 else {
6756 Candidate.FailureKind = ovl_fail_bad_deduction;
6757 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6758 Info);
6759 }
6760 return;
6761 }
6762
6763 // Add the function template specialization produced by template argument
6764 // deduction as a candidate.
6765 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6765, __extension__ __PRETTY_FUNCTION__))
;
6766 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6767 SuppressUserConversions, PartialOverloading,
6768 /*AllowExplicit*/false, Conversions);
6769}
6770
6771/// Check that implicit conversion sequences can be formed for each argument
6772/// whose corresponding parameter has a non-dependent type, per DR1391's
6773/// [temp.deduct.call]p10.
6774bool Sema::CheckNonDependentConversions(
6775 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6776 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6777 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6778 CXXRecordDecl *ActingContext, QualType ObjectType,
6779 Expr::Classification ObjectClassification) {
6780 // FIXME: The cases in which we allow explicit conversions for constructor
6781 // arguments never consider calling a constructor template. It's not clear
6782 // that is correct.
6783 const bool AllowExplicit = false;
6784
6785 auto *FD = FunctionTemplate->getTemplatedDecl();
6786 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6787 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6788 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6789
6790 Conversions =
6791 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6792
6793 // Overload resolution is always an unevaluated context.
6794 EnterExpressionEvaluationContext Unevaluated(
6795 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6796
6797 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6798 // require that, but this check should never result in a hard error, and
6799 // overload resolution is permitted to sidestep instantiations.
6800 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6801 !ObjectType.isNull()) {
6802 Conversions[0] = TryObjectArgumentInitialization(
6803 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6804 Method, ActingContext);
6805 if (Conversions[0].isBad())
6806 return true;
6807 }
6808
6809 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6810 ++I) {
6811 QualType ParamType = ParamTypes[I];
6812 if (!ParamType->isDependentType()) {
6813 Conversions[ThisConversions + I]
6814 = TryCopyInitialization(*this, Args[I], ParamType,
6815 SuppressUserConversions,
6816 /*InOverloadResolution=*/true,
6817 /*AllowObjCWritebackConversion=*/
6818 getLangOpts().ObjCAutoRefCount,
6819 AllowExplicit);
6820 if (Conversions[ThisConversions + I].isBad())
6821 return true;
6822 }
6823 }
6824
6825 return false;
6826}
6827
6828/// Determine whether this is an allowable conversion from the result
6829/// of an explicit conversion operator to the expected type, per C++
6830/// [over.match.conv]p1 and [over.match.ref]p1.
6831///
6832/// \param ConvType The return type of the conversion function.
6833///
6834/// \param ToType The type we are converting to.
6835///
6836/// \param AllowObjCPointerConversion Allow a conversion from one
6837/// Objective-C pointer to another.
6838///
6839/// \returns true if the conversion is allowable, false otherwise.
6840static bool isAllowableExplicitConversion(Sema &S,
6841 QualType ConvType, QualType ToType,
6842 bool AllowObjCPointerConversion) {
6843 QualType ToNonRefType = ToType.getNonReferenceType();
6844
6845 // Easy case: the types are the same.
6846 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6847 return true;
6848
6849 // Allow qualification conversions.
6850 bool ObjCLifetimeConversion;
6851 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6852 ObjCLifetimeConversion))
6853 return true;
6854
6855 // If we're not allowed to consider Objective-C pointer conversions,
6856 // we're done.
6857 if (!AllowObjCPointerConversion)
6858 return false;
6859
6860 // Is this an Objective-C pointer conversion?
6861 bool IncompatibleObjC = false;
6862 QualType ConvertedType;
6863 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6864 IncompatibleObjC);
6865}
6866
6867/// AddConversionCandidate - Add a C++ conversion function as a
6868/// candidate in the candidate set (C++ [over.match.conv],
6869/// C++ [over.match.copy]). From is the expression we're converting from,
6870/// and ToType is the type that we're eventually trying to convert to
6871/// (which may or may not be the same type as the type that the
6872/// conversion function produces).
6873void
6874Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6875 DeclAccessPair FoundDecl,
6876 CXXRecordDecl *ActingContext,
6877 Expr *From, QualType ToType,
6878 OverloadCandidateSet& CandidateSet,
6879 bool AllowObjCConversionOnExplicit,
6880 bool AllowResultConversion) {
6881 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6882, __extension__ __PRETTY_FUNCTION__))
6882 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6882, __extension__ __PRETTY_FUNCTION__))
;
6883 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6884 if (!CandidateSet.isNewCandidate(Conversion))
6885 return;
6886
6887 // If the conversion function has an undeduced return type, trigger its
6888 // deduction now.
6889 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6890 if (DeduceReturnType(Conversion, From->getExprLoc()))
6891 return;
6892 ConvType = Conversion->getConversionType().getNonReferenceType();
6893 }
6894
6895 // If we don't allow any conversion of the result type, ignore conversion
6896 // functions that don't convert to exactly (possibly cv-qualified) T.
6897 if (!AllowResultConversion &&
6898 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6899 return;
6900
6901 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6902 // operator is only a candidate if its return type is the target type or
6903 // can be converted to the target type with a qualification conversion.
6904 if (Conversion->isExplicit() &&
6905 !isAllowableExplicitConversion(*this, ConvType, ToType,
6906 AllowObjCConversionOnExplicit))
6907 return;
6908
6909 // Overload resolution is always an unevaluated context.
6910 EnterExpressionEvaluationContext Unevaluated(
6911 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6912
6913 // Add this candidate
6914 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6915 Candidate.FoundDecl = FoundDecl;
6916 Candidate.Function = Conversion;
6917 Candidate.IsSurrogate = false;
6918 Candidate.IgnoreObjectArgument = false;
6919 Candidate.FinalConversion.setAsIdentityConversion();
6920 Candidate.FinalConversion.setFromType(ConvType);
6921 Candidate.FinalConversion.setAllToTypes(ToType);
6922 Candidate.Viable = true;
6923 Candidate.ExplicitCallArguments = 1;
6924
6925 // C++ [over.match.funcs]p4:
6926 // For conversion functions, the function is considered to be a member of
6927 // the class of the implicit implied object argument for the purpose of
6928 // defining the type of the implicit object parameter.
6929 //
6930 // Determine the implicit conversion sequence for the implicit
6931 // object parameter.
6932 QualType ImplicitParamType = From->getType();
6933 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6934 ImplicitParamType = FromPtrType->getPointeeType();
6935 CXXRecordDecl *ConversionContext
6936 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6937
6938 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6939 *this, CandidateSet.getLocation(), From->getType(),
6940 From->Classify(Context), Conversion, ConversionContext);
6941
6942 if (Candidate.Conversions[0].isBad()) {
6943 Candidate.Viable = false;
6944 Candidate.FailureKind = ovl_fail_bad_conversion;
6945 return;
6946 }
6947
6948 // We won't go through a user-defined type conversion function to convert a
6949 // derived to base as such conversions are given Conversion Rank. They only
6950 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6951 QualType FromCanon
6952 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6953 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6954 if (FromCanon == ToCanon ||
6955 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6956 Candidate.Viable = false;
6957 Candidate.FailureKind = ovl_fail_trivial_conversion;
6958 return;
6959 }
6960
6961 // To determine what the conversion from the result of calling the
6962 // conversion function to the type we're eventually trying to
6963 // convert to (ToType), we need to synthesize a call to the
6964 // conversion function and attempt copy initialization from it. This
6965 // makes sure that we get the right semantics with respect to
6966 // lvalues/rvalues and the type. Fortunately, we can allocate this
6967 // call on the stack and we don't need its arguments to be
6968 // well-formed.
6969 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6970 VK_LValue, From->getLocStart());
6971 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6972 Context.getPointerType(Conversion->getType()),
6973 CK_FunctionToPointerDecay,
6974 &ConversionRef, VK_RValue);
6975
6976 QualType ConversionType = Conversion->getConversionType();
6977 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6978 Candidate.Viable = false;
6979 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6980 return;
6981 }
6982
6983 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6984
6985 // Note that it is safe to allocate CallExpr on the stack here because
6986 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6987 // allocator).
6988 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6989 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6990 From->getLocStart());
6991 ImplicitConversionSequence ICS =
6992 TryCopyInitialization(*this, &Call, ToType,
6993 /*SuppressUserConversions=*/true,
6994 /*InOverloadResolution=*/false,
6995 /*AllowObjCWritebackConversion=*/false);
6996
6997 switch (ICS.getKind()) {
6998 case ImplicitConversionSequence::StandardConversion:
6999 Candidate.FinalConversion = ICS.Standard;
7000
7001 // C++ [over.ics.user]p3:
7002 // If the user-defined conversion is specified by a specialization of a
7003 // conversion function template, the second standard conversion sequence
7004 // shall have exact match rank.
7005 if (Conversion->getPrimaryTemplate() &&
7006 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7007 Candidate.Viable = false;
7008 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7009 return;
7010 }
7011
7012 // C++0x [dcl.init.ref]p5:
7013 // In the second case, if the reference is an rvalue reference and
7014 // the second standard conversion sequence of the user-defined
7015 // conversion sequence includes an lvalue-to-rvalue conversion, the
7016 // program is ill-formed.
7017 if (ToType->isRValueReferenceType() &&
7018 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7019 Candidate.Viable = false;
7020 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7021 return;
7022 }
7023 break;
7024
7025 case ImplicitConversionSequence::BadConversion:
7026 Candidate.Viable = false;
7027 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7028 return;
7029
7030 default:
7031 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7032)
7032 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7032)
;
7033 }
7034
7035 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7036 Candidate.Viable = false;
7037 Candidate.FailureKind = ovl_fail_enable_if;
7038 Candidate.DeductionFailure.Data = FailedAttr;
7039 return;
7040 }
7041
7042 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7043 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7044 Candidate.Viable = false;
7045 Candidate.FailureKind = ovl_non_default_multiversion_function;
7046 }
7047}
7048
7049/// Adds a conversion function template specialization
7050/// candidate to the overload set, using template argument deduction
7051/// to deduce the template arguments of the conversion function
7052/// template from the type that we are converting to (C++
7053/// [temp.deduct.conv]).
7054void
7055Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
7056 DeclAccessPair FoundDecl,
7057 CXXRecordDecl *ActingDC,
7058 Expr *From, QualType ToType,
7059 OverloadCandidateSet &CandidateSet,
7060 bool AllowObjCConversionOnExplicit,
7061 bool AllowResultConversion) {
7062 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7063, __extension__ __PRETTY_FUNCTION__))
7063 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7063, __extension__ __PRETTY_FUNCTION__))
;
7064
7065 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7066 return;
7067
7068 TemplateDeductionInfo Info(CandidateSet.getLocation());
7069 CXXConversionDecl *Specialization = nullptr;
7070 if (TemplateDeductionResult Result
7071 = DeduceTemplateArguments(FunctionTemplate, ToType,
7072 Specialization, Info)) {
7073 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7074 Candidate.FoundDecl = FoundDecl;
7075 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7076 Candidate.Viable = false;
7077 Candidate.FailureKind = ovl_fail_bad_deduction;
7078 Candidate.IsSurrogate = false;
7079 Candidate.IgnoreObjectArgument = false;
7080 Candidate.ExplicitCallArguments = 1;
7081 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7082 Info);
7083 return;
7084 }
7085
7086 // Add the conversion function template specialization produced by
7087 // template argument deduction as a candidate.
7088 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7088, __extension__ __PRETTY_FUNCTION__))
;
7089 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7090 CandidateSet, AllowObjCConversionOnExplicit,
7091 AllowResultConversion);
7092}
7093
7094/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7095/// converts the given @c Object to a function pointer via the
7096/// conversion function @c Conversion, and then attempts to call it
7097/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7098/// the type of function that we'll eventually be calling.
7099void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7100 DeclAccessPair FoundDecl,
7101 CXXRecordDecl *ActingContext,
7102 const FunctionProtoType *Proto,
7103 Expr *Object,
7104 ArrayRef<Expr *> Args,
7105 OverloadCandidateSet& CandidateSet) {
7106 if (!CandidateSet.isNewCandidate(Conversion))
7107 return;
7108
7109 // Overload resolution is always an unevaluated context.
7110 EnterExpressionEvaluationContext Unevaluated(
7111 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7112
7113 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7114 Candidate.FoundDecl = FoundDecl;
7115 Candidate.Function = nullptr;
7116 Candidate.Surrogate = Conversion;
7117 Candidate.Viable = true;
7118 Candidate.IsSurrogate = true;
7119 Candidate.IgnoreObjectArgument = false;
7120 Candidate.ExplicitCallArguments = Args.size();
7121
7122 // Determine the implicit conversion sequence for the implicit
7123 // object parameter.
7124 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7125 *this, CandidateSet.getLocation(), Object->getType(),
7126 Object->Classify(Context), Conversion, ActingContext);
7127 if (ObjectInit.isBad()) {
7128 Candidate.Viable = false;
7129 Candidate.FailureKind = ovl_fail_bad_conversion;
7130 Candidate.Conversions[0] = ObjectInit;
7131 return;
7132 }
7133
7134 // The first conversion is actually a user-defined conversion whose
7135 // first conversion is ObjectInit's standard conversion (which is
7136 // effectively a reference binding). Record it as such.
7137 Candidate.Conversions[0].setUserDefined();
7138 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7139 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7140 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7141 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7142 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7143 Candidate.Conversions[0].UserDefined.After
7144 = Candidate.Conversions[0].UserDefined.Before;
7145 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7146
7147 // Find the
7148 unsigned NumParams = Proto->getNumParams();
7149
7150 // (C++ 13.3.2p2): A candidate function having fewer than m
7151 // parameters is viable only if it has an ellipsis in its parameter
7152 // list (8.3.5).
7153 if (Args.size() > NumParams && !Proto->isVariadic()) {
7154 Candidate.Viable = false;
7155 Candidate.FailureKind = ovl_fail_too_many_arguments;
7156 return;
7157 }
7158
7159 // Function types don't have any default arguments, so just check if
7160 // we have enough arguments.
7161 if (Args.size() < NumParams) {
7162 // Not enough arguments.
7163 Candidate.Viable = false;
7164 Candidate.FailureKind = ovl_fail_too_few_arguments;
7165 return;
7166 }
7167
7168 // Determine the implicit conversion sequences for each of the
7169 // arguments.
7170 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7171 if (ArgIdx < NumParams) {
7172 // (C++ 13.3.2p3): for F to be a viable function, there shall
7173 // exist for each argument an implicit conversion sequence
7174 // (13.3.3.1) that converts that argument to the corresponding
7175 // parameter of F.
7176 QualType ParamType = Proto->getParamType(ArgIdx);
7177 Candidate.Conversions[ArgIdx + 1]
7178 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7179 /*SuppressUserConversions=*/false,
7180 /*InOverloadResolution=*/false,
7181 /*AllowObjCWritebackConversion=*/
7182 getLangOpts().ObjCAutoRefCount);
7183 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7184 Candidate.Viable = false;
7185 Candidate.FailureKind = ovl_fail_bad_conversion;
7186 return;
7187 }
7188 } else {
7189 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7190 // argument for which there is no corresponding parameter is
7191 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7192 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7193 }
7194 }
7195
7196 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7197 Candidate.Viable = false;
7198 Candidate.FailureKind = ovl_fail_enable_if;
7199 Candidate.DeductionFailure.Data = FailedAttr;
7200 return;
7201 }
7202}
7203
7204/// Add overload candidates for overloaded operators that are
7205/// member functions.
7206///
7207/// Add the overloaded operator candidates that are member functions
7208/// for the operator Op that was used in an operator expression such
7209/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7210/// CandidateSet will store the added overload candidates. (C++
7211/// [over.match.oper]).
7212void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7213 SourceLocation OpLoc,
7214 ArrayRef<Expr *> Args,
7215 OverloadCandidateSet& CandidateSet,
7216 SourceRange OpRange) {
7217 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7218
7219 // C++ [over.match.oper]p3:
7220 // For a unary operator @ with an operand of a type whose
7221 // cv-unqualified version is T1, and for a binary operator @ with
7222 // a left operand of a type whose cv-unqualified version is T1 and
7223 // a right operand of a type whose cv-unqualified version is T2,
7224 // three sets of candidate functions, designated member
7225 // candidates, non-member candidates and built-in candidates, are
7226 // constructed as follows:
7227 QualType T1 = Args[0]->getType();
7228
7229 // -- If T1 is a complete class type or a class currently being
7230 // defined, the set of member candidates is the result of the
7231 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7232 // the set of member candidates is empty.
7233 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7234 // Complete the type if it can be completed.
7235 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7236 return;
7237 // If the type is neither complete nor being defined, bail out now.
7238 if (!T1Rec->getDecl()->getDefinition())
7239 return;
7240
7241 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7242 LookupQualifiedName(Operators, T1Rec->getDecl());
7243 Operators.suppressDiagnostics();
7244
7245 for (LookupResult::iterator Oper = Operators.begin(),
7246 OperEnd = Operators.end();
7247 Oper != OperEnd;
7248 ++Oper)
7249 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7250 Args[0]->Classify(Context), Args.slice(1),
7251 CandidateSet, /*SuppressUserConversions=*/false);
7252 }
7253}
7254
7255/// AddBuiltinCandidate - Add a candidate for a built-in
7256/// operator. ResultTy and ParamTys are the result and parameter types
7257/// of the built-in candidate, respectively. Args and NumArgs are the
7258/// arguments being passed to the candidate. IsAssignmentOperator
7259/// should be true when this built-in candidate is an assignment
7260/// operator. NumContextualBoolArguments is the number of arguments
7261/// (at the beginning of the argument list) that will be contextually
7262/// converted to bool.
7263void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7264 OverloadCandidateSet& CandidateSet,
7265 bool IsAssignmentOperator,
7266 unsigned NumContextualBoolArguments) {
7267 // Overload resolution is always an unevaluated context.
7268 EnterExpressionEvaluationContext Unevaluated(
7269 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7270
7271 // Add this candidate
7272 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7273 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7274 Candidate.Function = nullptr;
7275 Candidate.IsSurrogate = false;
7276 Candidate.IgnoreObjectArgument = false;
7277 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7278
7279 // Determine the implicit conversion sequences for each of the
7280 // arguments.
7281 Candidate.Viable = true;
7282 Candidate.ExplicitCallArguments = Args.size();
7283 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7284 // C++ [over.match.oper]p4:
7285 // For the built-in assignment operators, conversions of the
7286 // left operand are restricted as follows:
7287 // -- no temporaries are introduced to hold the left operand, and
7288 // -- no user-defined conversions are applied to the left
7289 // operand to achieve a type match with the left-most
7290 // parameter of a built-in candidate.
7291 //
7292 // We block these conversions by turning off user-defined
7293 // conversions, since that is the only way that initialization of
7294 // a reference to a non-class type can occur from something that
7295 // is not of the same type.
7296 if (ArgIdx < NumContextualBoolArguments) {
7297 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7298, __extension__ __PRETTY_FUNCTION__))
7298 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7298, __extension__ __PRETTY_FUNCTION__))
;
7299 Candidate.Conversions[ArgIdx]
7300 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7301 } else {
7302 Candidate.Conversions[ArgIdx]
7303 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7304 ArgIdx == 0 && IsAssignmentOperator,
7305 /*InOverloadResolution=*/false,
7306 /*AllowObjCWritebackConversion=*/
7307 getLangOpts().ObjCAutoRefCount);
7308 }
7309 if (Candidate.Conversions[ArgIdx].isBad()) {
7310 Candidate.Viable = false;
7311 Candidate.FailureKind = ovl_fail_bad_conversion;
7312 break;
7313 }
7314 }
7315}
7316
7317namespace {
7318
7319/// BuiltinCandidateTypeSet - A set of types that will be used for the
7320/// candidate operator functions for built-in operators (C++
7321/// [over.built]). The types are separated into pointer types and
7322/// enumeration types.
7323class BuiltinCandidateTypeSet {
7324 /// TypeSet - A set of types.
7325 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7326 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7327
7328 /// PointerTypes - The set of pointer types that will be used in the
7329 /// built-in candidates.
7330 TypeSet PointerTypes;
7331
7332 /// MemberPointerTypes - The set of member pointer types that will be
7333 /// used in the built-in candidates.
7334 TypeSet MemberPointerTypes;
7335
7336 /// EnumerationTypes - The set of enumeration types that will be
7337 /// used in the built-in candidates.
7338 TypeSet EnumerationTypes;
7339
7340 /// The set of vector types that will be used in the built-in
7341 /// candidates.
7342 TypeSet VectorTypes;
7343
7344 /// A flag indicating non-record types are viable candidates
7345 bool HasNonRecordTypes;
7346
7347 /// A flag indicating whether either arithmetic or enumeration types
7348 /// were present in the candidate set.
7349 bool HasArithmeticOrEnumeralTypes;
7350
7351 /// A flag indicating whether the nullptr type was present in the
7352 /// candidate set.
7353 bool HasNullPtrType;
7354
7355 /// Sema - The semantic analysis instance where we are building the
7356 /// candidate type set.
7357 Sema &SemaRef;
7358
7359 /// Context - The AST context in which we will build the type sets.
7360 ASTContext &Context;
7361
7362 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7363 const Qualifiers &VisibleQuals);
7364 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7365
7366public:
7367 /// iterator - Iterates through the types that are part of the set.
7368 typedef TypeSet::iterator iterator;
7369
7370 BuiltinCandidateTypeSet(Sema &SemaRef)
7371 : HasNonRecordTypes(false),
7372 HasArithmeticOrEnumeralTypes(false),
7373 HasNullPtrType(false),
7374 SemaRef(SemaRef),
7375 Context(SemaRef.Context) { }
7376
7377 void AddTypesConvertedFrom(QualType Ty,
7378 SourceLocation Loc,
7379 bool AllowUserConversions,
7380 bool AllowExplicitConversions,
7381 const Qualifiers &VisibleTypeConversionsQuals);
7382
7383 /// pointer_begin - First pointer type found;
7384 iterator pointer_begin() { return PointerTypes.begin(); }
7385
7386 /// pointer_end - Past the last pointer type found;
7387 iterator pointer_end() { return PointerTypes.end(); }
7388
7389 /// member_pointer_begin - First member pointer type found;
7390 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7391
7392 /// member_pointer_end - Past the last member pointer type found;
7393 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7394
7395 /// enumeration_begin - First enumeration type found;
7396 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7397
7398 /// enumeration_end - Past the last enumeration type found;
7399 iterator enumeration_end() { return EnumerationTypes.end(); }
7400
7401 iterator vector_begin() { return VectorTypes.begin(); }
7402 iterator vector_end() { return VectorTypes.end(); }
7403
7404 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7405 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7406 bool hasNullPtrType() const { return HasNullPtrType; }
7407};
7408
7409} // end anonymous namespace
7410
7411/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7412/// the set of pointer types along with any more-qualified variants of
7413/// that type. For example, if @p Ty is "int const *", this routine
7414/// will add "int const *", "int const volatile *", "int const
7415/// restrict *", and "int const volatile restrict *" to the set of
7416/// pointer types. Returns true if the add of @p Ty itself succeeded,
7417/// false otherwise.
7418///
7419/// FIXME: what to do about extended qualifiers?
7420bool
7421BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7422 const Qualifiers &VisibleQuals) {
7423
7424 // Insert this type.
7425 if (!PointerTypes.insert(Ty))
7426 return false;
7427
7428 QualType PointeeTy;
7429 const PointerType *PointerTy = Ty->getAs<PointerType>();
7430 bool buildObjCPtr = false;
7431 if (!PointerTy) {
7432 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7433 PointeeTy = PTy->getPointeeType();
7434 buildObjCPtr = true;
7435 } else {
7436 PointeeTy = PointerTy->getPointeeType();
7437 }
7438
7439 // Don't add qualified variants of arrays. For one, they're not allowed
7440 // (the qualifier would sink to the element type), and for another, the
7441 // only overload situation where it matters is subscript or pointer +- int,
7442 // and those shouldn't have qualifier variants anyway.
7443 if (PointeeTy->isArrayType())
7444 return true;
7445
7446 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7447 bool hasVolatile = VisibleQuals.hasVolatile();
7448 bool hasRestrict = VisibleQuals.hasRestrict();
7449
7450 // Iterate through all strict supersets of BaseCVR.
7451 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7452 if ((CVR | BaseCVR) != CVR) continue;
7453 // Skip over volatile if no volatile found anywhere in the types.
7454 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7455
7456 // Skip over restrict if no restrict found anywhere in the types, or if
7457 // the type cannot be restrict-qualified.
7458 if ((CVR & Qualifiers::Restrict) &&
7459 (!hasRestrict ||
7460 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7461 continue;
7462
7463 // Build qualified pointee type.
7464 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7465
7466 // Build qualified pointer type.
7467 QualType QPointerTy;
7468 if (!buildObjCPtr)
7469 QPointerTy = Context.getPointerType(QPointeeTy);
7470 else
7471 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7472
7473 // Insert qualified pointer type.
7474 PointerTypes.insert(QPointerTy);
7475 }
7476
7477 return true;
7478}
7479
7480/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7481/// to the set of pointer types along with any more-qualified variants of
7482/// that type. For example, if @p Ty is "int const *", this routine
7483/// will add "int const *", "int const volatile *", "int const
7484/// restrict *", and "int const volatile restrict *" to the set of
7485/// pointer types. Returns true if the add of @p Ty itself succeeded,
7486/// false otherwise.
7487///
7488/// FIXME: what to do about extended qualifiers?
7489bool
7490BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7491 QualType Ty) {
7492 // Insert this type.
7493 if (!MemberPointerTypes.insert(Ty))
7494 return false;
7495
7496 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7497 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7497, __extension__ __PRETTY_FUNCTION__))
;
7498
7499 QualType PointeeTy = PointerTy->getPointeeType();
7500 // Don't add qualified variants of arrays. For one, they're not allowed
7501 // (the qualifier would sink to the element type), and for another, the
7502 // only overload situation where it matters is subscript or pointer +- int,
7503 // and those shouldn't have qualifier variants anyway.
7504 if (PointeeTy->isArrayType())
7505 return true;
7506 const Type *ClassTy = PointerTy->getClass();
7507
7508 // Iterate through all strict supersets of the pointee type's CVR
7509 // qualifiers.
7510 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7511 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7512 if ((CVR | BaseCVR) != CVR) continue;
7513
7514 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7515 MemberPointerTypes.insert(
7516 Context.getMemberPointerType(QPointeeTy, ClassTy));
7517 }
7518
7519 return true;
7520}
7521
7522/// AddTypesConvertedFrom - Add each of the types to which the type @p
7523/// Ty can be implicit converted to the given set of @p Types. We're
7524/// primarily interested in pointer types and enumeration types. We also
7525/// take member pointer types, for the conditional operator.
7526/// AllowUserConversions is true if we should look at the conversion
7527/// functions of a class type, and AllowExplicitConversions if we
7528/// should also include the explicit conversion functions of a class
7529/// type.
7530void
7531BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7532 SourceLocation Loc,
7533 bool AllowUserConversions,
7534 bool AllowExplicitConversions,
7535 const Qualifiers &VisibleQuals) {
7536 // Only deal with canonical types.
7537 Ty = Context.getCanonicalType(Ty);
7538
7539 // Look through reference types; they aren't part of the type of an
7540 // expression for the purposes of conversions.
7541 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7542 Ty = RefTy->getPointeeType();
7543
7544 // If we're dealing with an array type, decay to the pointer.
7545 if (Ty->isArrayType())
7546 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7547
7548 // Otherwise, we don't care about qualifiers on the type.
7549 Ty = Ty.getLocalUnqualifiedType();
7550
7551 // Flag if we ever add a non-record type.
7552 const RecordType *TyRec = Ty->getAs<RecordType>();
7553 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7554
7555 // Flag if we encounter an arithmetic type.
7556 HasArithmeticOrEnumeralTypes =
7557 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7558
7559 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7560 PointerTypes.insert(Ty);
7561 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7562 // Insert our type, and its more-qualified variants, into the set
7563 // of types.
7564 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7565 return;
7566 } else if (Ty->isMemberPointerType()) {
7567 // Member pointers are far easier, since the pointee can't be converted.
7568 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7569 return;
7570 } else if (Ty->isEnumeralType()) {
7571 HasArithmeticOrEnumeralTypes = true;
7572 EnumerationTypes.insert(Ty);
7573 } else if (Ty->isVectorType()) {
7574 // We treat vector types as arithmetic types in many contexts as an
7575 // extension.
7576 HasArithmeticOrEnumeralTypes = true;
7577 VectorTypes.insert(Ty);
7578 } else if (Ty->isNullPtrType()) {
7579 HasNullPtrType = true;
7580 } else if (AllowUserConversions && TyRec) {
7581 // No conversion functions in incomplete types.
7582 if (!SemaRef.isCompleteType(Loc, Ty))
7583 return;
7584
7585 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7586 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7587 if (isa<UsingShadowDecl>(D))
7588 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7589
7590 // Skip conversion function templates; they don't tell us anything
7591 // about which builtin types we can convert to.
7592 if (isa<FunctionTemplateDecl>(D))
7593 continue;
7594
7595 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7596 if (AllowExplicitConversions || !Conv->isExplicit()) {
7597 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7598 VisibleQuals);
7599 }
7600 }
7601 }
7602}
7603
7604/// Helper function for AddBuiltinOperatorCandidates() that adds
7605/// the volatile- and non-volatile-qualified assignment operators for the
7606/// given type to the candidate set.
7607static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7608 QualType T,
7609 ArrayRef<Expr *> Args,
7610 OverloadCandidateSet &CandidateSet) {
7611 QualType ParamTypes[2];
7612
7613 // T& operator=(T&, T)
7614 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7615 ParamTypes[1] = T;
7616 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7617 /*IsAssignmentOperator=*/true);
7618
7619 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7620 // volatile T& operator=(volatile T&, T)
7621 ParamTypes[0]
7622 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7623 ParamTypes[1] = T;
7624 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7625 /*IsAssignmentOperator=*/true);
7626 }
7627}
7628
7629/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7630/// if any, found in visible type conversion functions found in ArgExpr's type.
7631static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7632 Qualifiers VRQuals;
7633 const RecordType *TyRec;
7634 if (const MemberPointerType *RHSMPType =
7635 ArgExpr->getType()->getAs<MemberPointerType>())
7636 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7637 else
7638 TyRec = ArgExpr->getType()->getAs<RecordType>();
7639 if (!TyRec) {
7640 // Just to be safe, assume the worst case.
7641 VRQuals.addVolatile();
7642 VRQuals.addRestrict();
7643 return VRQuals;
7644 }
7645
7646 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7647 if (!ClassDecl->hasDefinition())
7648 return VRQuals;
7649
7650 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7651 if (isa<UsingShadowDecl>(D))
7652 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7653 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7654 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7655 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7656 CanTy = ResTypeRef->getPointeeType();
7657 // Need to go down the pointer/mempointer chain and add qualifiers
7658 // as see them.
7659 bool done = false;
7660 while (!done) {
7661 if (CanTy.isRestrictQualified())
7662 VRQuals.addRestrict();
7663 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7664 CanTy = ResTypePtr->getPointeeType();
7665 else if (const MemberPointerType *ResTypeMPtr =
7666 CanTy->getAs<MemberPointerType>())
7667 CanTy = ResTypeMPtr->getPointeeType();
7668 else
7669 done = true;
7670 if (CanTy.isVolatileQualified())
7671 VRQuals.addVolatile();
7672 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7673 return VRQuals;
7674 }
7675 }
7676 }
7677 return VRQuals;
7678}
7679
7680namespace {
7681
7682/// Helper class to manage the addition of builtin operator overload
7683/// candidates. It provides shared state and utility methods used throughout
7684/// the process, as well as a helper method to add each group of builtin
7685/// operator overloads from the standard to a candidate set.
7686class BuiltinOperatorOverloadBuilder {
7687 // Common instance state available to all overload candidate addition methods.
7688 Sema &S;
7689 ArrayRef<Expr *> Args;
7690 Qualifiers VisibleTypeConversionsQuals;
7691 bool HasArithmeticOrEnumeralCandidateType;
7692 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7693 OverloadCandidateSet &CandidateSet;
7694
7695 static constexpr int ArithmeticTypesCap = 24;
7696 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7697
7698 // Define some indices used to iterate over the arithemetic types in
7699 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
7700 // types are that preserved by promotion (C++ [over.built]p2).
7701 unsigned FirstIntegralType,
7702 LastIntegralType;
7703 unsigned FirstPromotedIntegralType,
7704 LastPromotedIntegralType;
7705 unsigned FirstPromotedArithmeticType,
7706 LastPromotedArithmeticType;
7707 unsigned NumArithmeticTypes;
7708
7709 void InitArithmeticTypes() {
7710 // Start of promoted types.
7711 FirstPromotedArithmeticType = 0;
7712 ArithmeticTypes.push_back(S.Context.FloatTy);
7713 ArithmeticTypes.push_back(S.Context.DoubleTy);
7714 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7715 if (S.Context.getTargetInfo().hasFloat128Type())
7716 ArithmeticTypes.push_back(S.Context.Float128Ty);
7717
7718 // Start of integral types.
7719 FirstIntegralType = ArithmeticTypes.size();
7720 FirstPromotedIntegralType = ArithmeticTypes.size();
7721 ArithmeticTypes.push_back(S.Context.IntTy);
7722 ArithmeticTypes.push_back(S.Context.LongTy);
7723 ArithmeticTypes.push_back(S.Context.LongLongTy);
7724 if (S.Context.getTargetInfo().hasInt128Type())
7725 ArithmeticTypes.push_back(S.Context.Int128Ty);
7726 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7727 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7728 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7729 if (S.Context.getTargetInfo().hasInt128Type())
7730 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7731 LastPromotedIntegralType = ArithmeticTypes.size();
7732 LastPromotedArithmeticType = ArithmeticTypes.size();
7733 // End of promoted types.
7734
7735 ArithmeticTypes.push_back(S.Context.BoolTy);
7736 ArithmeticTypes.push_back(S.Context.CharTy);
7737 ArithmeticTypes.push_back(S.Context.WCharTy);
7738 if (S.Context.getLangOpts().Char8)
7739 ArithmeticTypes.push_back(S.Context.Char8Ty);
7740 ArithmeticTypes.push_back(S.Context.Char16Ty);
7741 ArithmeticTypes.push_back(S.Context.Char32Ty);
7742 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7743 ArithmeticTypes.push_back(S.Context.ShortTy);
7744 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7745 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7746 LastIntegralType = ArithmeticTypes.size();
7747 NumArithmeticTypes = ArithmeticTypes.size();
7748 // End of integral types.
7749 // FIXME: What about complex? What about half?
7750
7751 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7752, __extension__ __PRETTY_FUNCTION__))
7752 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7752, __extension__ __PRETTY_FUNCTION__))
;
7753 }
7754
7755 /// Helper method to factor out the common pattern of adding overloads
7756 /// for '++' and '--' builtin operators.
7757 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7758 bool HasVolatile,
7759 bool HasRestrict) {
7760 QualType ParamTypes[2] = {
7761 S.Context.getLValueReferenceType(CandidateTy),
7762 S.Context.IntTy
7763 };
7764
7765 // Non-volatile version.
7766 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7767
7768 // Use a heuristic to reduce number of builtin candidates in the set:
7769 // add volatile version only if there are conversions to a volatile type.
7770 if (HasVolatile) {
7771 ParamTypes[0] =
7772 S.Context.getLValueReferenceType(
7773 S.Context.getVolatileType(CandidateTy));
7774 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7775 }
7776
7777 // Add restrict version only if there are conversions to a restrict type
7778 // and our candidate type is a non-restrict-qualified pointer.
7779 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7780 !CandidateTy.isRestrictQualified()) {
7781 ParamTypes[0]
7782 = S.Context.getLValueReferenceType(
7783 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7784 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7785
7786 if (HasVolatile) {
7787 ParamTypes[0]
7788 = S.Context.getLValueReferenceType(
7789 S.Context.getCVRQualifiedType(CandidateTy,
7790 (Qualifiers::Volatile |
7791 Qualifiers::Restrict)));
7792 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7793 }
7794 }
7795
7796 }
7797
7798public:
7799 BuiltinOperatorOverloadBuilder(
7800 Sema &S, ArrayRef<Expr *> Args,
7801 Qualifiers VisibleTypeConversionsQuals,
7802 bool HasArithmeticOrEnumeralCandidateType,
7803 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7804 OverloadCandidateSet &CandidateSet)
7805 : S(S), Args(Args),
7806 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7807 HasArithmeticOrEnumeralCandidateType(
7808 HasArithmeticOrEnumeralCandidateType),
7809 CandidateTypes(CandidateTypes),
7810 CandidateSet(CandidateSet) {
7811
7812 InitArithmeticTypes();
7813 }
7814
7815 // Increment is deprecated for bool since C++17.
7816 //
7817 // C++ [over.built]p3:
7818 //
7819 // For every pair (T, VQ), where T is an arithmetic type other
7820 // than bool, and VQ is either volatile or empty, there exist
7821 // candidate operator functions of the form
7822 //
7823 // VQ T& operator++(VQ T&);
7824 // T operator++(VQ T&, int);
7825 //
7826 // C++ [over.built]p4:
7827 //
7828 // For every pair (T, VQ), where T is an arithmetic type other
7829 // than bool, and VQ is either volatile or empty, there exist
7830 // candidate operator functions of the form
7831 //
7832 // VQ T& operator--(VQ T&);
7833 // T operator--(VQ T&, int);
7834 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7835 if (!HasArithmeticOrEnumeralCandidateType)
7836 return;
7837
7838 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7839 const auto TypeOfT = ArithmeticTypes[Arith];
7840 if (TypeOfT == S.Context.BoolTy) {
7841 if (Op == OO_MinusMinus)
7842 continue;
7843 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7844 continue;
7845 }
7846 addPlusPlusMinusMinusStyleOverloads(
7847 TypeOfT,
7848 VisibleTypeConversionsQuals.hasVolatile(),
7849 VisibleTypeConversionsQuals.hasRestrict());
7850 }
7851 }
7852
7853 // C++ [over.built]p5:
7854 //
7855 // For every pair (T, VQ), where T is a cv-qualified or
7856 // cv-unqualified object type, and VQ is either volatile or
7857 // empty, there exist candidate operator functions of the form
7858 //
7859 // T*VQ& operator++(T*VQ&);
7860 // T*VQ& operator--(T*VQ&);
7861 // T* operator++(T*VQ&, int);
7862 // T* operator--(T*VQ&, int);
7863 void addPlusPlusMinusMinusPointerOverloads() {
7864 for (BuiltinCandidateTypeSet::iterator
7865 Ptr = CandidateTypes[0].pointer_begin(),
7866 PtrEnd = CandidateTypes[0].pointer_end();
7867 Ptr != PtrEnd; ++Ptr) {
7868 // Skip pointer types that aren't pointers to object types.
7869 if (!(*Ptr)->getPointeeType()->isObjectType())
7870 continue;
7871
7872 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7873 (!(*Ptr).isVolatileQualified() &&
7874 VisibleTypeConversionsQuals.hasVolatile()),
7875 (!(*Ptr).isRestrictQualified() &&
7876 VisibleTypeConversionsQuals.hasRestrict()));
7877 }
7878 }
7879
7880 // C++ [over.built]p6:
7881 // For every cv-qualified or cv-unqualified object type T, there
7882 // exist candidate operator functions of the form
7883 //
7884 // T& operator*(T*);
7885 //
7886 // C++ [over.built]p7:
7887 // For every function type T that does not have cv-qualifiers or a
7888 // ref-qualifier, there exist candidate operator functions of the form
7889 // T& operator*(T*);
7890 void addUnaryStarPointerOverloads() {
7891 for (BuiltinCandidateTypeSet::iterator
7892 Ptr = CandidateTypes[0].pointer_begin(),
7893 PtrEnd = CandidateTypes[0].pointer_end();
7894 Ptr != PtrEnd; ++Ptr) {
7895 QualType ParamTy = *Ptr;
7896 QualType PointeeTy = ParamTy->getPointeeType();
7897 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7898 continue;
7899
7900 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7901 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7902 continue;
7903
7904 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7905 }
7906 }
7907
7908 // C++ [over.built]p9:
7909 // For every promoted arithmetic type T, there exist candidate
7910 // operator functions of the form
7911 //
7912 // T operator+(T);
7913 // T operator-(T);
7914 void addUnaryPlusOrMinusArithmeticOverloads() {
7915 if (!HasArithmeticOrEnumeralCandidateType)
7916 return;
7917
7918 for (unsigned Arith = FirstPromotedArithmeticType;
7919 Arith < LastPromotedArithmeticType; ++Arith) {
7920 QualType ArithTy = ArithmeticTypes[Arith];
7921 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
7922 }
7923
7924 // Extension: We also add these operators for vector types.
7925 for (BuiltinCandidateTypeSet::iterator
7926 Vec = CandidateTypes[0].vector_begin(),
7927 VecEnd = CandidateTypes[0].vector_end();
7928 Vec != VecEnd; ++Vec) {
7929 QualType VecTy = *Vec;
7930 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7931 }
7932 }
7933
7934 // C++ [over.built]p8:
7935 // For every type T, there exist candidate operator functions of
7936 // the form
7937 //
7938 // T* operator+(T*);
7939 void addUnaryPlusPointerOverloads() {
7940 for (BuiltinCandidateTypeSet::iterator
7941 Ptr = CandidateTypes[0].pointer_begin(),
7942 PtrEnd = CandidateTypes[0].pointer_end();
7943 Ptr != PtrEnd; ++Ptr) {
7944 QualType ParamTy = *Ptr;
7945 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
7946 }
7947 }
7948
7949 // C++ [over.built]p10:
7950 // For every promoted integral type T, there exist candidate
7951 // operator functions of the form
7952 //
7953 // T operator~(T);
7954 void addUnaryTildePromotedIntegralOverloads() {
7955 if (!HasArithmeticOrEnumeralCandidateType)
7956 return;
7957
7958 for (unsigned Int = FirstPromotedIntegralType;
7959 Int < LastPromotedIntegralType; ++Int) {
7960 QualType IntTy = ArithmeticTypes[Int];
7961 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
7962 }
7963
7964 // Extension: We also add this operator for vector types.
7965 for (BuiltinCandidateTypeSet::iterator
7966 Vec = CandidateTypes[0].vector_begin(),
7967 VecEnd = CandidateTypes[0].vector_end();
7968 Vec != VecEnd; ++Vec) {
7969 QualType VecTy = *Vec;
7970 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
7971 }
7972 }
7973
7974 // C++ [over.match.oper]p16:
7975 // For every pointer to member type T or type std::nullptr_t, there
7976 // exist candidate operator functions of the form
7977 //
7978 // bool operator==(T,T);
7979 // bool operator!=(T,T);
7980 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7981 /// Set of (canonical) types that we've already handled.
7982 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7983
7984 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7985 for (BuiltinCandidateTypeSet::iterator
7986 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7987 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7988 MemPtr != MemPtrEnd;
7989 ++MemPtr) {
7990 // Don't add the same builtin candidate twice.
7991 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7992 continue;
7993
7994 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7995 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7996 }
7997
7998 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7999 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8000 if (AddedTypes.insert(NullPtrTy).second) {
8001 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8002 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8003 }
8004 }
8005 }
8006 }
8007
8008 // C++ [over.built]p15:
8009 //
8010 // For every T, where T is an enumeration type or a pointer type,
8011 // there exist candidate operator functions of the form
8012 //
8013 // bool operator<(T, T);
8014 // bool operator>(T, T);
8015 // bool operator<=(T, T);
8016 // bool operator>=(T, T);
8017 // bool operator==(T, T);
8018 // bool operator!=(T, T);
8019 // R operator<=>(T, T)
8020 void addGenericBinaryPointerOrEnumeralOverloads() {
8021 // C++ [over.match.oper]p3:
8022 // [...]the built-in candidates include all of the candidate operator
8023 // functions defined in 13.6 that, compared to the given operator, [...]
8024 // do not have the same parameter-type-list as any non-template non-member
8025 // candidate.
8026 //
8027 // Note that in practice, this only affects enumeration types because there
8028 // aren't any built-in candidates of record type, and a user-defined operator
8029 // must have an operand of record or enumeration type. Also, the only other
8030 // overloaded operator with enumeration arguments, operator=,
8031 // cannot be overloaded for enumeration types, so this is the only place
8032 // where we must suppress candidates like this.
8033 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8034 UserDefinedBinaryOperators;
8035
8036 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8037 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8038 CandidateTypes[ArgIdx].enumeration_end()) {
8039 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8040 CEnd = CandidateSet.end();
8041 C != CEnd; ++C) {
8042 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8043 continue;
8044
8045 if (C->Function->isFunctionTemplateSpecialization())
8046 continue;
8047
8048 QualType FirstParamType =
8049 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8050 QualType SecondParamType =
8051 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8052
8053 // Skip if either parameter isn't of enumeral type.
8054 if (!FirstParamType->isEnumeralType() ||
8055 !SecondParamType->isEnumeralType())
8056 continue;
8057
8058 // Add this operator to the set of known user-defined operators.
8059 UserDefinedBinaryOperators.insert(
8060 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8061 S.Context.getCanonicalType(SecondParamType)));
8062 }
8063 }
8064 }
8065
8066 /// Set of (canonical) types that we've already handled.
8067 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8068
8069 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8070 for (BuiltinCandidateTypeSet::iterator
8071 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8072 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8073 Ptr != PtrEnd; ++Ptr) {
8074 // Don't add the same builtin candidate twice.
8075 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8076 continue;
8077
8078 QualType ParamTypes[2] = { *Ptr, *Ptr };
8079 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8080 }
8081 for (BuiltinCandidateTypeSet::iterator
8082 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8083 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8084 Enum != EnumEnd; ++Enum) {
8085 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8086
8087 // Don't add the same builtin candidate twice, or if a user defined
8088 // candidate exists.
8089 if (!AddedTypes.insert(CanonType).second ||
8090 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8091 CanonType)))
8092 continue;
8093 QualType ParamTypes[2] = { *Enum, *Enum };
8094 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8095 }
8096 }
8097 }
8098
8099 // C++ [over.built]p13:
8100 //
8101 // For every cv-qualified or cv-unqualified object type T
8102 // there exist candidate operator functions of the form
8103 //
8104 // T* operator+(T*, ptrdiff_t);
8105 // T& operator[](T*, ptrdiff_t); [BELOW]
8106 // T* operator-(T*, ptrdiff_t);
8107 // T* operator+(ptrdiff_t, T*);
8108 // T& operator[](ptrdiff_t, T*); [BELOW]
8109 //
8110 // C++ [over.built]p14:
8111 //
8112 // For every T, where T is a pointer to object type, there
8113 // exist candidate operator functions of the form
8114 //
8115 // ptrdiff_t operator-(T, T);
8116 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8117 /// Set of (canonical) types that we've already handled.
8118 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8119
8120 for (int Arg = 0; Arg < 2; ++Arg) {
8121 QualType AsymmetricParamTypes[2] = {
8122 S.Context.getPointerDiffType(),
8123 S.Context.getPointerDiffType(),
8124 };
8125 for (BuiltinCandidateTypeSet::iterator
8126 Ptr = CandidateTypes[Arg].pointer_begin(),
8127 PtrEnd = CandidateTypes[Arg].pointer_end();
8128 Ptr != PtrEnd; ++Ptr) {
8129 QualType PointeeTy = (*Ptr)->getPointeeType();
8130 if (!PointeeTy->isObjectType())
8131 continue;
8132
8133 AsymmetricParamTypes[Arg] = *Ptr;
8134 if (Arg == 0 || Op == OO_Plus) {
8135 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8136 // T* operator+(ptrdiff_t, T*);
8137 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8138 }
8139 if (Op == OO_Minus) {
8140 // ptrdiff_t operator-(T, T);
8141 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8142 continue;
8143
8144 QualType ParamTypes[2] = { *Ptr, *Ptr };
8145 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8146 }
8147 }
8148 }
8149 }
8150
8151 // C++ [over.built]p12:
8152 //
8153 // For every pair of promoted arithmetic types L and R, there
8154 // exist candidate operator functions of the form
8155 //
8156 // LR operator*(L, R);
8157 // LR operator/(L, R);
8158 // LR operator+(L, R);
8159 // LR operator-(L, R);
8160 // bool operator<(L, R);
8161 // bool operator>(L, R);
8162 // bool operator<=(L, R);
8163 // bool operator>=(L, R);
8164 // bool operator==(L, R);
8165 // bool operator!=(L, R);
8166 //
8167 // where LR is the result of the usual arithmetic conversions
8168 // between types L and R.
8169 //
8170 // C++ [over.built]p24:
8171 //
8172 // For every pair of promoted arithmetic types L and R, there exist
8173 // candidate operator functions of the form
8174 //
8175 // LR operator?(bool, L, R);
8176 //
8177 // where LR is the result of the usual arithmetic conversions
8178 // between types L and R.
8179 // Our candidates ignore the first parameter.
8180 void addGenericBinaryArithmeticOverloads() {
8181 if (!HasArithmeticOrEnumeralCandidateType)
8182 return;
8183
8184 for (unsigned Left = FirstPromotedArithmeticType;
8185 Left < LastPromotedArithmeticType; ++Left) {
8186 for (unsigned Right = FirstPromotedArithmeticType;
8187 Right < LastPromotedArithmeticType; ++Right) {
8188 QualType LandR[2] = { ArithmeticTypes[Left],
8189 ArithmeticTypes[Right] };
8190 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8191 }
8192 }
8193
8194 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8195 // conditional operator for vector types.
8196 for (BuiltinCandidateTypeSet::iterator
8197 Vec1 = CandidateTypes[0].vector_begin(),
8198 Vec1End = CandidateTypes[0].vector_end();
8199 Vec1 != Vec1End; ++Vec1) {
8200 for (BuiltinCandidateTypeSet::iterator
8201 Vec2 = CandidateTypes[1].vector_begin(),
8202 Vec2End = CandidateTypes[1].vector_end();
8203 Vec2 != Vec2End; ++Vec2) {
8204 QualType LandR[2] = { *Vec1, *Vec2 };
8205 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8206 }
8207 }
8208 }
8209
8210 // C++2a [over.built]p14:
8211 //
8212 // For every integral type T there exists a candidate operator function
8213 // of the form
8214 //
8215 // std::strong_ordering operator<=>(T, T)
8216 //
8217 // C++2a [over.built]p15:
8218 //
8219 // For every pair of floating-point types L and R, there exists a candidate
8220 // operator function of the form
8221 //
8222 // std::partial_ordering operator<=>(L, R);
8223 //
8224 // FIXME: The current specification for integral types doesn't play nice with
8225 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8226 // comparisons. Under the current spec this can lead to ambiguity during
8227 // overload resolution. For example:
8228 //
8229 // enum A : int {a};
8230 // auto x = (a <=> (long)42);
8231 //
8232 // error: call is ambiguous for arguments 'A' and 'long'.
8233 // note: candidate operator<=>(int, int)
8234 // note: candidate operator<=>(long, long)
8235 //
8236 // To avoid this error, this function deviates from the specification and adds
8237 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8238 // arithmetic types (the same as the generic relational overloads).
8239 //
8240 // For now this function acts as a placeholder.
8241 void addThreeWayArithmeticOverloads() {
8242 addGenericBinaryArithmeticOverloads();
8243 }
8244
8245 // C++ [over.built]p17:
8246 //
8247 // For every pair of promoted integral types L and R, there
8248 // exist candidate operator functions of the form
8249 //
8250 // LR operator%(L, R);
8251 // LR operator&(L, R);
8252 // LR operator^(L, R);
8253 // LR operator|(L, R);
8254 // L operator<<(L, R);
8255 // L operator>>(L, R);
8256 //
8257 // where LR is the result of the usual arithmetic conversions
8258 // between types L and R.
8259 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8260 if (!HasArithmeticOrEnumeralCandidateType)
8261 return;
8262
8263 for (unsigned Left = FirstPromotedIntegralType;
8264 Left < LastPromotedIntegralType; ++Left) {
8265 for (unsigned Right = FirstPromotedIntegralType;
8266 Right < LastPromotedIntegralType; ++Right) {
8267 QualType LandR[2] = { ArithmeticTypes[Left],
8268 ArithmeticTypes[Right] };
8269 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8270 }
8271 }
8272 }
8273
8274 // C++ [over.built]p20:
8275 //
8276 // For every pair (T, VQ), where T is an enumeration or
8277 // pointer to member type and VQ is either volatile or
8278 // empty, there exist candidate operator functions of the form
8279 //
8280 // VQ T& operator=(VQ T&, T);
8281 void addAssignmentMemberPointerOrEnumeralOverloads() {
8282 /// Set of (canonical) types that we've already handled.
8283 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8284
8285 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8286 for (BuiltinCandidateTypeSet::iterator
8287 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8288 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8289 Enum != EnumEnd; ++Enum) {
8290 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8291 continue;
8292
8293 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8294 }
8295
8296 for (BuiltinCandidateTypeSet::iterator
8297 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8298 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8299 MemPtr != MemPtrEnd; ++MemPtr) {
8300 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8301 continue;
8302
8303 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8304 }
8305 }
8306 }
8307
8308 // C++ [over.built]p19:
8309 //
8310 // For every pair (T, VQ), where T is any type and VQ is either
8311 // volatile or empty, there exist candidate operator functions
8312 // of the form
8313 //
8314 // T*VQ& operator=(T*VQ&, T*);
8315 //
8316 // C++ [over.built]p21:
8317 //
8318 // For every pair (T, VQ), where T is a cv-qualified or
8319 // cv-unqualified object type and VQ is either volatile or
8320 // empty, there exist candidate operator functions of the form
8321 //
8322 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8323 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8324 void addAssignmentPointerOverloads(bool isEqualOp) {
8325 /// Set of (canonical) types that we've already handled.
8326 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8327
8328 for (BuiltinCandidateTypeSet::iterator
8329 Ptr = CandidateTypes[0].pointer_begin(),
8330 PtrEnd = CandidateTypes[0].pointer_end();
8331 Ptr != PtrEnd; ++Ptr) {
8332 // If this is operator=, keep track of the builtin candidates we added.
8333 if (isEqualOp)
8334 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8335 else if (!(*Ptr)->getPointeeType()->isObjectType())
8336 continue;
8337
8338 // non-volatile version
8339 QualType ParamTypes[2] = {
8340 S.Context.getLValueReferenceType(*Ptr),
8341 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8342 };
8343 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8344 /*IsAssigmentOperator=*/ isEqualOp);
8345
8346 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8347 VisibleTypeConversionsQuals.hasVolatile();
8348 if (NeedVolatile) {
8349 // volatile version
8350 ParamTypes[0] =
8351 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8352 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8353 /*IsAssigmentOperator=*/isEqualOp);
8354 }
8355
8356 if (!(*Ptr).isRestrictQualified() &&
8357 VisibleTypeConversionsQuals.hasRestrict()) {
8358 // restrict version
8359 ParamTypes[0]
8360 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8361 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8362 /*IsAssigmentOperator=*/isEqualOp);
8363
8364 if (NeedVolatile) {
8365 // volatile restrict version
8366 ParamTypes[0]
8367 = S.Context.getLValueReferenceType(
8368 S.Context.getCVRQualifiedType(*Ptr,
8369 (Qualifiers::Volatile |
8370 Qualifiers::Restrict)));
8371 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8372 /*IsAssigmentOperator=*/isEqualOp);
8373 }
8374 }
8375 }
8376
8377 if (isEqualOp) {
8378 for (BuiltinCandidateTypeSet::iterator
8379 Ptr = CandidateTypes[1].pointer_begin(),
8380 PtrEnd = CandidateTypes[1].pointer_end();
8381 Ptr != PtrEnd; ++Ptr) {
8382 // Make sure we don't add the same candidate twice.
8383 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8384 continue;
8385
8386 QualType ParamTypes[2] = {
8387 S.Context.getLValueReferenceType(*Ptr),
8388 *Ptr,
8389 };
8390
8391 // non-volatile version
8392 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8393 /*IsAssigmentOperator=*/true);
8394
8395 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8396 VisibleTypeConversionsQuals.hasVolatile();
8397 if (NeedVolatile) {
8398 // volatile version
8399 ParamTypes[0] =
8400 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8401 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8402 /*IsAssigmentOperator=*/true);
8403 }
8404
8405 if (!(*Ptr).isRestrictQualified() &&
8406 VisibleTypeConversionsQuals.hasRestrict()) {
8407 // restrict version
8408 ParamTypes[0]
8409 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8410 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8411 /*IsAssigmentOperator=*/true);
8412
8413 if (NeedVolatile) {
8414 // volatile restrict version
8415 ParamTypes[0]
8416 = S.Context.getLValueReferenceType(
8417 S.Context.getCVRQualifiedType(*Ptr,
8418 (Qualifiers::Volatile |
8419 Qualifiers::Restrict)));
8420 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8421 /*IsAssigmentOperator=*/true);
8422 }
8423 }
8424 }
8425 }
8426 }
8427
8428 // C++ [over.built]p18:
8429 //
8430 // For every triple (L, VQ, R), where L is an arithmetic type,
8431 // VQ is either volatile or empty, and R is a promoted
8432 // arithmetic type, there exist candidate operator functions of
8433 // the form
8434 //
8435 // VQ L& operator=(VQ L&, R);
8436 // VQ L& operator*=(VQ L&, R);
8437 // VQ L& operator/=(VQ L&, R);
8438 // VQ L& operator+=(VQ L&, R);
8439 // VQ L& operator-=(VQ L&, R);
8440 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8441 if (!HasArithmeticOrEnumeralCandidateType)
8442 return;
8443
8444 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8445 for (unsigned Right = FirstPromotedArithmeticType;
8446 Right < LastPromotedArithmeticType; ++Right) {
8447 QualType ParamTypes[2];
8448 ParamTypes[1] = ArithmeticTypes[Right];
8449
8450 // Add this built-in operator as a candidate (VQ is empty).
8451 ParamTypes[0] =
8452 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8453 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8454 /*IsAssigmentOperator=*/isEqualOp);
8455
8456 // Add this built-in operator as a candidate (VQ is 'volatile').
8457 if (VisibleTypeConversionsQuals.hasVolatile()) {
8458 ParamTypes[0] =
8459 S.Context.getVolatileType(ArithmeticTypes[Left]);
8460 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8461 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8462 /*IsAssigmentOperator=*/isEqualOp);
8463 }
8464 }
8465 }
8466
8467 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8468 for (BuiltinCandidateTypeSet::iterator
8469 Vec1 = CandidateTypes[0].vector_begin(),
8470 Vec1End = CandidateTypes[0].vector_end();
8471 Vec1 != Vec1End; ++Vec1) {
8472 for (BuiltinCandidateTypeSet::iterator
8473 Vec2 = CandidateTypes[1].vector_begin(),
8474 Vec2End = CandidateTypes[1].vector_end();
8475 Vec2 != Vec2End; ++Vec2) {
8476 QualType ParamTypes[2];
8477 ParamTypes[1] = *Vec2;
8478 // Add this built-in operator as a candidate (VQ is empty).
8479 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8480 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8481 /*IsAssigmentOperator=*/isEqualOp);
8482
8483 // Add this built-in operator as a candidate (VQ is 'volatile').
8484 if (VisibleTypeConversionsQuals.hasVolatile()) {
8485 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8486 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8487 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8488 /*IsAssigmentOperator=*/isEqualOp);
8489 }
8490 }
8491 }
8492 }
8493
8494 // C++ [over.built]p22:
8495 //
8496 // For every triple (L, VQ, R), where L is an integral type, VQ
8497 // is either volatile or empty, and R is a promoted integral
8498 // type, there exist candidate operator functions of the form
8499 //
8500 // VQ L& operator%=(VQ L&, R);
8501 // VQ L& operator<<=(VQ L&, R);
8502 // VQ L& operator>>=(VQ L&, R);
8503 // VQ L& operator&=(VQ L&, R);
8504 // VQ L& operator^=(VQ L&, R);
8505 // VQ L& operator|=(VQ L&, R);
8506 void addAssignmentIntegralOverloads() {
8507 if (!HasArithmeticOrEnumeralCandidateType)
8508 return;
8509
8510 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8511 for (unsigned Right = FirstPromotedIntegralType;
8512 Right < LastPromotedIntegralType; ++Right) {
8513 QualType ParamTypes[2];
8514 ParamTypes[1] = ArithmeticTypes[Right];
8515
8516 // Add this built-in operator as a candidate (VQ is empty).
8517 ParamTypes[0] =
8518 S.Context.getLValueReferenceType(ArithmeticTypes[Left]);
8519 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8520 if (VisibleTypeConversionsQuals.hasVolatile()) {
8521 // Add this built-in operator as a candidate (VQ is 'volatile').
8522 ParamTypes[0] = ArithmeticTypes[Left];
8523 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8524 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8525 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8526 }
8527 }
8528 }
8529 }
8530
8531 // C++ [over.operator]p23:
8532 //
8533 // There also exist candidate operator functions of the form
8534 //
8535 // bool operator!(bool);
8536 // bool operator&&(bool, bool);
8537 // bool operator||(bool, bool);
8538 void addExclaimOverload() {
8539 QualType ParamTy = S.Context.BoolTy;
8540 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8541 /*IsAssignmentOperator=*/false,
8542 /*NumContextualBoolArguments=*/1);
8543 }
8544 void addAmpAmpOrPipePipeOverload() {
8545 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8546 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8547 /*IsAssignmentOperator=*/false,
8548 /*NumContextualBoolArguments=*/2);
8549 }
8550
8551 // C++ [over.built]p13:
8552 //
8553 // For every cv-qualified or cv-unqualified object type T there
8554 // exist candidate operator functions of the form
8555 //
8556 // T* operator+(T*, ptrdiff_t); [ABOVE]
8557 // T& operator[](T*, ptrdiff_t);
8558 // T* operator-(T*, ptrdiff_t); [ABOVE]
8559 // T* operator+(ptrdiff_t, T*); [ABOVE]
8560 // T& operator[](ptrdiff_t, T*);
8561 void addSubscriptOverloads() {
8562 for (BuiltinCandidateTypeSet::iterator
8563 Ptr = CandidateTypes[0].pointer_begin(),
8564 PtrEnd = CandidateTypes[0].pointer_end();
8565 Ptr != PtrEnd; ++Ptr) {
8566 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8567 QualType PointeeType = (*Ptr)->getPointeeType();
8568 if (!PointeeType->isObjectType())
8569 continue;
8570
8571 // T& operator[](T*, ptrdiff_t)
8572 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8573 }
8574
8575 for (BuiltinCandidateTypeSet::iterator
8576 Ptr = CandidateTypes[1].pointer_begin(),
8577 PtrEnd = CandidateTypes[1].pointer_end();
8578 Ptr != PtrEnd; ++Ptr) {
8579 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8580 QualType PointeeType = (*Ptr)->getPointeeType();
8581 if (!PointeeType->isObjectType())
8582 continue;
8583
8584 // T& operator[](ptrdiff_t, T*)
8585 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8586 }
8587 }
8588
8589 // C++ [over.built]p11:
8590 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8591 // C1 is the same type as C2 or is a derived class of C2, T is an object
8592 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8593 // there exist candidate operator functions of the form
8594 //
8595 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8596 //
8597 // where CV12 is the union of CV1 and CV2.
8598 void addArrowStarOverloads() {
8599 for (BuiltinCandidateTypeSet::iterator
8600 Ptr = CandidateTypes[0].pointer_begin(),
8601 PtrEnd = CandidateTypes[0].pointer_end();
8602 Ptr != PtrEnd; ++Ptr) {
8603 QualType C1Ty = (*Ptr);
8604 QualType C1;
8605 QualifierCollector Q1;
8606 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8607 if (!isa<RecordType>(C1))
8608 continue;
8609 // heuristic to reduce number of builtin candidates in the set.
8610 // Add volatile/restrict version only if there are conversions to a
8611 // volatile/restrict type.
8612 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8613 continue;
8614 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8615 continue;
8616 for (BuiltinCandidateTypeSet::iterator
8617 MemPtr = CandidateTypes[1].member_pointer_begin(),
8618 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8619 MemPtr != MemPtrEnd; ++MemPtr) {
8620 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8621 QualType C2 = QualType(mptr->getClass(), 0);
8622 C2 = C2.getUnqualifiedType();
8623 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8624 break;
8625 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8626 // build CV12 T&
8627 QualType T = mptr->getPointeeType();
8628 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8629 T.isVolatileQualified())
8630 continue;
8631 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8632 T.isRestrictQualified())
8633 continue;
8634 T = Q1.apply(S.Context, T);
8635 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8636 }
8637 }
8638 }
8639
8640 // Note that we don't consider the first argument, since it has been
8641 // contextually converted to bool long ago. The candidates below are
8642 // therefore added as binary.
8643 //
8644 // C++ [over.built]p25:
8645 // For every type T, where T is a pointer, pointer-to-member, or scoped
8646 // enumeration type, there exist candidate operator functions of the form
8647 //
8648 // T operator?(bool, T, T);
8649 //
8650 void addConditionalOperatorOverloads() {
8651 /// Set of (canonical) types that we've already handled.
8652 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8653
8654 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8655 for (BuiltinCandidateTypeSet::iterator
8656 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8657 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8658 Ptr != PtrEnd; ++Ptr) {
8659 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8660 continue;
8661
8662 QualType ParamTypes[2] = { *Ptr, *Ptr };
8663 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8664 }
8665
8666 for (BuiltinCandidateTypeSet::iterator
8667 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8668 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8669 MemPtr != MemPtrEnd; ++MemPtr) {
8670 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8671 continue;
8672
8673 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8674 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8675 }
8676
8677 if (S.getLangOpts().CPlusPlus11) {
8678 for (BuiltinCandidateTypeSet::iterator
8679 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8680 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8681 Enum != EnumEnd; ++Enum) {
8682 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8683 continue;
8684
8685 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8686 continue;
8687
8688 QualType ParamTypes[2] = { *Enum, *Enum };
8689 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8690 }
8691 }
8692 }
8693 }
8694};
8695
8696} // end anonymous namespace
8697
8698/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8699/// operator overloads to the candidate set (C++ [over.built]), based
8700/// on the operator @p Op and the arguments given. For example, if the
8701/// operator is a binary '+', this routine might add "int
8702/// operator+(int, int)" to cover integer addition.
8703void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8704 SourceLocation OpLoc,
8705 ArrayRef<Expr *> Args,
8706 OverloadCandidateSet &CandidateSet) {
8707 // Find all of the types that the arguments can convert to, but only
8708 // if the operator we're looking at has built-in operator candidates
8709 // that make use of these types. Also record whether we encounter non-record
8710 // candidate types or either arithmetic or enumeral candidate types.
8711 Qualifiers VisibleTypeConversionsQuals;
8712 VisibleTypeConversionsQuals.addConst();
8713 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8714 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8715
8716 bool HasNonRecordCandidateType = false;
8717 bool HasArithmeticOrEnumeralCandidateType = false;
8718 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8719 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8720 CandidateTypes.emplace_back(*this);
8721 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8722 OpLoc,
8723 true,
8724 (Op == OO_Exclaim ||
8725 Op == OO_AmpAmp ||
8726 Op == OO_PipePipe),
8727 VisibleTypeConversionsQuals);
8728 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8729 CandidateTypes[ArgIdx].hasNonRecordTypes();
8730 HasArithmeticOrEnumeralCandidateType =
8731 HasArithmeticOrEnumeralCandidateType ||
8732 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8733 }
8734
8735 // Exit early when no non-record types have been added to the candidate set
8736 // for any of the arguments to the operator.
8737 //
8738 // We can't exit early for !, ||, or &&, since there we have always have
8739 // 'bool' overloads.
8740 if (!HasNonRecordCandidateType &&
8741 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8742 return;
8743
8744 // Setup an object to manage the common state for building overloads.
8745 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8746 VisibleTypeConversionsQuals,
8747 HasArithmeticOrEnumeralCandidateType,
8748 CandidateTypes, CandidateSet);
8749
8750 // Dispatch over the operation to add in only those overloads which apply.
8751 switch (Op) {
8752 case OO_None:
8753 case NUM_OVERLOADED_OPERATORS:
8754 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8754)
;
8755
8756 case OO_New:
8757 case OO_Delete:
8758 case OO_Array_New:
8759 case OO_Array_Delete:
8760 case OO_Call:
8761 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8762)
8762 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8762)
;
8763
8764 case OO_Comma:
8765 case OO_Arrow:
8766 case OO_Coawait:
8767 // C++ [over.match.oper]p3:
8768 // -- For the operator ',', the unary operator '&', the
8769 // operator '->', or the operator 'co_await', the
8770 // built-in candidates set is empty.
8771 break;
8772
8773 case OO_Plus: // '+' is either unary or binary
8774 if (Args.size() == 1)
8775 OpBuilder.addUnaryPlusPointerOverloads();
8776 LLVM_FALLTHROUGH[[clang::fallthrough]];
8777
8778 case OO_Minus: // '-' is either unary or binary
8779 if (Args.size() == 1) {
8780 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8781 } else {
8782 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8783 OpBuilder.addGenericBinaryArithmeticOverloads();
8784 }
8785 break;
8786
8787 case OO_Star: // '*' is either unary or binary
8788 if (Args.size() == 1)
8789 OpBuilder.addUnaryStarPointerOverloads();
8790 else
8791 OpBuilder.addGenericBinaryArithmeticOverloads();
8792 break;
8793
8794 case OO_Slash:
8795 OpBuilder.addGenericBinaryArithmeticOverloads();
8796 break;
8797
8798 case OO_PlusPlus:
8799 case OO_MinusMinus:
8800 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8801 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8802 break;
8803
8804 case OO_EqualEqual:
8805 case OO_ExclaimEqual:
8806 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8807 LLVM_FALLTHROUGH[[clang::fallthrough]];
8808
8809 case OO_Less:
8810 case OO_Greater:
8811 case OO_LessEqual:
8812 case OO_GreaterEqual:
8813 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8814 OpBuilder.addGenericBinaryArithmeticOverloads();
8815 break;
8816
8817 case OO_Spaceship:
8818 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8819 OpBuilder.addThreeWayArithmeticOverloads();
8820 break;
8821
8822 case OO_Percent:
8823 case OO_Caret:
8824 case OO_Pipe:
8825 case OO_LessLess:
8826 case OO_GreaterGreater:
8827 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8828 break;
8829
8830 case OO_Amp: // '&' is either unary or binary
8831 if (Args.size() == 1)
8832 // C++ [over.match.oper]p3:
8833 // -- For the operator ',', the unary operator '&', or the
8834 // operator '->', the built-in candidates set is empty.
8835 break;
8836
8837 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8838 break;
8839
8840 case OO_Tilde:
8841 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8842 break;
8843
8844 case OO_Equal:
8845 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8846 LLVM_FALLTHROUGH[[clang::fallthrough]];
8847
8848 case OO_PlusEqual:
8849 case OO_MinusEqual:
8850 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8851 LLVM_FALLTHROUGH[[clang::fallthrough]];
8852
8853 case OO_StarEqual:
8854 case OO_SlashEqual:
8855 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8856 break;
8857
8858 case OO_PercentEqual:
8859 case OO_LessLessEqual:
8860 case OO_GreaterGreaterEqual:
8861 case OO_AmpEqual:
8862 case OO_CaretEqual:
8863 case OO_PipeEqual:
8864 OpBuilder.addAssignmentIntegralOverloads();
8865 break;
8866
8867 case OO_Exclaim:
8868 OpBuilder.addExclaimOverload();
8869 break;
8870
8871 case OO_AmpAmp:
8872 case OO_PipePipe:
8873 OpBuilder.addAmpAmpOrPipePipeOverload();
8874 break;
8875
8876 case OO_Subscript:
8877 OpBuilder.addSubscriptOverloads();
8878 break;
8879
8880 case OO_ArrowStar:
8881 OpBuilder.addArrowStarOverloads();
8882 break;
8883
8884 case OO_Conditional:
8885 OpBuilder.addConditionalOperatorOverloads();
8886 OpBuilder.addGenericBinaryArithmeticOverloads();
8887 break;
8888 }
8889}
8890
8891/// Add function candidates found via argument-dependent lookup
8892/// to the set of overloading candidates.
8893///
8894/// This routine performs argument-dependent name lookup based on the
8895/// given function name (which may also be an operator name) and adds
8896/// all of the overload candidates found by ADL to the overload
8897/// candidate set (C++ [basic.lookup.argdep]).
8898void
8899Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8900 SourceLocation Loc,
8901 ArrayRef<Expr *> Args,
8902 TemplateArgumentListInfo *ExplicitTemplateArgs,
8903 OverloadCandidateSet& CandidateSet,
8904 bool PartialOverloading) {
8905 ADLResult Fns;
8906
8907 // FIXME: This approach for uniquing ADL results (and removing
8908 // redundant candidates from the set) relies on pointer-equality,
8909 // which means we need to key off the canonical decl. However,
8910 // always going back to the canonical decl might not get us the
8911 // right set of default arguments. What default arguments are
8912 // we supposed to consider on ADL candidates, anyway?
8913
8914 // FIXME: Pass in the explicit template arguments?
8915 ArgumentDependentLookup(Name, Loc, Args, Fns);
8916
8917 // Erase all of the candidates we already knew about.
8918 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8919 CandEnd = CandidateSet.end();
8920 Cand != CandEnd; ++Cand)
8921 if (Cand->Function) {
8922 Fns.erase(Cand->Function);
8923 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8924 Fns.erase(FunTmpl);
8925 }
8926
8927 // For each of the ADL candidates we found, add it to the overload
8928 // set.
8929 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8930 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8931 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8932 if (ExplicitTemplateArgs)
8933 continue;
8934
8935 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8936 PartialOverloading);
8937 } else
8938 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8939 FoundDecl, ExplicitTemplateArgs,
8940 Args, CandidateSet, PartialOverloading);
8941 }
8942}
8943
8944namespace {
8945enum class Comparison { Equal, Better, Worse };
8946}
8947
8948/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8949/// overload resolution.
8950///
8951/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8952/// Cand1's first N enable_if attributes have precisely the same conditions as
8953/// Cand2's first N enable_if attributes (where N = the number of enable_if
8954/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8955///
8956/// Note that you can have a pair of candidates such that Cand1's enable_if
8957/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8958/// worse than Cand1's.
8959static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8960 const FunctionDecl *Cand2) {
8961 // Common case: One (or both) decls don't have enable_if attrs.
8962 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8963 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8964 if (!Cand1Attr || !Cand2Attr) {
8965 if (Cand1Attr == Cand2Attr)
8966 return Comparison::Equal;
8967 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8968 }
8969
8970 // FIXME: The next several lines are just
8971 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8972 // instead of reverse order which is how they're stored in the AST.
8973 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8974 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8975
8976 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8977 // has fewer enable_if attributes than Cand2.
8978 if (Cand1Attrs.size() < Cand2Attrs.size())
8979 return Comparison::Worse;
8980
8981 auto Cand1I = Cand1Attrs.begin();
8982 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8983 for (auto &Cand2A : Cand2Attrs) {
8984 Cand1ID.clear();
8985 Cand2ID.clear();
8986
8987 auto &Cand1A = *Cand1I++;
8988 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8989 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8990 if (Cand1ID != Cand2ID)
8991 return Comparison::Worse;
8992 }
8993
8994 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8995}
8996
8997static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
8998 const OverloadCandidate &Cand2) {
8999 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9000 !Cand2.Function->isMultiVersion())
9001 return false;
9002
9003 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9004 // cpu_dispatch, else arbitrarily based on the identifiers.
9005 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9006 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9007 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9008 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9009
9010 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9011 return false;
9012
9013 if (Cand1CPUDisp && !Cand2CPUDisp)
9014 return true;
9015 if (Cand2CPUDisp && !Cand1CPUDisp)
9016 return false;
9017
9018 if (Cand1CPUSpec && Cand2CPUSpec) {
9019 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9020 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9021
9022 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9023 FirstDiff = std::mismatch(
9024 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9025 Cand2CPUSpec->cpus_begin(),
9026 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9027 return LHS->getName() == RHS->getName();
9028 });
9029
9030 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&(static_cast <bool> (FirstDiff.first != Cand1CPUSpec->
cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? void
(0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9032, __extension__ __PRETTY_FUNCTION__))
9031 "Two different cpu-specific versions should not have the same "(static_cast <bool> (FirstDiff.first != Cand1CPUSpec->
cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? void
(0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9032, __extension__ __PRETTY_FUNCTION__))
9032 "identifier list, otherwise they'd be the same decl!")(static_cast <bool> (FirstDiff.first != Cand1CPUSpec->
cpus_end() && "Two different cpu-specific versions should not have the same "
"identifier list, otherwise they'd be the same decl!") ? void
(0) : __assert_fail ("FirstDiff.first != Cand1CPUSpec->cpus_end() && \"Two different cpu-specific versions should not have the same \" \"identifier list, otherwise they'd be the same decl!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9032, __extension__ __PRETTY_FUNCTION__))
;
9033 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9034 }
9035 llvm_unreachable("No way to get here unless both had cpu_dispatch")::llvm::llvm_unreachable_internal("No way to get here unless both had cpu_dispatch"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9035)
;
9036}
9037
9038/// isBetterOverloadCandidate - Determines whether the first overload
9039/// candidate is a better candidate than the second (C++ 13.3.3p1).
9040bool clang::isBetterOverloadCandidate(
9041 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9042 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9043 // Define viable functions to be better candidates than non-viable
9044 // functions.
9045 if (!Cand2.Viable)
9046 return Cand1.Viable;
9047 else if (!Cand1.Viable)
9048 return false;
9049
9050 // C++ [over.match.best]p1:
9051 //
9052 // -- if F is a static member function, ICS1(F) is defined such
9053 // that ICS1(F) is neither better nor worse than ICS1(G) for
9054 // any function G, and, symmetrically, ICS1(G) is neither
9055 // better nor worse than ICS1(F).
9056 unsigned StartArg = 0;
9057 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9058 StartArg = 1;
9059
9060 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9061 // We don't allow incompatible pointer conversions in C++.
9062 if (!S.getLangOpts().CPlusPlus)
9063 return ICS.isStandard() &&
9064 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9065
9066 // The only ill-formed conversion we allow in C++ is the string literal to
9067 // char* conversion, which is only considered ill-formed after C++11.
9068 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9069 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9070 };
9071
9072 // Define functions that don't require ill-formed conversions for a given
9073 // argument to be better candidates than functions that do.
9074 unsigned NumArgs = Cand1.Conversions.size();
9075 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9075, __extension__ __PRETTY_FUNCTION__))
;
9076 bool HasBetterConversion = false;
9077 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9078 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9079 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9080 if (Cand1Bad != Cand2Bad) {
9081 if (Cand1Bad)
9082 return false;
9083 HasBetterConversion = true;
9084 }
9085 }
9086
9087 if (HasBetterConversion)
9088 return true;
9089
9090 // C++ [over.match.best]p1:
9091 // A viable function F1 is defined to be a better function than another
9092 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9093 // conversion sequence than ICSi(F2), and then...
9094 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9095 switch (CompareImplicitConversionSequences(S, Loc,
9096 Cand1.Conversions[ArgIdx],
9097 Cand2.Conversions[ArgIdx])) {
9098 case ImplicitConversionSequence::Better:
9099 // Cand1 has a better conversion sequence.
9100 HasBetterConversion = true;
9101 break;
9102
9103 case ImplicitConversionSequence::Worse:
9104 // Cand1 can't be better than Cand2.
9105 return false;
9106
9107 case ImplicitConversionSequence::Indistinguishable:
9108 // Do nothing.
9109 break;
9110 }
9111 }
9112
9113 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9114 // ICSj(F2), or, if not that,
9115 if (HasBetterConversion)
9116 return true;
9117
9118 // -- the context is an initialization by user-defined conversion
9119 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9120 // from the return type of F1 to the destination type (i.e.,
9121 // the type of the entity being initialized) is a better
9122 // conversion sequence than the standard conversion sequence
9123 // from the return type of F2 to the destination type.
9124 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9125 Cand1.Function && Cand2.Function &&
9126 isa<CXXConversionDecl>(Cand1.Function) &&
9127 isa<CXXConversionDecl>(Cand2.Function)) {
9128 // First check whether we prefer one of the conversion functions over the
9129 // other. This only distinguishes the results in non-standard, extension
9130 // cases such as the conversion from a lambda closure type to a function
9131 // pointer or block.
9132 ImplicitConversionSequence::CompareKind Result =
9133 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9134 if (Result == ImplicitConversionSequence::Indistinguishable)
9135 Result = CompareStandardConversionSequences(S, Loc,
9136 Cand1.FinalConversion,
9137 Cand2.FinalConversion);
9138
9139 if (Result != ImplicitConversionSequence::Indistinguishable)
9140 return Result == ImplicitConversionSequence::Better;
9141
9142 // FIXME: Compare kind of reference binding if conversion functions
9143 // convert to a reference type used in direct reference binding, per
9144 // C++14 [over.match.best]p1 section 2 bullet 3.
9145 }
9146
9147 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9148 // as combined with the resolution to CWG issue 243.
9149 //
9150 // When the context is initialization by constructor ([over.match.ctor] or
9151 // either phase of [over.match.list]), a constructor is preferred over
9152 // a conversion function.
9153 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9154 Cand1.Function && Cand2.Function &&
9155 isa<CXXConstructorDecl>(Cand1.Function) !=
9156 isa<CXXConstructorDecl>(Cand2.Function))
9157 return isa<CXXConstructorDecl>(Cand1.Function);
9158
9159 // -- F1 is a non-template function and F2 is a function template
9160 // specialization, or, if not that,
9161 bool Cand1IsSpecialization = Cand1.Function &&
9162 Cand1.Function->getPrimaryTemplate();
9163 bool Cand2IsSpecialization = Cand2.Function &&
9164 Cand2.Function->getPrimaryTemplate();
9165 if (Cand1IsSpecialization != Cand2IsSpecialization)
9166 return Cand2IsSpecialization;
9167
9168 // -- F1 and F2 are function template specializations, and the function
9169 // template for F1 is more specialized than the template for F2
9170 // according to the partial ordering rules described in 14.5.5.2, or,
9171 // if not that,
9172 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9173 if (FunctionTemplateDecl *BetterTemplate
9174 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9175 Cand2.Function->getPrimaryTemplate(),
9176 Loc,
9177 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9178 : TPOC_Call,
9179 Cand1.ExplicitCallArguments,
9180 Cand2.ExplicitCallArguments))
9181 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9182 }
9183
9184 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9185 // A derived-class constructor beats an (inherited) base class constructor.
9186 bool Cand1IsInherited =
9187 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9188 bool Cand2IsInherited =
9189 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9190 if (Cand1IsInherited != Cand2IsInherited)
9191 return Cand2IsInherited;
9192 else if (Cand1IsInherited) {
9193 assert(Cand2IsInherited)(static_cast <bool> (Cand2IsInherited) ? void (0) : __assert_fail
("Cand2IsInherited", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9193, __extension__ __PRETTY_FUNCTION__))
;
9194 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9195 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9196 if (Cand1Class->isDerivedFrom(Cand2Class))
9197 return true;
9198 if (Cand2Class->isDerivedFrom(Cand1Class))
9199 return false;
9200 // Inherited from sibling base classes: still ambiguous.
9201 }
9202
9203 // Check C++17 tie-breakers for deduction guides.
9204 {
9205 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9206 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9207 if (Guide1 && Guide2) {
9208 // -- F1 is generated from a deduction-guide and F2 is not
9209 if (Guide1->isImplicit() != Guide2->isImplicit())
9210 return Guide2->isImplicit();
9211
9212 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9213 if (Guide1->isCopyDeductionCandidate())
9214 return true;
9215 }
9216 }
9217
9218 // Check for enable_if value-based overload resolution.
9219 if (Cand1.Function && Cand2.Function) {
9220 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9221 if (Cmp != Comparison::Equal)
9222 return Cmp == Comparison::Better;
9223 }
9224
9225 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9226 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9227 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9228 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9229 }
9230
9231 bool HasPS1 = Cand1.Function != nullptr &&
9232 functionHasPassObjectSizeParams(Cand1.Function);
9233 bool HasPS2 = Cand2.Function != nullptr &&
9234 functionHasPassObjectSizeParams(Cand2.Function);
9235 if (HasPS1 != HasPS2 && HasPS1)
9236 return true;
9237
9238 return isBetterMultiversionCandidate(Cand1, Cand2);
9239}
9240
9241/// Determine whether two declarations are "equivalent" for the purposes of
9242/// name lookup and overload resolution. This applies when the same internal/no
9243/// linkage entity is defined by two modules (probably by textually including
9244/// the same header). In such a case, we don't consider the declarations to
9245/// declare the same entity, but we also don't want lookups with both
9246/// declarations visible to be ambiguous in some cases (this happens when using
9247/// a modularized libstdc++).
9248bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9249 const NamedDecl *B) {
9250 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9251 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9252 if (!VA || !VB)
9253 return false;
9254
9255 // The declarations must be declaring the same name as an internal linkage
9256 // entity in different modules.
9257 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9258 VB->getDeclContext()->getRedeclContext()) ||
9259 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9260 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9261 VA->isExternallyVisible() || VB->isExternallyVisible())
9262 return false;
9263
9264 // Check that the declarations appear to be equivalent.
9265 //
9266 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9267 // For constants and functions, we should check the initializer or body is
9268 // the same. For non-constant variables, we shouldn't allow it at all.
9269 if (Context.hasSameType(VA->getType(), VB->getType()))
9270 return true;
9271
9272 // Enum constants within unnamed enumerations will have different types, but
9273 // may still be similar enough to be interchangeable for our purposes.
9274 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9275 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9276 // Only handle anonymous enums. If the enumerations were named and
9277 // equivalent, they would have been merged to the same type.
9278 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9279 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9280 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9281 !Context.hasSameType(EnumA->getIntegerType(),
9282 EnumB->getIntegerType()))
9283 return false;
9284 // Allow this only if the value is the same for both enumerators.
9285 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9286 }
9287 }
9288
9289 // Nothing else is sufficiently similar.
9290 return false;
9291}
9292
9293void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9294 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9295 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9296
9297 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9298 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9299 << !M << (M ? M->getFullModuleName() : "");
9300
9301 for (auto *E : Equiv) {
9302 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9303 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9304 << !M << (M ? M->getFullModuleName() : "");
9305 }
9306}
9307
9308/// Computes the best viable function (C++ 13.3.3)
9309/// within an overload candidate set.
9310///
9311/// \param Loc The location of the function name (or operator symbol) for
9312/// which overload resolution occurs.
9313///
9314/// \param Best If overload resolution was successful or found a deleted
9315/// function, \p Best points to the candidate function found.
9316///
9317/// \returns The result of overload resolution.
9318OverloadingResult
9319OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9320 iterator &Best) {
9321 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9322 std::transform(begin(), end(), std::back_inserter(Candidates),
9323 [](OverloadCandidate &Cand) { return &Cand; });
9324
9325 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9326 // are accepted by both clang and NVCC. However, during a particular
9327 // compilation mode only one call variant is viable. We need to
9328 // exclude non-viable overload candidates from consideration based
9329 // only on their host/device attributes. Specifically, if one
9330 // candidate call is WrongSide and the other is SameSide, we ignore
9331 // the WrongSide candidate.
9332 if (S.getLangOpts().CUDA) {
9333 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9334 bool ContainsSameSideCandidate =
9335 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9336 return Cand->Function &&
9337 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9338 Sema::CFP_SameSide;
9339 });
9340 if (ContainsSameSideCandidate) {
9341 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9342 return Cand->Function &&
9343 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9344 Sema::CFP_WrongSide;
9345 };
9346 llvm::erase_if(Candidates, IsWrongSideCandidate);
9347 }
9348 }
9349
9350 // Find the best viable function.
9351 Best = end();
9352 for (auto *Cand : Candidates)
9353 if (Cand->Viable)
9354 if (Best == end() ||
9355 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9356 Best = Cand;
9357
9358 // If we didn't find any viable functions, abort.
9359 if (Best == end())
9360 return OR_No_Viable_Function;
9361
9362 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9363
9364 // Make sure that this function is better than every other viable
9365 // function. If not, we have an ambiguity.
9366 for (auto *Cand : Candidates) {
9367 if (Cand->Viable && Cand != Best &&
9368 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9369 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9370 Cand->Function)) {
9371 EquivalentCands.push_back(Cand->Function);
9372 continue;
9373 }
9374
9375 Best = end();
9376 return OR_Ambiguous;
9377 }
9378 }
9379
9380 // Best is the best viable function.
9381 if (Best->Function &&
9382 (Best->Function->isDeleted() ||
9383 S.isFunctionConsideredUnavailable(Best->Function)))
9384 return OR_Deleted;
9385
9386 if (!EquivalentCands.empty())
9387 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9388 EquivalentCands);
9389
9390 return OR_Success;
9391}
9392
9393namespace {
9394
9395enum OverloadCandidateKind {
9396 oc_function,
9397 oc_method,
9398 oc_constructor,
9399 oc_implicit_default_constructor,
9400 oc_implicit_copy_constructor,
9401 oc_implicit_move_constructor,
9402 oc_implicit_copy_assignment,
9403 oc_implicit_move_assignment,
9404 oc_inherited_constructor
9405};
9406
9407enum OverloadCandidateSelect {
9408 ocs_non_template,
9409 ocs_template,
9410 ocs_described_template,
9411};
9412
9413static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9414ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9415 std::string &Description) {
9416
9417 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9418 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9419 isTemplate = true;
9420 Description = S.getTemplateArgumentBindingsText(
9421 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9422 }
9423
9424 OverloadCandidateSelect Select = [&]() {
9425 if (!Description.empty())
9426 return ocs_described_template;
9427 return isTemplate ? ocs_template : ocs_non_template;
9428 }();
9429
9430 OverloadCandidateKind Kind = [&]() {
9431 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9432 if (!Ctor->isImplicit()) {
9433 if (isa<ConstructorUsingShadowDecl>(Found))
9434 return oc_inherited_constructor;
9435 else
9436 return oc_constructor;
9437 }
9438
9439 if (Ctor->isDefaultConstructor())
9440 return oc_implicit_default_constructor;
9441
9442 if (Ctor->isMoveConstructor())
9443 return oc_implicit_move_constructor;
9444
9445 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9446, __extension__ __PRETTY_FUNCTION__))
9446 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9446, __extension__ __PRETTY_FUNCTION__))
;
9447 return oc_implicit_copy_constructor;
9448 }
9449
9450 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9451 // This actually gets spelled 'candidate function' for now, but
9452 // it doesn't hurt to split it out.
9453 if (!Meth->isImplicit())
9454 return oc_method;
9455
9456 if (Meth->isMoveAssignmentOperator())
9457 return oc_implicit_move_assignment;
9458
9459 if (Meth->isCopyAssignmentOperator())
9460 return oc_implicit_copy_assignment;
9461
9462 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9462, __extension__ __PRETTY_FUNCTION__))
;
9463 return oc_method;
9464 }
9465
9466 return oc_function;
9467 }();
9468
9469 return std::make_pair(Kind, Select);
9470}
9471
9472void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9473 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9474 // set.
9475 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9476 S.Diag(FoundDecl->getLocation(),
9477 diag::note_ovl_candidate_inherited_constructor)
9478 << Shadow->getNominatedBaseClass();
9479}
9480
9481} // end anonymous namespace
9482
9483static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9484 const FunctionDecl *FD) {
9485 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9486 bool AlwaysTrue;
9487 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9488 return false;
9489 if (!AlwaysTrue)
9490 return false;
9491 }
9492 return true;
9493}
9494
9495/// Returns true if we can take the address of the function.
9496///
9497/// \param Complain - If true, we'll emit a diagnostic
9498/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9499/// we in overload resolution?
9500/// \param Loc - The location of the statement we're complaining about. Ignored
9501/// if we're not complaining, or if we're in overload resolution.
9502static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9503 bool Complain,
9504 bool InOverloadResolution,
9505 SourceLocation Loc) {
9506 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9507 if (Complain) {
9508 if (InOverloadResolution)
9509 S.Diag(FD->getLocStart(),
9510 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9511 else
9512 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9513 }
9514 return false;
9515 }
9516
9517 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9518 return P->hasAttr<PassObjectSizeAttr>();
9519 });
9520 if (I == FD->param_end())
9521 return true;
9522
9523 if (Complain) {
9524 // Add one to ParamNo because it's user-facing
9525 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9526 if (InOverloadResolution)
9527 S.Diag(FD->getLocation(),
9528 diag::note_ovl_candidate_has_pass_object_size_params)
9529 << ParamNo;
9530 else
9531 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9532 << FD << ParamNo;
9533 }
9534 return false;
9535}
9536
9537static bool checkAddressOfCandidateIsAvailable(Sema &S,
9538 const FunctionDecl *FD) {
9539 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9540 /*InOverloadResolution=*/true,
9541 /*Loc=*/SourceLocation());
9542}
9543
9544bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9545 bool Complain,
9546 SourceLocation Loc) {
9547 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9548 /*InOverloadResolution=*/false,
9549 Loc);
9550}
9551
9552// Notes the location of an overload candidate.
9553void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9554 QualType DestType, bool TakingAddress) {
9555 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9556 return;
9557 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9558 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9559 return;
9560
9561 std::string FnDesc;
9562 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9563 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9564 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9565 << (unsigned)KSPair.first << (unsigned)KSPair.second
9566 << Fn << FnDesc;
9567
9568 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9569 Diag(Fn->getLocation(), PD);
9570 MaybeEmitInheritedConstructorNote(*this, Found);
9571}
9572
9573// Notes the location of all overload candidates designated through
9574// OverloadedExpr
9575void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9576 bool TakingAddress) {
9577 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9577, __extension__ __PRETTY_FUNCTION__))
;
9578
9579 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9580 OverloadExpr *OvlExpr = Ovl.Expression;
9581
9582 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9583 IEnd = OvlExpr->decls_end();
9584 I != IEnd; ++I) {
9585 if (FunctionTemplateDecl *FunTmpl =
9586 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9587 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9588 TakingAddress);
9589 } else if (FunctionDecl *Fun
9590 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9591 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9592 }
9593 }
9594}
9595
9596/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9597/// "lead" diagnostic; it will be given two arguments, the source and
9598/// target types of the conversion.
9599void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9600 Sema &S,
9601 SourceLocation CaretLoc,
9602 const PartialDiagnostic &PDiag) const {
9603 S.Diag(CaretLoc, PDiag)
9604 << Ambiguous.getFromType() << Ambiguous.getToType();
9605 // FIXME: The note limiting machinery is borrowed from
9606 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9607 // refactoring here.
9608 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9609 unsigned CandsShown = 0;
9610 AmbiguousConversionSequence::const_iterator I, E;
9611 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9612 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9613 break;
9614 ++CandsShown;
9615 S.NoteOverloadCandidate(I->first, I->second);
9616 }
9617 if (I != E)
9618 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9619}
9620
9621static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9622 unsigned I, bool TakingCandidateAddress) {
9623 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9624 assert(Conv.isBad())(static_cast <bool> (Conv.isBad()) ? void (0) : __assert_fail
("Conv.isBad()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9624, __extension__ __PRETTY_FUNCTION__))
;
9625 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9625, __extension__ __PRETTY_FUNCTION__))
;
9626 FunctionDecl *Fn = Cand->Function;
9627
9628 // There's a conversion slot for the object argument if this is a
9629 // non-constructor method. Note that 'I' corresponds the
9630 // conversion-slot index.
9631 bool isObjectArgument = false;
9632 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9633 if (I == 0)
9634 isObjectArgument = true;
9635 else
9636 I--;
9637 }
9638
9639 std::string FnDesc;
9640 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9641 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9642
9643 Expr *FromExpr = Conv.Bad.FromExpr;
9644 QualType FromTy = Conv.Bad.getFromType();
9645 QualType ToTy = Conv.Bad.getToType();
9646
9647 if (FromTy == S.Context.OverloadTy) {
9648 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9648, __extension__ __PRETTY_FUNCTION__))
;
9649 Expr *E = FromExpr->IgnoreParens();
9650 if (isa<UnaryOperator>(E))
9651 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9652 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9653
9654 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9655 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9656 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9657 << Name << I + 1;
9658 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9659 return;
9660 }
9661
9662 // Do some hand-waving analysis to see if the non-viability is due
9663 // to a qualifier mismatch.
9664 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9665 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9666 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9667 CToTy = RT->getPointeeType();
9668 else {
9669 // TODO: detect and diagnose the full richness of const mismatches.
9670 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9671 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9672 CFromTy = FromPT->getPointeeType();
9673 CToTy = ToPT->getPointeeType();
9674 }
9675 }
9676
9677 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9678 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9679 Qualifiers FromQs = CFromTy.getQualifiers();
9680 Qualifiers ToQs = CToTy.getQualifiers();
9681
9682 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9683 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9684 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9685 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9686 << ToTy << (unsigned)isObjectArgument << I + 1;
9687 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9688 return;
9689 }
9690
9691 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9692 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9693 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9694 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9695 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9696 << (unsigned)isObjectArgument << I + 1;
9697 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9698 return;
9699 }
9700
9701 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9702 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9703 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9704 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9705 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9706 << (unsigned)isObjectArgument << I + 1;
9707 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9708 return;
9709 }
9710
9711 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9712 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9713 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9714 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9715 << FromQs.hasUnaligned() << I + 1;
9716 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9717 return;
9718 }
9719
9720 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9721 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9721, __extension__ __PRETTY_FUNCTION__))
;
9722
9723 if (isObjectArgument) {
9724 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9725 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9726 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9727 << (CVR - 1);
9728 } else {
9729 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9730 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9731 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9732 << (CVR - 1) << I + 1;
9733 }
9734 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9735 return;
9736 }
9737
9738 // Special diagnostic for failure to convert an initializer list, since
9739 // telling the user that it has type void is not useful.
9740 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9741 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9742 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9743 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9744 << ToTy << (unsigned)isObjectArgument << I + 1;
9745 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9746 return;
9747 }
9748
9749 // Diagnose references or pointers to incomplete types differently,
9750 // since it's far from impossible that the incompleteness triggered
9751 // the failure.
9752 QualType TempFromTy = FromTy.getNonReferenceType();
9753 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9754 TempFromTy = PTy->getPointeeType();
9755 if (TempFromTy->isIncompleteType()) {
9756 // Emit the generic diagnostic and, optionally, add the hints to it.
9757 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9758 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9759 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9760 << ToTy << (unsigned)isObjectArgument << I + 1
9761 << (unsigned)(Cand->Fix.Kind);
9762
9763 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9764 return;
9765 }
9766
9767 // Diagnose base -> derived pointer conversions.
9768 unsigned BaseToDerivedConversion = 0;
9769 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9770 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9771 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9772 FromPtrTy->getPointeeType()) &&
9773 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9774 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9775 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9776 FromPtrTy->getPointeeType()))
9777 BaseToDerivedConversion = 1;
9778 }
9779 } else if (const ObjCObjectPointerType *FromPtrTy
9780 = FromTy->getAs<ObjCObjectPointerType>()) {
9781 if (const ObjCObjectPointerType *ToPtrTy
9782 = ToTy->getAs<ObjCObjectPointerType>())
9783 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9784 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9785 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9786 FromPtrTy->getPointeeType()) &&
9787 FromIface->isSuperClassOf(ToIface))
9788 BaseToDerivedConversion = 2;
9789 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9790 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9791 !FromTy->isIncompleteType() &&
9792 !ToRefTy->getPointeeType()->isIncompleteType() &&
9793 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9794 BaseToDerivedConversion = 3;
9795 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9796 ToTy.getNonReferenceType().getCanonicalType() ==
9797 FromTy.getNonReferenceType().getCanonicalType()) {
9798 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9799 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9800 << (unsigned)isObjectArgument << I + 1
9801 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9802 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9803 return;
9804 }
9805 }
9806
9807 if (BaseToDerivedConversion) {
9808 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9809 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9810 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9811 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9812 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9813 return;
9814 }
9815
9816 if (isa<ObjCObjectPointerType>(CFromTy) &&
9817 isa<PointerType>(CToTy)) {
9818 Qualifiers FromQs = CFromTy.getQualifiers();
9819 Qualifiers ToQs = CToTy.getQualifiers();
9820 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9821 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9822 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9823 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9824 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9825 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9826 return;
9827 }
9828 }
9829
9830 if (TakingCandidateAddress &&
9831 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9832 return;
9833
9834 // Emit the generic diagnostic and, optionally, add the hints to it.
9835 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9836 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9837 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9838 << ToTy << (unsigned)isObjectArgument << I + 1
9839 << (unsigned)(Cand->Fix.Kind);
9840
9841 // If we can fix the conversion, suggest the FixIts.
9842 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9843 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9844 FDiag << *HI;
9845 S.Diag(Fn->getLocation(), FDiag);
9846
9847 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9848}
9849
9850/// Additional arity mismatch diagnosis specific to a function overload
9851/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9852/// over a candidate in any candidate set.
9853static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9854 unsigned NumArgs) {
9855 FunctionDecl *Fn = Cand->Function;
9856 unsigned MinParams = Fn->getMinRequiredArguments();
9857
9858 // With invalid overloaded operators, it's possible that we think we
9859 // have an arity mismatch when in fact it looks like we have the
9860 // right number of arguments, because only overloaded operators have
9861 // the weird behavior of overloading member and non-member functions.
9862 // Just don't report anything.
9863 if (Fn->isInvalidDecl() &&
9864 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9865 return true;
9866
9867 if (NumArgs < MinParams) {
9868 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9870, __extension__ __PRETTY_FUNCTION__))
9869 (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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9870, __extension__ __PRETTY_FUNCTION__))
9870 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9870, __extension__ __PRETTY_FUNCTION__))
;
9871 } else {
9872 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9874, __extension__ __PRETTY_FUNCTION__))
9873 (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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9874, __extension__ __PRETTY_FUNCTION__))
9874 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9874, __extension__ __PRETTY_FUNCTION__))
;
9875 }
9876
9877 return false;
9878}
9879
9880/// General arity mismatch diagnosis over a candidate in a candidate set.
9881static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9882 unsigned NumFormalArgs) {
9883 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9886, __extension__ __PRETTY_FUNCTION__))
9884 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9886, __extension__ __PRETTY_FUNCTION__))
9885 " 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9886, __extension__ __PRETTY_FUNCTION__))
9886 " 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9886, __extension__ __PRETTY_FUNCTION__))
;
9887
9888 FunctionDecl *Fn = cast<FunctionDecl>(D);
9889
9890 // TODO: treat calls to a missing default constructor as a special case
9891 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9892 unsigned MinParams = Fn->getMinRequiredArguments();
9893
9894 // at least / at most / exactly
9895 unsigned mode, modeCount;
9896 if (NumFormalArgs < MinParams) {
9897 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9898 FnTy->isTemplateVariadic())
9899 mode = 0; // "at least"
9900 else
9901 mode = 2; // "exactly"
9902 modeCount = MinParams;
9903 } else {
9904 if (MinParams != FnTy->getNumParams())
9905 mode = 1; // "at most"
9906 else
9907 mode = 2; // "exactly"
9908 modeCount = FnTy->getNumParams();
9909 }
9910
9911 std::string Description;
9912 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9913 ClassifyOverloadCandidate(S, Found, Fn, Description);
9914
9915 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9916 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9917 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9918 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
9919 else
9920 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9921 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9922 << Description << mode << modeCount << NumFormalArgs;
9923
9924 MaybeEmitInheritedConstructorNote(S, Found);
9925}
9926
9927/// Arity mismatch diagnosis specific to a function overload candidate.
9928static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9929 unsigned NumFormalArgs) {
9930 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9931 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9932}
9933
9934static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9935 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9936 return TD;
9937 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9938)
9938 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9938)
;
9939}
9940
9941/// Diagnose a failed template-argument deduction.
9942static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9943 DeductionFailureInfo &DeductionFailure,
9944 unsigned NumArgs,
9945 bool TakingCandidateAddress) {
9946 TemplateParameter Param = DeductionFailure.getTemplateParameter();
9947 NamedDecl *ParamD;
9948 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9949 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9950 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9951 switch (DeductionFailure.Result) {
9952 case Sema::TDK_Success:
9953 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9953)
;
9954
9955 case Sema::TDK_Incomplete: {
9956 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9956, __extension__ __PRETTY_FUNCTION__))
;
9957 S.Diag(Templated->getLocation(),
9958 diag::note_ovl_candidate_incomplete_deduction)
9959 << ParamD->getDeclName();
9960 MaybeEmitInheritedConstructorNote(S, Found);
9961 return;
9962 }
9963
9964 case Sema::TDK_IncompletePack: {
9965 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9965, __extension__ __PRETTY_FUNCTION__))
;
9966 S.Diag(Templated->getLocation(),
9967 diag::note_ovl_candidate_incomplete_deduction_pack)
9968 << ParamD->getDeclName()
9969 << (DeductionFailure.getFirstArg()->pack_size() + 1)
9970 << *DeductionFailure.getFirstArg();
9971 MaybeEmitInheritedConstructorNote(S, Found);
9972 return;
9973 }
9974
9975 case Sema::TDK_Underqualified: {
9976 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9976, __extension__ __PRETTY_FUNCTION__))
;
9977 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9978
9979 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9980
9981 // Param will have been canonicalized, but it should just be a
9982 // qualified version of ParamD, so move the qualifiers to that.
9983 QualifierCollector Qs;
9984 Qs.strip(Param);
9985 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9986 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9986, __extension__ __PRETTY_FUNCTION__))
;
9987
9988 // Arg has also been canonicalized, but there's nothing we can do
9989 // about that. It also doesn't matter as much, because it won't
9990 // have any template parameters in it (because deduction isn't
9991 // done on dependent types).
9992 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9993
9994 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9995 << ParamD->getDeclName() << Arg << NonCanonParam;
9996 MaybeEmitInheritedConstructorNote(S, Found);
9997 return;
9998 }
9999
10000 case Sema::TDK_Inconsistent: {
10001 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10001, __extension__ __PRETTY_FUNCTION__))
;
10002 int which = 0;
10003 if (isa<TemplateTypeParmDecl>(ParamD))
10004 which = 0;
10005 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10006 // Deduction might have failed because we deduced arguments of two
10007 // different types for a non-type template parameter.
10008 // FIXME: Use a different TDK value for this.
10009 QualType T1 =
10010 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10011 QualType T2 =
10012 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10013 if (!S.Context.hasSameType(T1, T2)) {
10014 S.Diag(Templated->getLocation(),
10015 diag::note_ovl_candidate_inconsistent_deduction_types)
10016 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10017 << *DeductionFailure.getSecondArg() << T2;
10018 MaybeEmitInheritedConstructorNote(S, Found);
10019 return;
10020 }
10021
10022 which = 1;
10023 } else {
10024 which = 2;
10025 }
10026
10027 S.Diag(Templated->getLocation(),
10028 diag::note_ovl_candidate_inconsistent_deduction)
10029 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10030 << *DeductionFailure.getSecondArg();
10031 MaybeEmitInheritedConstructorNote(S, Found);
10032 return;
10033 }
10034
10035 case Sema::TDK_InvalidExplicitArguments:
10036 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10036, __extension__ __PRETTY_FUNCTION__))
;
10037 if (ParamD->getDeclName())
10038 S.Diag(Templated->getLocation(),
10039 diag::note_ovl_candidate_explicit_arg_mismatch_named)
10040 << ParamD->getDeclName();
10041 else {
10042 int index = 0;
10043 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10044 index = TTP->getIndex();
10045 else if (NonTypeTemplateParmDecl *NTTP
10046 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10047 index = NTTP->getIndex();
10048 else
10049 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10050 S.Diag(Templated->getLocation(),
10051 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10052 << (index + 1);
10053 }
10054 MaybeEmitInheritedConstructorNote(S, Found);
10055 return;
10056
10057 case Sema::TDK_TooManyArguments:
10058 case Sema::TDK_TooFewArguments:
10059 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10060 return;
10061
10062 case Sema::TDK_InstantiationDepth:
10063 S.Diag(Templated->getLocation(),
10064 diag::note_ovl_candidate_instantiation_depth);
10065 MaybeEmitInheritedConstructorNote(S, Found);
10066 return;
10067
10068 case Sema::TDK_SubstitutionFailure: {
10069 // Format the template argument list into the argument string.
10070 SmallString<128> TemplateArgString;
10071 if (TemplateArgumentList *Args =
10072 DeductionFailure.getTemplateArgumentList()) {
10073 TemplateArgString = " ";
10074 TemplateArgString += S.getTemplateArgumentBindingsText(
10075 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10076 }
10077
10078 // If this candidate was disabled by enable_if, say so.
10079 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10080 if (PDiag && PDiag->second.getDiagID() ==
10081 diag::err_typename_nested_not_found_enable_if) {
10082 // FIXME: Use the source range of the condition, and the fully-qualified
10083 // name of the enable_if template. These are both present in PDiag.
10084 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10085 << "'enable_if'" << TemplateArgString;
10086 return;
10087 }
10088
10089 // We found a specific requirement that disabled the enable_if.
10090 if (PDiag && PDiag->second.getDiagID() ==
10091 diag::err_typename_nested_not_found_requirement) {
10092 S.Diag(Templated->getLocation(),
10093 diag::note_ovl_candidate_disabled_by_requirement)
10094 << PDiag->second.getStringArg(0) << TemplateArgString;
10095 return;
10096 }
10097
10098 // Format the SFINAE diagnostic into the argument string.
10099 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10100 // formatted message in another diagnostic.
10101 SmallString<128> SFINAEArgString;
10102 SourceRange R;
10103 if (PDiag) {
10104 SFINAEArgString = ": ";
10105 R = SourceRange(PDiag->first, PDiag->first);
10106 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10107 }
10108
10109 S.Diag(Templated->getLocation(),
10110 diag::note_ovl_candidate_substitution_failure)
10111 << TemplateArgString << SFINAEArgString << R;
10112 MaybeEmitInheritedConstructorNote(S, Found);
10113 return;
10114 }
10115
10116 case Sema::TDK_DeducedMismatch:
10117 case Sema::TDK_DeducedMismatchNested: {
10118 // Format the template argument list into the argument string.
10119 SmallString<128> TemplateArgString;
10120 if (TemplateArgumentList *Args =
10121 DeductionFailure.getTemplateArgumentList()) {
10122 TemplateArgString = " ";
10123 TemplateArgString += S.getTemplateArgumentBindingsText(
10124 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10125 }
10126
10127 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10128 << (*DeductionFailure.getCallArgIndex() + 1)
10129 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10130 << TemplateArgString
10131 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10132 break;
10133 }
10134
10135 case Sema::TDK_NonDeducedMismatch: {
10136 // FIXME: Provide a source location to indicate what we couldn't match.
10137 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10138 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10139 if (FirstTA.getKind() == TemplateArgument::Template &&
10140 SecondTA.getKind() == TemplateArgument::Template) {
10141 TemplateName FirstTN = FirstTA.getAsTemplate();
10142 TemplateName SecondTN = SecondTA.getAsTemplate();
10143 if (FirstTN.getKind() == TemplateName::Template &&
10144 SecondTN.getKind() == TemplateName::Template) {
10145 if (FirstTN.getAsTemplateDecl()->getName() ==
10146 SecondTN.getAsTemplateDecl()->getName()) {
10147 // FIXME: This fixes a bad diagnostic where both templates are named
10148 // the same. This particular case is a bit difficult since:
10149 // 1) It is passed as a string to the diagnostic printer.
10150 // 2) The diagnostic printer only attempts to find a better
10151 // name for types, not decls.
10152 // Ideally, this should folded into the diagnostic printer.
10153 S.Diag(Templated->getLocation(),
10154 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10155 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10156 return;
10157 }
10158 }
10159 }
10160
10161 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10162 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10163 return;
10164
10165 // FIXME: For generic lambda parameters, check if the function is a lambda
10166 // call operator, and if so, emit a prettier and more informative
10167 // diagnostic that mentions 'auto' and lambda in addition to
10168 // (or instead of?) the canonical template type parameters.
10169 S.Diag(Templated->getLocation(),
10170 diag::note_ovl_candidate_non_deduced_mismatch)
10171 << FirstTA << SecondTA;
10172 return;
10173 }
10174 // TODO: diagnose these individually, then kill off
10175 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10176 case Sema::TDK_MiscellaneousDeductionFailure:
10177 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10178 MaybeEmitInheritedConstructorNote(S, Found);
10179 return;
10180 case Sema::TDK_CUDATargetMismatch:
10181 S.Diag(Templated->getLocation(),
10182 diag::note_cuda_ovl_candidate_target_mismatch);
10183 return;
10184 }
10185}
10186
10187/// Diagnose a failed template-argument deduction, for function calls.
10188static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10189 unsigned NumArgs,
10190 bool TakingCandidateAddress) {
10191 unsigned TDK = Cand->DeductionFailure.Result;
10192 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10193 if (CheckArityMismatch(S, Cand, NumArgs))
10194 return;
10195 }
10196 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10197 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10198}
10199
10200/// CUDA: diagnose an invalid call across targets.
10201static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10202 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10203 FunctionDecl *Callee = Cand->Function;
10204
10205 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10206 CalleeTarget = S.IdentifyCUDATarget(Callee);
10207
10208 std::string FnDesc;
10209 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10210 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10211
10212 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10213 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10214 << FnDesc /* Ignored */
10215 << CalleeTarget << CallerTarget;
10216
10217 // This could be an implicit constructor for which we could not infer the
10218 // target due to a collsion. Diagnose that case.
10219 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10220 if (Meth != nullptr && Meth->isImplicit()) {
10221 CXXRecordDecl *ParentClass = Meth->getParent();
10222 Sema::CXXSpecialMember CSM;
10223
10224 switch (FnKindPair.first) {
10225 default:
10226 return;
10227 case oc_implicit_default_constructor:
10228 CSM = Sema::CXXDefaultConstructor;
10229 break;
10230 case oc_implicit_copy_constructor:
10231 CSM = Sema::CXXCopyConstructor;
10232 break;
10233 case oc_implicit_move_constructor:
10234 CSM = Sema::CXXMoveConstructor;
10235 break;
10236 case oc_implicit_copy_assignment:
10237 CSM = Sema::CXXCopyAssignment;
10238 break;
10239 case oc_implicit_move_assignment:
10240 CSM = Sema::CXXMoveAssignment;
10241 break;
10242 };
10243
10244 bool ConstRHS = false;
10245 if (Meth->getNumParams()) {
10246 if (const ReferenceType *RT =
10247 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10248 ConstRHS = RT->getPointeeType().isConstQualified();
10249 }
10250 }
10251
10252 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10253 /* ConstRHS */ ConstRHS,
10254 /* Diagnose */ true);
10255 }
10256}
10257
10258static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10259 FunctionDecl *Callee = Cand->Function;
10260 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10261
10262 S.Diag(Callee->getLocation(),
10263 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10264 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10265}
10266
10267static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10268 FunctionDecl *Callee = Cand->Function;
10269
10270 S.Diag(Callee->getLocation(),
10271 diag::note_ovl_candidate_disabled_by_extension);
10272}
10273
10274/// Generates a 'note' diagnostic for an overload candidate. We've
10275/// already generated a primary error at the call site.
10276///
10277/// It really does need to be a single diagnostic with its caret
10278/// pointed at the candidate declaration. Yes, this creates some
10279/// major challenges of technical writing. Yes, this makes pointing
10280/// out problems with specific arguments quite awkward. It's still
10281/// better than generating twenty screens of text for every failed
10282/// overload.
10283///
10284/// It would be great to be able to express per-candidate problems
10285/// more richly for those diagnostic clients that cared, but we'd
10286/// still have to be just as careful with the default diagnostics.
10287static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10288 unsigned NumArgs,
10289 bool TakingCandidateAddress) {
10290 FunctionDecl *Fn = Cand->Function;
10291
10292 // Note deleted candidates, but only if they're viable.
10293 if (Cand->Viable) {
10294 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) {
10295 std::string FnDesc;
10296 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10297 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10298
10299 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10300 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10301 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10302 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10303 return;
10304 }
10305
10306 // We don't really have anything else to say about viable candidates.
10307 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10308 return;
10309 }
10310
10311 switch (Cand->FailureKind) {
10312 case ovl_fail_too_many_arguments:
10313 case ovl_fail_too_few_arguments:
10314 return DiagnoseArityMismatch(S, Cand, NumArgs);
10315
10316 case ovl_fail_bad_deduction:
10317 return DiagnoseBadDeduction(S, Cand, NumArgs,
10318 TakingCandidateAddress);
10319
10320 case ovl_fail_illegal_constructor: {
10321 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10322 << (Fn->getPrimaryTemplate() ? 1 : 0);
10323 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10324 return;
10325 }
10326
10327 case ovl_fail_trivial_conversion:
10328 case ovl_fail_bad_final_conversion:
10329 case ovl_fail_final_conversion_not_exact:
10330 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10331
10332 case ovl_fail_bad_conversion: {
10333 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10334 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10335 if (Cand->Conversions[I].isBad())
10336 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10337
10338 // FIXME: this currently happens when we're called from SemaInit
10339 // when user-conversion overload fails. Figure out how to handle
10340 // those conditions and diagnose them well.
10341 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10342 }
10343
10344 case ovl_fail_bad_target:
10345 return DiagnoseBadTarget(S, Cand);
10346
10347 case ovl_fail_enable_if:
10348 return DiagnoseFailedEnableIfAttr(S, Cand);
10349
10350 case ovl_fail_ext_disabled:
10351 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10352
10353 case ovl_fail_inhctor_slice:
10354 // It's generally not interesting to note copy/move constructors here.
10355 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10356 return;
10357 S.Diag(Fn->getLocation(),
10358 diag::note_ovl_candidate_inherited_constructor_slice)
10359 << (Fn->getPrimaryTemplate() ? 1 : 0)
10360 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10361 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10362 return;
10363
10364 case ovl_fail_addr_not_available: {
10365 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10366 (void)Available;
10367 assert(!Available)(static_cast <bool> (!Available) ? void (0) : __assert_fail
("!Available", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10367, __extension__ __PRETTY_FUNCTION__))
;
10368 break;
10369 }
10370 case ovl_non_default_multiversion_function:
10371 // Do nothing, these should simply be ignored.
10372 break;
10373 }
10374}
10375
10376static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10377 // Desugar the type of the surrogate down to a function type,
10378 // retaining as many typedefs as possible while still showing
10379 // the function type (and, therefore, its parameter types).
10380 QualType FnType = Cand->Surrogate->getConversionType();
10381 bool isLValueReference = false;
10382 bool isRValueReference = false;
10383 bool isPointer = false;
10384 if (const LValueReferenceType *FnTypeRef =
10385 FnType->getAs<LValueReferenceType>()) {
10386 FnType = FnTypeRef->getPointeeType();
10387 isLValueReference = true;
10388 } else if (const RValueReferenceType *FnTypeRef =
10389 FnType->getAs<RValueReferenceType>()) {
10390 FnType = FnTypeRef->getPointeeType();
10391 isRValueReference = true;
10392 }
10393 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10394 FnType = FnTypePtr->getPointeeType();
10395 isPointer = true;
10396 }
10397 // Desugar down to a function type.
10398 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10399 // Reconstruct the pointer/reference as appropriate.
10400 if (isPointer) FnType = S.Context.getPointerType(FnType);
10401 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10402 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10403
10404 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10405 << FnType;
10406}
10407
10408static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10409 SourceLocation OpLoc,
10410 OverloadCandidate *Cand) {
10411 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10411, __extension__ __PRETTY_FUNCTION__))
;
10412 std::string TypeStr("operator");
10413 TypeStr += Opc;
10414 TypeStr += "(";
10415 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10416 if (Cand->Conversions.size() == 1) {
10417 TypeStr += ")";
10418 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10419 } else {
10420 TypeStr += ", ";
10421 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10422 TypeStr += ")";
10423 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10424 }
10425}
10426
10427static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10428 OverloadCandidate *Cand) {
10429 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10430 if (ICS.isBad()) break; // all meaningless after first invalid
10431 if (!ICS.isAmbiguous()) continue;
10432
10433 ICS.DiagnoseAmbiguousConversion(
10434 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10435 }
10436}
10437
10438static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10439 if (Cand->Function)
10440 return Cand->Function->getLocation();
10441 if (Cand->IsSurrogate)
10442 return Cand->Surrogate->getLocation();
10443 return SourceLocation();
10444}
10445
10446static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10447 switch ((Sema::TemplateDeductionResult)DFI.Result) {
10448 case Sema::TDK_Success:
10449 case Sema::TDK_NonDependentConversionFailure:
10450 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10450)
;
10451
10452 case Sema::TDK_Invalid:
10453 case Sema::TDK_Incomplete:
10454 case Sema::TDK_IncompletePack:
10455 return 1;
10456
10457 case Sema::TDK_Underqualified:
10458 case Sema::TDK_Inconsistent:
10459 return 2;
10460
10461 case Sema::TDK_SubstitutionFailure:
10462 case Sema::TDK_DeducedMismatch:
10463 case Sema::TDK_DeducedMismatchNested:
10464 case Sema::TDK_NonDeducedMismatch:
10465 case Sema::TDK_MiscellaneousDeductionFailure:
10466 case Sema::TDK_CUDATargetMismatch:
10467 return 3;
10468
10469 case Sema::TDK_InstantiationDepth:
10470 return 4;
10471
10472 case Sema::TDK_InvalidExplicitArguments:
10473 return 5;
10474
10475 case Sema::TDK_TooManyArguments:
10476 case Sema::TDK_TooFewArguments:
10477 return 6;
10478 }
10479 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10479)
;
10480}
10481
10482namespace {
10483struct CompareOverloadCandidatesForDisplay {
10484 Sema &S;
10485 SourceLocation Loc;
10486 size_t NumArgs;
10487 OverloadCandidateSet::CandidateSetKind CSK;
10488
10489 CompareOverloadCandidatesForDisplay(
10490 Sema &S, SourceLocation Loc, size_t NArgs,
10491 OverloadCandidateSet::CandidateSetKind CSK)
10492 : S(S), NumArgs(NArgs), CSK(CSK) {}
10493
10494 bool operator()(const OverloadCandidate *L,
10495 const OverloadCandidate *R) {
10496 // Fast-path this check.
10497 if (L == R) return false;
10498
10499 // Order first by viability.
10500 if (L->Viable) {
10501 if (!R->Viable) return true;
10502
10503 // TODO: introduce a tri-valued comparison for overload
10504 // candidates. Would be more worthwhile if we had a sort
10505 // that could exploit it.
10506 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10507 return true;
10508 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10509 return false;
10510 } else if (R->Viable)
10511 return false;
10512
10513 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10513, __extension__ __PRETTY_FUNCTION__))
;
10514
10515 // Criteria by which we can sort non-viable candidates:
10516 if (!L->Viable) {
10517 // 1. Arity mismatches come after other candidates.
10518 if (L->FailureKind == ovl_fail_too_many_arguments ||
10519 L->FailureKind == ovl_fail_too_few_arguments) {
10520 if (R->FailureKind == ovl_fail_too_many_arguments ||
10521 R->FailureKind == ovl_fail_too_few_arguments) {
10522 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10523 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10524 if (LDist == RDist) {
10525 if (L->FailureKind == R->FailureKind)
10526 // Sort non-surrogates before surrogates.
10527 return !L->IsSurrogate && R->IsSurrogate;
10528 // Sort candidates requiring fewer parameters than there were
10529 // arguments given after candidates requiring more parameters
10530 // than there were arguments given.
10531 return L->FailureKind == ovl_fail_too_many_arguments;
10532 }
10533 return LDist < RDist;
10534 }
10535 return false;
10536 }
10537 if (R->FailureKind == ovl_fail_too_many_arguments ||
10538 R->FailureKind == ovl_fail_too_few_arguments)
10539 return true;
10540
10541 // 2. Bad conversions come first and are ordered by the number
10542 // of bad conversions and quality of good conversions.
10543 if (L->FailureKind == ovl_fail_bad_conversion) {
10544 if (R->FailureKind != ovl_fail_bad_conversion)
10545 return true;
10546
10547 // The conversion that can be fixed with a smaller number of changes,
10548 // comes first.
10549 unsigned numLFixes = L->Fix.NumConversionsFixed;
10550 unsigned numRFixes = R->Fix.NumConversionsFixed;
10551 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes;
10552 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes;
10553 if (numLFixes != numRFixes) {
10554 return numLFixes < numRFixes;
10555 }
10556
10557 // If there's any ordering between the defined conversions...
10558 // FIXME: this might not be transitive.
10559 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10559, __extension__ __PRETTY_FUNCTION__))
;
10560
10561 int leftBetter = 0;
10562 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10563 for (unsigned E = L->Conversions.size(); I != E; ++I) {
10564 switch (CompareImplicitConversionSequences(S, Loc,
10565 L->Conversions[I],
10566 R->Conversions[I])) {
10567 case ImplicitConversionSequence::Better:
10568 leftBetter++;
10569 break;
10570
10571 case ImplicitConversionSequence::Worse:
10572 leftBetter--;
10573 break;
10574
10575 case ImplicitConversionSequence::Indistinguishable:
10576 break;
10577 }
10578 }
10579 if (leftBetter > 0) return true;
10580 if (leftBetter < 0) return false;
10581
10582 } else if (R->FailureKind == ovl_fail_bad_conversion)
10583 return false;
10584
10585 if (L->FailureKind == ovl_fail_bad_deduction) {
10586 if (R->FailureKind != ovl_fail_bad_deduction)
10587 return true;
10588
10589 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10590 return RankDeductionFailure(L->DeductionFailure)
10591 < RankDeductionFailure(R->DeductionFailure);
10592 } else if (R->FailureKind == ovl_fail_bad_deduction)
10593 return false;
10594
10595 // TODO: others?
10596 }
10597
10598 // Sort everything else by location.
10599 SourceLocation LLoc = GetLocationForCandidate(L);
10600 SourceLocation RLoc = GetLocationForCandidate(R);
10601
10602 // Put candidates without locations (e.g. builtins) at the end.
10603 if (LLoc.isInvalid()) return false;
10604 if (RLoc.isInvalid()) return true;
10605
10606 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10607 }
10608};
10609}
10610
10611/// CompleteNonViableCandidate - Normally, overload resolution only
10612/// computes up to the first bad conversion. Produces the FixIt set if
10613/// possible.
10614static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10615 ArrayRef<Expr *> Args) {
10616 assert(!Cand->Viable)(static_cast <bool> (!Cand->Viable) ? void (0) : __assert_fail
("!Cand->Viable", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10616, __extension__ __PRETTY_FUNCTION__))
;
10617
10618 // Don't do anything on failures other than bad conversion.
10619 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10620
10621 // We only want the FixIts if all the arguments can be corrected.
10622 bool Unfixable = false;
10623 // Use a implicit copy initialization to check conversion fixes.
10624 Cand->Fix.setConversionChecker(TryCopyInitialization);
10625
10626 // Attempt to fix the bad conversion.
10627 unsigned ConvCount = Cand->Conversions.size();
10628 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10629 ++ConvIdx) {
10630 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10630, __extension__ __PRETTY_FUNCTION__))
;
10631 if (Cand->Conversions[ConvIdx].isInitialized() &&
10632 Cand->Conversions[ConvIdx].isBad()) {
10633 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10634 break;
10635 }
10636 }
10637
10638 // FIXME: this should probably be preserved from the overload
10639 // operation somehow.
10640 bool SuppressUserConversions = false;
10641
10642 unsigned ConvIdx = 0;
10643 ArrayRef<QualType> ParamTypes;
10644
10645 if (Cand->IsSurrogate) {
10646 QualType ConvType
10647 = Cand->Surrogate->getConversionType().getNonReferenceType();
10648 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10649 ConvType = ConvPtrType->getPointeeType();
10650 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10651 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10652 ConvIdx = 1;
10653 } else if (Cand->Function) {
10654 ParamTypes =
10655 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10656 if (isa<CXXMethodDecl>(Cand->Function) &&
10657 !isa<CXXConstructorDecl>(Cand->Function)) {
10658 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10659 ConvIdx = 1;
10660 }
10661 } else {
10662 // Builtin operator.
10663 assert(ConvCount <= 3)(static_cast <bool> (ConvCount <= 3) ? void (0) : __assert_fail
("ConvCount <= 3", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10663, __extension__ __PRETTY_FUNCTION__))
;
10664 ParamTypes = Cand->BuiltinParamTypes;
10665 }
10666
10667 // Fill in the rest of the conversions.
10668 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10669 if (Cand->Conversions[ConvIdx].isInitialized()) {
10670 // We've already checked this conversion.
10671 } else if (ArgIdx < ParamTypes.size()) {
10672 if (ParamTypes[ArgIdx]->isDependentType())
10673 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10674 Args[ArgIdx]->getType());
10675 else {
10676 Cand->Conversions[ConvIdx] =
10677 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10678 SuppressUserConversions,
10679 /*InOverloadResolution=*/true,
10680 /*AllowObjCWritebackConversion=*/
10681 S.getLangOpts().ObjCAutoRefCount);
10682 // Store the FixIt in the candidate if it exists.
10683 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10684 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10685 }
10686 } else
10687 Cand->Conversions[ConvIdx].setEllipsis();
10688 }
10689}
10690
10691/// When overload resolution fails, prints diagnostic messages containing the
10692/// candidates in the candidate set.
10693void OverloadCandidateSet::NoteCandidates(
10694 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10695 StringRef Opc, SourceLocation OpLoc,
10696 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10697 // Sort the candidates by viability and position. Sorting directly would
10698 // be prohibitive, so we make a set of pointers and sort those.
10699 SmallVector<OverloadCandidate*, 32> Cands;
10700 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10701 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10702 if (!Filter(*Cand))
10703 continue;
10704 if (Cand->Viable)
10705 Cands.push_back(Cand);
10706 else if (OCD == OCD_AllCandidates) {
10707 CompleteNonViableCandidate(S, Cand, Args);
10708 if (Cand->Function || Cand->IsSurrogate)
10709 Cands.push_back(Cand);
10710 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10711 // want to list every possible builtin candidate.
10712 }
10713 }
10714
10715 std::stable_sort(Cands.begin(), Cands.end(),
10716 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10717
10718 bool ReportedAmbiguousConversions = false;
10719
10720 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10721 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10722 unsigned CandsShown = 0;
10723 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10724 OverloadCandidate *Cand = *I;
10725
10726 // Set an arbitrary limit on the number of candidate functions we'll spam
10727 // the user with. FIXME: This limit should depend on details of the
10728 // candidate list.
10729 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10730 break;
10731 }
10732 ++CandsShown;
10733
10734 if (Cand->Function)
10735 NoteFunctionCandidate(S, Cand, Args.size(),
10736 /*TakingCandidateAddress=*/false);
10737 else if (Cand->IsSurrogate)
10738 NoteSurrogateCandidate(S, Cand);
10739 else {
10740 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10741, __extension__ __PRETTY_FUNCTION__))
10741 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10741, __extension__ __PRETTY_FUNCTION__))
;
10742 // Generally we only see ambiguities including viable builtin
10743 // operators if overload resolution got screwed up by an
10744 // ambiguous user-defined conversion.
10745 //
10746 // FIXME: It's quite possible for different conversions to see
10747 // different ambiguities, though.
10748 if (!ReportedAmbiguousConversions) {
10749 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10750 ReportedAmbiguousConversions = true;
10751 }
10752
10753 // If this is a viable builtin, print it.
10754 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10755 }
10756 }
10757
10758 if (I != E)
10759 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10760}
10761
10762static SourceLocation
10763GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10764 return Cand->Specialization ? Cand->Specialization->getLocation()
10765 : SourceLocation();
10766}
10767
10768namespace {
10769struct CompareTemplateSpecCandidatesForDisplay {
10770 Sema &S;
10771 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10772
10773 bool operator()(const TemplateSpecCandidate *L,
10774 const TemplateSpecCandidate *R) {
10775 // Fast-path this check.
10776 if (L == R)
10777 return false;
10778
10779 // Assuming that both candidates are not matches...
10780
10781 // Sort by the ranking of deduction failures.
10782 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10783 return RankDeductionFailure(L->DeductionFailure) <
10784 RankDeductionFailure(R->DeductionFailure);
10785
10786 // Sort everything else by location.
10787 SourceLocation LLoc = GetLocationForCandidate(L);
10788 SourceLocation RLoc = GetLocationForCandidate(R);
10789
10790 // Put candidates without locations (e.g. builtins) at the end.
10791 if (LLoc.isInvalid())
10792 return false;
10793 if (RLoc.isInvalid())
10794 return true;
10795
10796 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10797 }
10798};
10799}
10800
10801/// Diagnose a template argument deduction failure.
10802/// We are treating these failures as overload failures due to bad
10803/// deductions.
10804void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10805 bool ForTakingAddress) {
10806 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10807 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10808}
10809
10810void TemplateSpecCandidateSet::destroyCandidates() {
10811 for (iterator i = begin(), e = end(); i != e; ++i) {
10812 i->DeductionFailure.Destroy();
10813 }
10814}
10815
10816void TemplateSpecCandidateSet::clear() {
10817 destroyCandidates();
10818 Candidates.clear();
10819}
10820
10821/// NoteCandidates - When no template specialization match is found, prints
10822/// diagnostic messages containing the non-matching specializations that form
10823/// the candidate set.
10824/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10825/// OCD == OCD_AllCandidates and Cand->Viable == false.
10826void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10827 // Sort the candidates by position (assuming no candidate is a match).
10828 // Sorting directly would be prohibitive, so we make a set of pointers
10829 // and sort those.
10830 SmallVector<TemplateSpecCandidate *, 32> Cands;
10831 Cands.reserve(size());
10832 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10833 if (Cand->Specialization)
10834 Cands.push_back(Cand);
10835 // Otherwise, this is a non-matching builtin candidate. We do not,
10836 // in general, want to list every possible builtin candidate.
10837 }
10838
10839 llvm::sort(Cands.begin(), Cands.end(),
10840 CompareTemplateSpecCandidatesForDisplay(S));
10841
10842 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10843 // for generalization purposes (?).
10844 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10845
10846 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10847 unsigned CandsShown = 0;
10848 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10849 TemplateSpecCandidate *Cand = *I;
10850
10851 // Set an arbitrary limit on the number of candidates we'll spam
10852 // the user with. FIXME: This limit should depend on details of the
10853 // candidate list.
10854 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10855 break;
10856 ++CandsShown;
10857
10858 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10859, __extension__ __PRETTY_FUNCTION__))
10859 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10859, __extension__ __PRETTY_FUNCTION__))
;
10860 Cand->NoteDeductionFailure(S, ForTakingAddress);
10861 }
10862
10863 if (I != E)
10864 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10865}
10866
10867// [PossiblyAFunctionType] --> [Return]
10868// NonFunctionType --> NonFunctionType
10869// R (A) --> R(A)
10870// R (*)(A) --> R (A)
10871// R (&)(A) --> R (A)
10872// R (S::*)(A) --> R (A)
10873QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10874 QualType Ret = PossiblyAFunctionType;
10875 if (const PointerType *ToTypePtr =
10876 PossiblyAFunctionType->getAs<PointerType>())
10877 Ret = ToTypePtr->getPointeeType();
10878 else if (const ReferenceType *ToTypeRef =
10879 PossiblyAFunctionType->getAs<ReferenceType>())
10880 Ret = ToTypeRef->getPointeeType();
10881 else if (const MemberPointerType *MemTypePtr =
10882 PossiblyAFunctionType->getAs<MemberPointerType>())
10883 Ret = MemTypePtr->getPointeeType();
10884 Ret =
10885 Context.getCanonicalType(Ret).getUnqualifiedType();
10886 return Ret;
10887}
10888
10889static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10890 bool Complain = true) {
10891 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10892 S.DeduceReturnType(FD, Loc, Complain))
10893 return true;
10894
10895 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10896 if (S.getLangOpts().CPlusPlus17 &&
10897 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10898 !S.ResolveExceptionSpec(Loc, FPT))
10899 return true;
10900
10901 return false;
10902}
10903
10904namespace {
10905// A helper class to help with address of function resolution
10906// - allows us to avoid passing around all those ugly parameters
10907class AddressOfFunctionResolver {
10908 Sema& S;
10909 Expr* SourceExpr;
10910 const QualType& TargetType;
10911 QualType TargetFunctionType; // Extracted function type from target type
10912
10913 bool Complain;
10914 //DeclAccessPair& ResultFunctionAccessPair;
10915 ASTContext& Context;
10916
10917 bool TargetTypeIsNonStaticMemberFunction;
10918 bool FoundNonTemplateFunction;
10919 bool StaticMemberFunctionFromBoundPointer;
10920 bool HasComplained;
10921
10922 OverloadExpr::FindResult OvlExprInfo;
10923 OverloadExpr *OvlExpr;
10924 TemplateArgumentListInfo OvlExplicitTemplateArgs;
10925 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10926 TemplateSpecCandidateSet FailedCandidates;
10927
10928public:
10929 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10930 const QualType &TargetType, bool Complain)
10931 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10932 Complain(Complain), Context(S.getASTContext()),
10933 TargetTypeIsNonStaticMemberFunction(
10934 !!TargetType->getAs<MemberPointerType>()),
10935 FoundNonTemplateFunction(false),
10936 StaticMemberFunctionFromBoundPointer(false),
10937 HasComplained(false),
10938 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10939 OvlExpr(OvlExprInfo.Expression),
10940 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10941 ExtractUnqualifiedFunctionTypeFromTargetType();
10942
10943 if (TargetFunctionType->isFunctionType()) {
10944 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10945 if (!UME->isImplicitAccess() &&
10946 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10947 StaticMemberFunctionFromBoundPointer = true;
10948 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10949 DeclAccessPair dap;
10950 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10951 OvlExpr, false, &dap)) {
10952 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10953 if (!Method->isStatic()) {
10954 // If the target type is a non-function type and the function found
10955 // is a non-static member function, pretend as if that was the
10956 // target, it's the only possible type to end up with.
10957 TargetTypeIsNonStaticMemberFunction = true;
10958
10959 // And skip adding the function if its not in the proper form.
10960 // We'll diagnose this due to an empty set of functions.
10961 if (!OvlExprInfo.HasFormOfMemberPointer)
10962 return;
10963 }
10964
10965 Matches.push_back(std::make_pair(dap, Fn));
10966 }
10967 return;
10968 }
10969
10970 if (OvlExpr->hasExplicitTemplateArgs())
10971 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10972
10973 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10974 // C++ [over.over]p4:
10975 // If more than one function is selected, [...]
10976 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10977 if (FoundNonTemplateFunction)
10978 EliminateAllTemplateMatches();
10979 else
10980 EliminateAllExceptMostSpecializedTemplate();
10981 }
10982 }
10983
10984 if (S.getLangOpts().CUDA && Matches.size() > 1)
10985 EliminateSuboptimalCudaMatches();
10986 }
10987
10988 bool hasComplained() const { return HasComplained; }
10989
10990private:
10991 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10992 QualType Discard;
10993 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10994 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10995 }
10996
10997 /// \return true if A is considered a better overload candidate for the
10998 /// desired type than B.
10999 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11000 // If A doesn't have exactly the correct type, we don't want to classify it
11001 // as "better" than anything else. This way, the user is required to
11002 // disambiguate for us if there are multiple candidates and no exact match.
11003 return candidateHasExactlyCorrectType(A) &&
11004 (!candidateHasExactlyCorrectType(B) ||
11005 compareEnableIfAttrs(S, A, B) == Comparison::Better);
11006 }
11007
11008 /// \return true if we were able to eliminate all but one overload candidate,
11009 /// false otherwise.
11010 bool eliminiateSuboptimalOverloadCandidates() {
11011 // Same algorithm as overload resolution -- one pass to pick the "best",
11012 // another pass to be sure that nothing is better than the best.
11013 auto Best = Matches.begin();
11014 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11015 if (isBetterCandidate(I->second, Best->second))
11016 Best = I;
11017
11018 const FunctionDecl *BestFn = Best->second;
11019 auto IsBestOrInferiorToBest = [this, BestFn](
11020 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11021 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11022 };
11023
11024 // Note: We explicitly leave Matches unmodified if there isn't a clear best
11025 // option, so we can potentially give the user a better error
11026 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
11027 return false;
11028 Matches[0] = *Best;
11029 Matches.resize(1);
11030 return true;
11031 }
11032
11033 bool isTargetTypeAFunction() const {
11034 return TargetFunctionType->isFunctionType();
11035 }
11036
11037 // [ToType] [Return]
11038
11039 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11040 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11041 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11042 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11043 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11044 }
11045
11046 // return true if any matching specializations were found
11047 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11048 const DeclAccessPair& CurAccessFunPair) {
11049 if (CXXMethodDecl *Method
11050 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11051 // Skip non-static function templates when converting to pointer, and
11052 // static when converting to member pointer.
11053 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11054 return false;
11055 }
11056 else if (TargetTypeIsNonStaticMemberFunction)
11057 return false;
11058
11059 // C++ [over.over]p2:
11060 // If the name is a function template, template argument deduction is
11061 // done (14.8.2.2), and if the argument deduction succeeds, the
11062 // resulting template argument list is used to generate a single
11063 // function template specialization, which is added to the set of
11064 // overloaded functions considered.
11065 FunctionDecl *Specialization = nullptr;
11066 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11067 if (Sema::TemplateDeductionResult Result
11068 = S.DeduceTemplateArguments(FunctionTemplate,
11069 &OvlExplicitTemplateArgs,
11070 TargetFunctionType, Specialization,
11071 Info, /*IsAddressOfFunction*/true)) {
11072 // Make a note of the failed deduction for diagnostics.
11073 FailedCandidates.addCandidate()
11074 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11075 MakeDeductionFailureInfo(Context, Result, Info));
11076 return false;
11077 }
11078
11079 // Template argument deduction ensures that we have an exact match or
11080 // compatible pointer-to-function arguments that would be adjusted by ICS.
11081 // This function template specicalization works.
11082 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11084, __extension__ __PRETTY_FUNCTION__))
11083 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11084, __extension__ __PRETTY_FUNCTION__))
11084 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11084, __extension__ __PRETTY_FUNCTION__))
;
11085
11086 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11087 return false;
11088
11089 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11090 return true;
11091 }
11092
11093 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11094 const DeclAccessPair& CurAccessFunPair) {
11095 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11096 // Skip non-static functions when converting to pointer, and static
11097 // when converting to member pointer.
11098 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11099 return false;
11100 }
11101 else if (TargetTypeIsNonStaticMemberFunction)
11102 return false;
11103
11104 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11105 if (S.getLangOpts().CUDA)
11106 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11107 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11108 return false;
11109 if (FunDecl->isMultiVersion()) {
11110 const auto *TA = FunDecl->getAttr<TargetAttr>();
11111 if (TA && !TA->isDefaultVersion())
11112 return false;
11113 }
11114
11115 // If any candidate has a placeholder return type, trigger its deduction
11116 // now.
11117 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
11118 Complain)) {
11119 HasComplained |= Complain;
11120 return false;
11121 }
11122
11123 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11124 return false;
11125
11126 // If we're in C, we need to support types that aren't exactly identical.
11127 if (!S.getLangOpts().CPlusPlus ||
11128 candidateHasExactlyCorrectType(FunDecl)) {
11129 Matches.push_back(std::make_pair(
11130 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11131 FoundNonTemplateFunction = true;
11132 return true;
11133 }
11134 }
11135
11136 return false;
11137 }
11138
11139 bool FindAllFunctionsThatMatchTargetTypeExactly() {
11140 bool Ret = false;
11141
11142 // If the overload expression doesn't have the form of a pointer to
11143 // member, don't try to convert it to a pointer-to-member type.
11144 if (IsInvalidFormOfPointerToMemberFunction())
11145 return false;
11146
11147 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11148 E = OvlExpr->decls_end();
11149 I != E; ++I) {
11150 // Look through any using declarations to find the underlying function.
11151 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11152
11153 // C++ [over.over]p3:
11154 // Non-member functions and static member functions match
11155 // targets of type "pointer-to-function" or "reference-to-function."
11156 // Nonstatic member functions match targets of
11157 // type "pointer-to-member-function."
11158 // Note that according to DR 247, the containing class does not matter.
11159 if (FunctionTemplateDecl *FunctionTemplate
11160 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11161 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11162 Ret = true;
11163 }
11164 // If we have explicit template arguments supplied, skip non-templates.
11165 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11166 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11167 Ret = true;
11168 }
11169 assert(Ret || Matches.empty())(static_cast <bool> (Ret || Matches.empty()) ? void (0)
: __assert_fail ("Ret || Matches.empty()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11169, __extension__ __PRETTY_FUNCTION__))
;
11170 return Ret;
11171 }
11172
11173 void EliminateAllExceptMostSpecializedTemplate() {
11174 // [...] and any given function template specialization F1 is
11175 // eliminated if the set contains a second function template
11176 // specialization whose function template is more specialized
11177 // than the function template of F1 according to the partial
11178 // ordering rules of 14.5.5.2.
11179
11180 // The algorithm specified above is quadratic. We instead use a
11181 // two-pass algorithm (similar to the one used to identify the
11182 // best viable function in an overload set) that identifies the
11183 // best function template (if it exists).
11184
11185 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11186 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11187 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11188
11189 // TODO: It looks like FailedCandidates does not serve much purpose
11190 // here, since the no_viable diagnostic has index 0.
11191 UnresolvedSetIterator Result = S.getMostSpecialized(
11192 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11193 SourceExpr->getLocStart(), S.PDiag(),
11194 S.PDiag(diag::err_addr_ovl_ambiguous)
11195 << Matches[0].second->getDeclName(),
11196 S.PDiag(diag::note_ovl_candidate)
11197 << (unsigned)oc_function << (unsigned)ocs_described_template,
11198 Complain, TargetFunctionType);
11199
11200 if (Result != MatchesCopy.end()) {
11201 // Make it the first and only element
11202 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11203 Matches[0].second = cast<FunctionDecl>(*Result);
11204 Matches.resize(1);
11205 } else
11206 HasComplained |= Complain;
11207 }
11208
11209 void EliminateAllTemplateMatches() {
11210 // [...] any function template specializations in the set are
11211 // eliminated if the set also contains a non-template function, [...]
11212 for (unsigned I = 0, N = Matches.size(); I != N; ) {
11213 if (Matches[I].second->getPrimaryTemplate() == nullptr)
11214 ++I;
11215 else {
11216 Matches[I] = Matches[--N];
11217 Matches.resize(N);
11218 }
11219 }
11220 }
11221
11222 void EliminateSuboptimalCudaMatches() {
11223 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11224 }
11225
11226public:
11227 void ComplainNoMatchesFound() const {
11228 assert(Matches.empty())(static_cast <bool> (Matches.empty()) ? void (0) : __assert_fail
("Matches.empty()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11228, __extension__ __PRETTY_FUNCTION__))
;
11229 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
11230 << OvlExpr->getName() << TargetFunctionType
11231 << OvlExpr->getSourceRange();
11232 if (FailedCandidates.empty())
11233 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11234 /*TakingAddress=*/true);
11235 else {
11236 // We have some deduction failure messages. Use them to diagnose
11237 // the function templates, and diagnose the non-template candidates
11238 // normally.
11239 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11240 IEnd = OvlExpr->decls_end();
11241 I != IEnd; ++I)
11242 if (FunctionDecl *Fun =
11243 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11244 if (!functionHasPassObjectSizeParams(Fun))
11245 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11246 /*TakingAddress=*/true);
11247 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
11248 }
11249 }
11250
11251 bool IsInvalidFormOfPointerToMemberFunction() const {
11252 return TargetTypeIsNonStaticMemberFunction &&
11253 !OvlExprInfo.HasFormOfMemberPointer;
11254 }
11255
11256 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11257 // TODO: Should we condition this on whether any functions might
11258 // have matched, or is it more appropriate to do that in callers?
11259 // TODO: a fixit wouldn't hurt.
11260 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11261 << TargetType << OvlExpr->getSourceRange();
11262 }
11263
11264 bool IsStaticMemberFunctionFromBoundPointer() const {
11265 return StaticMemberFunctionFromBoundPointer;
11266 }
11267
11268 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11269 S.Diag(OvlExpr->getLocStart(),
11270 diag::err_invalid_form_pointer_member_function)
11271 << OvlExpr->getSourceRange();
11272 }
11273
11274 void ComplainOfInvalidConversion() const {
11275 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
11276 << OvlExpr->getName() << TargetType;
11277 }
11278
11279 void ComplainMultipleMatchesFound() const {
11280 assert(Matches.size() > 1)(static_cast <bool> (Matches.size() > 1) ? void (0) :
__assert_fail ("Matches.size() > 1", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11280, __extension__ __PRETTY_FUNCTION__))
;
11281 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
11282 << OvlExpr->getName()
11283 << OvlExpr->getSourceRange();
11284 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11285 /*TakingAddress=*/true);
11286 }
11287
11288 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11289
11290 int getNumMatches() const { return Matches.size(); }
11291
11292 FunctionDecl* getMatchingFunctionDecl() const {
11293 if (Matches.size() != 1) return nullptr;
11294 return Matches[0].second;
11295 }
11296
11297 const DeclAccessPair* getMatchingFunctionAccessPair() const {
11298 if (Matches.size() != 1) return nullptr;
11299 return &Matches[0].first;
11300 }
11301};
11302}
11303
11304/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11305/// an overloaded function (C++ [over.over]), where @p From is an
11306/// expression with overloaded function type and @p ToType is the type
11307/// we're trying to resolve to. For example:
11308///
11309/// @code
11310/// int f(double);
11311/// int f(int);
11312///
11313/// int (*pfd)(double) = f; // selects f(double)
11314/// @endcode
11315///
11316/// This routine returns the resulting FunctionDecl if it could be
11317/// resolved, and NULL otherwise. When @p Complain is true, this
11318/// routine will emit diagnostics if there is an error.
11319FunctionDecl *
11320Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11321 QualType TargetType,
11322 bool Complain,
11323 DeclAccessPair &FoundResult,
11324 bool *pHadMultipleCandidates) {
11325 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11325, __extension__ __PRETTY_FUNCTION__))
;
11326
11327 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11328 Complain);
11329 int NumMatches = Resolver.getNumMatches();
11330 FunctionDecl *Fn = nullptr;
11331 bool ShouldComplain = Complain && !Resolver.hasComplained();
11332 if (NumMatches == 0 && ShouldComplain) {
11333 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11334 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11335 else
11336 Resolver.ComplainNoMatchesFound();
11337 }
11338 else if (NumMatches > 1 && ShouldComplain)
11339 Resolver.ComplainMultipleMatchesFound();
11340 else if (NumMatches == 1) {
11341 Fn = Resolver.getMatchingFunctionDecl();
11342 assert(Fn)(static_cast <bool> (Fn) ? void (0) : __assert_fail ("Fn"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11342, __extension__ __PRETTY_FUNCTION__))
;
11343 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11344 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11345 FoundResult = *Resolver.getMatchingFunctionAccessPair();
11346 if (Complain) {
11347 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11348 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11349 else
11350 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11351 }
11352 }
11353
11354 if (pHadMultipleCandidates)
11355 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11356 return Fn;
11357}
11358
11359/// Given an expression that refers to an overloaded function, try to
11360/// resolve that function to a single function that can have its address taken.
11361/// This will modify `Pair` iff it returns non-null.
11362///
11363/// This routine can only realistically succeed if all but one candidates in the
11364/// overload set for SrcExpr cannot have their addresses taken.
11365FunctionDecl *
11366Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11367 DeclAccessPair &Pair) {
11368 OverloadExpr::FindResult R = OverloadExpr::find(E);
11369 OverloadExpr *Ovl = R.Expression;
11370 FunctionDecl *Result = nullptr;
11371 DeclAccessPair DAP;
11372 // Don't use the AddressOfResolver because we're specifically looking for
11373 // cases where we have one overload candidate that lacks
11374 // enable_if/pass_object_size/...
11375 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11376 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11377 if (!FD)
11378 return nullptr;
11379
11380 if (!checkAddressOfFunctionIsAvailable(FD))
11381 continue;
11382
11383 // We have more than one result; quit.
11384 if (Result)
11385 return nullptr;
11386 DAP = I.getPair();
11387 Result = FD;
11388 }
11389
11390 if (Result)
11391 Pair = DAP;
11392 return Result;
11393}
11394
11395/// Given an overloaded function, tries to turn it into a non-overloaded
11396/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11397/// will perform access checks, diagnose the use of the resultant decl, and, if
11398/// requested, potentially perform a function-to-pointer decay.
11399///
11400/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11401/// Otherwise, returns true. This may emit diagnostics and return true.
11402bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11403 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11404 Expr *E = SrcExpr.get();
11405 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11405, __extension__ __PRETTY_FUNCTION__))
;
11406
11407 DeclAccessPair DAP;
11408 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11409 if (!Found || Found->isCPUDispatchMultiVersion() ||
11410 Found->isCPUSpecificMultiVersion())
11411 return false;
11412
11413 // Emitting multiple diagnostics for a function that is both inaccessible and
11414 // unavailable is consistent with our behavior elsewhere. So, always check
11415 // for both.
11416 DiagnoseUseOfDecl(Found, E->getExprLoc());
11417 CheckAddressOfMemberAccess(E, DAP);
11418 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11419 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11420 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11421 else
11422 SrcExpr = Fixed;
11423 return true;
11424}
11425
11426/// Given an expression that refers to an overloaded function, try to
11427/// resolve that overloaded function expression down to a single function.
11428///
11429/// This routine can only resolve template-ids that refer to a single function
11430/// template, where that template-id refers to a single template whose template
11431/// arguments are either provided by the template-id or have defaults,
11432/// as described in C++0x [temp.arg.explicit]p3.
11433///
11434/// If no template-ids are found, no diagnostics are emitted and NULL is
11435/// returned.
11436FunctionDecl *
11437Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11438 bool Complain,
11439 DeclAccessPair *FoundResult) {
11440 // C++ [over.over]p1:
11441 // [...] [Note: any redundant set of parentheses surrounding the
11442 // overloaded function name is ignored (5.1). ]
11443 // C++ [over.over]p1:
11444 // [...] The overloaded function name can be preceded by the &
11445 // operator.
11446
11447 // If we didn't actually find any template-ids, we're done.
11448 if (!ovl->hasExplicitTemplateArgs())
2
Taking false branch
11449 return nullptr;
11450
11451 TemplateArgumentListInfo ExplicitTemplateArgs;
11452 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11453 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11454
11455 // Look through all of the overloaded functions, searching for one
11456 // whose type matches exactly.
11457 FunctionDecl *Matched = nullptr;
11458 for (UnresolvedSetIterator I = ovl->decls_begin(),
3
Loop condition is true. Entering loop body
11459 E = ovl->decls_end(); I != E; ++I) {
11460 // C++0x [temp.arg.explicit]p3:
11461 // [...] In contexts where deduction is done and fails, or in contexts
11462 // where deduction is not done, if a template argument list is
11463 // specified and it, along with any default template arguments,
11464 // identifies a single function template specialization, then the
11465 // template-id is an lvalue for the function template specialization.
11466 FunctionTemplateDecl *FunctionTemplate
11467 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11468
11469 // C++ [over.over]p2:
11470 // If the name is a function template, template argument deduction is
11471 // done (14.8.2.2), and if the argument deduction succeeds, the
11472 // resulting template argument list is used to generate a single
11473 // function template specialization, which is added to the set of
11474 // overloaded functions considered.
11475 FunctionDecl *Specialization = nullptr;
11476 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11477 if (TemplateDeductionResult Result
4
Assuming 'Result' is not equal to 0
5
Taking true branch
11478 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11479 Specialization, Info,
11480 /*IsAddressOfFunction*/true)) {
11481 // Make a note of the failed deduction for diagnostics.
11482 // TODO: Actually use the failed-deduction info?
11483 FailedCandidates.addCandidate()
11484 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11485 MakeDeductionFailureInfo(Context, Result, Info));
6
Calling 'MakeDeductionFailureInfo'
11486 continue;
11487 }
11488
11489 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11489, __extension__ __PRETTY_FUNCTION__))
;
11490
11491 // Multiple matches; we can't resolve to a single declaration.
11492 if (Matched) {
11493 if (Complain) {
11494 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11495 << ovl->getName();
11496 NoteAllOverloadCandidates(ovl);
11497 }
11498 return nullptr;
11499 }
11500
11501 Matched = Specialization;
11502 if (FoundResult) *FoundResult = I.getPair();
11503 }
11504
11505 if (Matched &&
11506 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11507 return nullptr;
11508
11509 return Matched;
11510}
11511
11512// Resolve and fix an overloaded expression that can be resolved
11513// because it identifies a single function template specialization.
11514//
11515// Last three arguments should only be supplied if Complain = true
11516//
11517// Return true if it was logically possible to so resolve the
11518// expression, regardless of whether or not it succeeded. Always
11519// returns true if 'complain' is set.
11520bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11521 ExprResult &SrcExpr, bool doFunctionPointerConverion,
11522 bool complain, SourceRange OpRangeForComplaining,
11523 QualType DestTypeForComplaining,
11524 unsigned DiagIDForComplaining) {
11525 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11525, __extension__ __PRETTY_FUNCTION__))
;
11526
11527 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11528
11529 DeclAccessPair found;
11530 ExprResult SingleFunctionExpression;
11531 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
1
Calling 'Sema::ResolveSingleFunctionTemplateSpecialization'
11532 ovl.Expression, /*complain*/ false, &found)) {
11533 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11534 SrcExpr = ExprError();
11535 return true;
11536 }
11537
11538 // It is only correct to resolve to an instance method if we're
11539 // resolving a form that's permitted to be a pointer to member.
11540 // Otherwise we'll end up making a bound member expression, which
11541 // is illegal in all the contexts we resolve like this.
11542 if (!ovl.HasFormOfMemberPointer &&
11543 isa<CXXMethodDecl>(fn) &&
11544 cast<CXXMethodDecl>(fn)->isInstance()) {
11545 if (!complain) return false;
11546
11547 Diag(ovl.Expression->getExprLoc(),
11548 diag::err_bound_member_function)
11549 << 0 << ovl.Expression->getSourceRange();
11550
11551 // TODO: I believe we only end up here if there's a mix of
11552 // static and non-static candidates (otherwise the expression
11553 // would have 'bound member' type, not 'overload' type).
11554 // Ideally we would note which candidate was chosen and why
11555 // the static candidates were rejected.
11556 SrcExpr = ExprError();
11557 return true;
11558 }
11559
11560 // Fix the expression to refer to 'fn'.
11561 SingleFunctionExpression =
11562 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11563
11564 // If desired, do function-to-pointer decay.
11565 if (doFunctionPointerConverion) {
11566 SingleFunctionExpression =
11567 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11568 if (SingleFunctionExpression.isInvalid()) {
11569 SrcExpr = ExprError();
11570 return true;
11571 }
11572 }
11573 }
11574
11575 if (!SingleFunctionExpression.isUsable()) {
11576 if (complain) {
11577 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11578 << ovl.Expression->getName()
11579 << DestTypeForComplaining
11580 << OpRangeForComplaining
11581 << ovl.Expression->getQualifierLoc().getSourceRange();
11582 NoteAllOverloadCandidates(SrcExpr.get());
11583
11584 SrcExpr = ExprError();
11585 return true;
11586 }
11587
11588 return false;
11589 }
11590
11591 SrcExpr = SingleFunctionExpression;
11592 return true;
11593}
11594
11595/// Add a single candidate to the overload set.
11596static void AddOverloadedCallCandidate(Sema &S,
11597 DeclAccessPair FoundDecl,
11598 TemplateArgumentListInfo *ExplicitTemplateArgs,
11599 ArrayRef<Expr *> Args,
11600 OverloadCandidateSet &CandidateSet,
11601 bool PartialOverloading,
11602 bool KnownValid) {
11603 NamedDecl *Callee = FoundDecl.getDecl();
11604 if (isa<UsingShadowDecl>(Callee))
11605 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11606
11607 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11608 if (ExplicitTemplateArgs) {
11609 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11609, __extension__ __PRETTY_FUNCTION__))
;
11610 return;
11611 }
11612 // Prevent ill-formed function decls to be added as overload candidates.
11613 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11614 return;
11615
11616 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11617 /*SuppressUsedConversions=*/false,
11618 PartialOverloading);
11619 return;
11620 }
11621
11622 if (FunctionTemplateDecl *FuncTemplate
11623 = dyn_cast<FunctionTemplateDecl>(Callee)) {
11624 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11625 ExplicitTemplateArgs, Args, CandidateSet,
11626 /*SuppressUsedConversions=*/false,
11627 PartialOverloading);
11628 return;
11629 }
11630
11631 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11631, __extension__ __PRETTY_FUNCTION__))
;
11632}
11633
11634/// Add the overload candidates named by callee and/or found by argument
11635/// dependent lookup to the given overload set.
11636void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11637 ArrayRef<Expr *> Args,
11638 OverloadCandidateSet &CandidateSet,
11639 bool PartialOverloading) {
11640
11641#ifndef NDEBUG
11642 // Verify that ArgumentDependentLookup is consistent with the rules
11643 // in C++0x [basic.lookup.argdep]p3:
11644 //
11645 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11646 // and let Y be the lookup set produced by argument dependent
11647 // lookup (defined as follows). If X contains
11648 //
11649 // -- a declaration of a class member, or
11650 //
11651 // -- a block-scope function declaration that is not a
11652 // using-declaration, or
11653 //
11654 // -- a declaration that is neither a function or a function
11655 // template
11656 //
11657 // then Y is empty.
11658
11659 if (ULE->requiresADL()) {
11660 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11661 E = ULE->decls_end(); I != E; ++I) {
11662 assert(!(*I)->getDeclContext()->isRecord())(static_cast <bool> (!(*I)->getDeclContext()->isRecord
()) ? void (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11662, __extension__ __PRETTY_FUNCTION__))
;
11663 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11664, __extension__ __PRETTY_FUNCTION__))
11664 !(*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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11664, __extension__ __PRETTY_FUNCTION__))
;
11665 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(static_cast <bool> ((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? void (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11665, __extension__ __PRETTY_FUNCTION__))
;
11666 }
11667 }
11668#endif
11669
11670 // It would be nice to avoid this copy.
11671 TemplateArgumentListInfo TABuffer;
11672 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11673 if (ULE->hasExplicitTemplateArgs()) {
11674 ULE->copyTemplateArgumentsInto(TABuffer);
11675 ExplicitTemplateArgs = &TABuffer;
11676 }
11677
11678 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11679 E = ULE->decls_end(); I != E; ++I)
11680 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11681 CandidateSet, PartialOverloading,
11682 /*KnownValid*/ true);
11683
11684 if (ULE->requiresADL())
11685 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11686 Args, ExplicitTemplateArgs,
11687 CandidateSet, PartialOverloading);
11688}
11689
11690/// Determine whether a declaration with the specified name could be moved into
11691/// a different namespace.
11692static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11693 switch (Name.getCXXOverloadedOperator()) {
11694 case OO_New: case OO_Array_New:
11695 case OO_Delete: case OO_Array_Delete:
11696 return false;
11697
11698 default:
11699 return true;
11700 }
11701}
11702
11703/// Attempt to recover from an ill-formed use of a non-dependent name in a
11704/// template, where the non-dependent name was declared after the template
11705/// was defined. This is common in code written for a compilers which do not
11706/// correctly implement two-stage name lookup.
11707///
11708/// Returns true if a viable candidate was found and a diagnostic was issued.
11709static bool
11710DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11711 const CXXScopeSpec &SS, LookupResult &R,
11712 OverloadCandidateSet::CandidateSetKind CSK,
11713 TemplateArgumentListInfo *ExplicitTemplateArgs,
11714 ArrayRef<Expr *> Args,
11715 bool *DoDiagnoseEmptyLookup = nullptr) {
11716 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11717 return false;
11718
11719 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11720 if (DC->isTransparentContext())
11721 continue;
11722
11723 SemaRef.LookupQualifiedName(R, DC);
11724
11725 if (!R.empty()) {
11726 R.suppressDiagnostics();
11727
11728 if (isa<CXXRecordDecl>(DC)) {
11729 // Don't diagnose names we find in classes; we get much better
11730 // diagnostics for these from DiagnoseEmptyLookup.
11731 R.clear();
11732 if (DoDiagnoseEmptyLookup)
11733 *DoDiagnoseEmptyLookup = true;
11734 return false;
11735 }
11736
11737 OverloadCandidateSet Candidates(FnLoc, CSK);
11738 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11739 AddOverloadedCallCandidate(SemaRef, I.getPair(),
11740 ExplicitTemplateArgs, Args,
11741 Candidates, false, /*KnownValid*/ false);
11742
11743 OverloadCandidateSet::iterator Best;
11744 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11745 // No viable functions. Don't bother the user with notes for functions
11746 // which don't work and shouldn't be found anyway.
11747 R.clear();
11748 return false;
11749 }
11750
11751 // Find the namespaces where ADL would have looked, and suggest
11752 // declaring the function there instead.
11753 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11754 Sema::AssociatedClassSet AssociatedClasses;
11755 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11756 AssociatedNamespaces,
11757 AssociatedClasses);
11758 Sema::AssociatedNamespaceSet SuggestedNamespaces;
11759 if (canBeDeclaredInNamespace(R.getLookupName())) {
11760 DeclContext *Std = SemaRef.getStdNamespace();
11761 for (Sema::AssociatedNamespaceSet::iterator
11762 it = AssociatedNamespaces.begin(),
11763 end = AssociatedNamespaces.end(); it != end; ++it) {
11764 // Never suggest declaring a function within namespace 'std'.
11765 if (Std && Std->Encloses(*it))
11766 continue;
11767
11768 // Never suggest declaring a function within a namespace with a
11769 // reserved name, like __gnu_cxx.
11770 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11771 if (NS &&
11772 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11773 continue;
11774
11775 SuggestedNamespaces.insert(*it);
11776 }
11777 }
11778
11779 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11780 << R.getLookupName();
11781 if (SuggestedNamespaces.empty()) {
11782 SemaRef.Diag(Best->Function->getLocation(),
11783 diag::note_not_found_by_two_phase_lookup)
11784 << R.getLookupName() << 0;
11785 } else if (SuggestedNamespaces.size() == 1) {
11786 SemaRef.Diag(Best->Function->getLocation(),
11787 diag::note_not_found_by_two_phase_lookup)
11788 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11789 } else {
11790 // FIXME: It would be useful to list the associated namespaces here,
11791 // but the diagnostics infrastructure doesn't provide a way to produce
11792 // a localized representation of a list of items.
11793 SemaRef.Diag(Best->Function->getLocation(),
11794 diag::note_not_found_by_two_phase_lookup)
11795 << R.getLookupName() << 2;
11796 }
11797
11798 // Try to recover by calling this function.
11799 return true;
11800 }
11801
11802 R.clear();
11803 }
11804
11805 return false;
11806}
11807
11808/// Attempt to recover from ill-formed use of a non-dependent operator in a
11809/// template, where the non-dependent operator was declared after the template
11810/// was defined.
11811///
11812/// Returns true if a viable candidate was found and a diagnostic was issued.
11813static bool
11814DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11815 SourceLocation OpLoc,
11816 ArrayRef<Expr *> Args) {
11817 DeclarationName OpName =
11818 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11819 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11820 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11821 OverloadCandidateSet::CSK_Operator,
11822 /*ExplicitTemplateArgs=*/nullptr, Args);
11823}
11824
11825namespace {
11826class BuildRecoveryCallExprRAII {
11827 Sema &SemaRef;
11828public:
11829 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11830 assert(SemaRef.IsBuildingRecoveryCallExpr == false)(static_cast <bool> (SemaRef.IsBuildingRecoveryCallExpr
== false) ? void (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11830, __extension__ __PRETTY_FUNCTION__))
;
11831 SemaRef.IsBuildingRecoveryCallExpr = true;
11832 }
11833
11834 ~BuildRecoveryCallExprRAII() {
11835 SemaRef.IsBuildingRecoveryCallExpr = false;
11836 }
11837};
11838
11839}
11840
11841static std::unique_ptr<CorrectionCandidateCallback>
11842MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11843 bool HasTemplateArgs, bool AllowTypoCorrection) {
11844 if (!AllowTypoCorrection)
11845 return llvm::make_unique<NoTypoCorrectionCCC>();
11846 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11847 HasTemplateArgs, ME);
11848}
11849
11850/// Attempts to recover from a call where no functions were found.
11851///
11852/// Returns true if new candidates were found.
11853static ExprResult
11854BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11855 UnresolvedLookupExpr *ULE,
11856 SourceLocation LParenLoc,
11857 MutableArrayRef<Expr *> Args,
11858 SourceLocation RParenLoc,
11859 bool EmptyLookup, bool AllowTypoCorrection) {
11860 // Do not try to recover if it is already building a recovery call.
11861 // This stops infinite loops for template instantiations like
11862 //
11863 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11864 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11865 //
11866 if (SemaRef.IsBuildingRecoveryCallExpr)
11867 return ExprError();
11868 BuildRecoveryCallExprRAII RCE(SemaRef);
11869
11870 CXXScopeSpec SS;
11871 SS.Adopt(ULE->getQualifierLoc());
11872 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11873
11874 TemplateArgumentListInfo TABuffer;
11875 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11876 if (ULE->hasExplicitTemplateArgs()) {
11877 ULE->copyTemplateArgumentsInto(TABuffer);
11878 ExplicitTemplateArgs = &TABuffer;
11879 }
11880
11881 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11882 Sema::LookupOrdinaryName);
11883 bool DoDiagnoseEmptyLookup = EmptyLookup;
11884 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11885 OverloadCandidateSet::CSK_Normal,
11886 ExplicitTemplateArgs, Args,
11887 &DoDiagnoseEmptyLookup) &&
11888 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11889 S, SS, R,
11890 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11891 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11892 ExplicitTemplateArgs, Args)))
11893 return ExprError();
11894
11895 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11895, __extension__ __PRETTY_FUNCTION__))
;
11896
11897 // If recovery created an ambiguity, just bail out.
11898 if (R.isAmbiguous()) {
11899 R.suppressDiagnostics();
11900 return ExprError();
11901 }
11902
11903 // Build an implicit member call if appropriate. Just drop the
11904 // casts and such from the call, we don't really care.
11905 ExprResult NewFn = ExprError();
11906 if ((*R.begin())->isCXXClassMember())
11907 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11908 ExplicitTemplateArgs, S);
11909 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11910 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11911 ExplicitTemplateArgs);
11912 else
11913 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11914
11915 if (NewFn.isInvalid())
11916 return ExprError();
11917
11918 // This shouldn't cause an infinite loop because we're giving it
11919 // an expression with viable lookup results, which should never
11920 // end up here.
11921 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11922 MultiExprArg(Args.data(), Args.size()),
11923 RParenLoc);
11924}
11925
11926/// Constructs and populates an OverloadedCandidateSet from
11927/// the given function.
11928/// \returns true when an the ExprResult output parameter has been set.
11929bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11930 UnresolvedLookupExpr *ULE,
11931 MultiExprArg Args,
11932 SourceLocation RParenLoc,
11933 OverloadCandidateSet *CandidateSet,
11934 ExprResult *Result) {
11935#ifndef NDEBUG
11936 if (ULE->requiresADL()) {
11937 // To do ADL, we must have found an unqualified name.
11938 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11938, __extension__ __PRETTY_FUNCTION__))
;
11939
11940 // We don't perform ADL for implicit declarations of builtins.
11941 // Verify that this was correctly set up.
11942 FunctionDecl *F;
11943 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11944 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11945 F->getBuiltinID() && F->isImplicit())
11946 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11946)
;
11947
11948 // We don't perform ADL in C.
11949 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11949, __extension__ __PRETTY_FUNCTION__))
;
11950 }
11951#endif
11952
11953 UnbridgedCastsSet UnbridgedCasts;
11954 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11955 *Result = ExprError();
11956 return true;
11957 }
11958
11959 // Add the functions denoted by the callee to the set of candidate
11960 // functions, including those from argument-dependent lookup.
11961 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11962
11963 if (getLangOpts().MSVCCompat &&
11964 CurContext->isDependentContext() && !isSFINAEContext() &&
11965 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11966
11967 OverloadCandidateSet::iterator Best;
11968 if (CandidateSet->empty() ||
11969 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11970 OR_No_Viable_Function) {
11971 // In Microsoft mode, if we are inside a template class member function then
11972 // create a type dependent CallExpr. The goal is to postpone name lookup
11973 // to instantiation time to be able to search into type dependent base
11974 // classes.
11975 CallExpr *CE = new (Context) CallExpr(
11976 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11977 CE->setTypeDependent(true);
11978 CE->setValueDependent(true);
11979 CE->setInstantiationDependent(true);
11980 *Result = CE;
11981 return true;
11982 }
11983 }
11984
11985 if (CandidateSet->empty())
11986 return false;
11987
11988 UnbridgedCasts.restore();
11989 return false;
11990}
11991
11992/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11993/// the completed call expression. If overload resolution fails, emits
11994/// diagnostics and returns ExprError()
11995static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11996 UnresolvedLookupExpr *ULE,
11997 SourceLocation LParenLoc,
11998 MultiExprArg Args,
11999 SourceLocation RParenLoc,
12000 Expr *ExecConfig,
12001 OverloadCandidateSet *CandidateSet,
12002 OverloadCandidateSet::iterator *Best,
12003 OverloadingResult OverloadResult,
12004 bool AllowTypoCorrection) {
12005 if (CandidateSet->empty())
12006 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12007 RParenLoc, /*EmptyLookup=*/true,
12008 AllowTypoCorrection);
12009
12010 switch (OverloadResult) {
12011 case OR_Success: {
12012 FunctionDecl *FDecl = (*Best)->Function;
12013 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12014 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12015 return ExprError();
12016 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12017 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12018 ExecConfig);
12019 }
12020
12021 case OR_No_Viable_Function: {
12022 // Try to recover by looking for viable functions which the user might
12023 // have meant to call.
12024 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12025 Args, RParenLoc,
12026 /*EmptyLookup=*/false,
12027 AllowTypoCorrection);
12028 if (!Recovery.isInvalid())
12029 return Recovery;
12030
12031 // If the user passes in a function that we can't take the address of, we
12032 // generally end up emitting really bad error messages. Here, we attempt to
12033 // emit better ones.
12034 for (const Expr *Arg : Args) {
12035 if (!Arg->getType()->isFunctionType())
12036 continue;
12037 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12038 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12039 if (FD &&
12040 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12041 Arg->getExprLoc()))
12042 return ExprError();
12043 }
12044 }
12045
12046 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
12047 << ULE->getName() << Fn->getSourceRange();
12048 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12049 break;
12050 }
12051
12052 case OR_Ambiguous:
12053 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
12054 << ULE->getName() << Fn->getSourceRange();
12055 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
12056 break;
12057
12058 case OR_Deleted: {
12059 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
12060 << (*Best)->Function->isDeleted()
12061 << ULE->getName()
12062 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
12063 << Fn->getSourceRange();
12064 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
12065
12066 // We emitted an error for the unavailable/deleted function call but keep
12067 // the call in the AST.
12068 FunctionDecl *FDecl = (*Best)->Function;
12069 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12070 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12071 ExecConfig);
12072 }
12073 }
12074
12075 // Overload resolution failed.
12076 return ExprError();
12077}
12078
12079static void markUnaddressableCandidatesUnviable(Sema &S,
12080 OverloadCandidateSet &CS) {
12081 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12082 if (I->Viable &&
12083 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12084 I->Viable = false;
12085 I->FailureKind = ovl_fail_addr_not_available;
12086 }
12087 }
12088}
12089
12090/// BuildOverloadedCallExpr - Given the call expression that calls Fn
12091/// (which eventually refers to the declaration Func) and the call
12092/// arguments Args/NumArgs, attempt to resolve the function call down
12093/// to a specific function. If overload resolution succeeds, returns
12094/// the call expression produced by overload resolution.
12095/// Otherwise, emits diagnostics and returns ExprError.
12096ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12097 UnresolvedLookupExpr *ULE,
12098 SourceLocation LParenLoc,
12099 MultiExprArg Args,
12100 SourceLocation RParenLoc,
12101 Expr *ExecConfig,
12102 bool AllowTypoCorrection,
12103 bool CalleesAddressIsTaken) {
12104 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12105 OverloadCandidateSet::CSK_Normal);
12106 ExprResult result;
12107
12108 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12109 &result))
12110 return result;
12111
12112 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12113 // functions that aren't addressible are considered unviable.
12114 if (CalleesAddressIsTaken)
12115 markUnaddressableCandidatesUnviable(*this, CandidateSet);
12116
12117 OverloadCandidateSet::iterator Best;
12118 OverloadingResult OverloadResult =
12119 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
12120
12121 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
12122 RParenLoc, ExecConfig, &CandidateSet,
12123 &Best, OverloadResult,
12124 AllowTypoCorrection);
12125}
12126
12127static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12128 return Functions.size() > 1 ||
12129 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12130}
12131
12132/// Create a unary operation that may resolve to an overloaded
12133/// operator.
12134///
12135/// \param OpLoc The location of the operator itself (e.g., '*').
12136///
12137/// \param Opc The UnaryOperatorKind that describes this operator.
12138///
12139/// \param Fns The set of non-member functions that will be
12140/// considered by overload resolution. The caller needs to build this
12141/// set based on the context using, e.g.,
12142/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12143/// set should not contain any member functions; those will be added
12144/// by CreateOverloadedUnaryOp().
12145///
12146/// \param Input The input argument.
12147ExprResult
12148Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12149 const UnresolvedSetImpl &Fns,
12150 Expr *Input, bool PerformADL) {
12151 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12152 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12152, __extension__ __PRETTY_FUNCTION__))
;
12153 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12154 // TODO: provide better source location info.
12155 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12156
12157 if (checkPlaceholderForOverload(*this, Input))
12158 return ExprError();
12159
12160 Expr *Args[2] = { Input, nullptr };
12161 unsigned NumArgs = 1;
12162
12163 // For post-increment and post-decrement, add the implicit '0' as
12164 // the second argument, so that we know this is a post-increment or
12165 // post-decrement.
12166 if (Opc == UO_PostInc || Opc == UO_PostDec) {
12167 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12168 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12169 SourceLocation());
12170 NumArgs = 2;
12171 }
12172
12173 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12174
12175 if (Input->isTypeDependent()) {
12176 if (Fns.empty())
12177 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12178 VK_RValue, OK_Ordinary, OpLoc, false);
12179
12180 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12181 UnresolvedLookupExpr *Fn
12182 = UnresolvedLookupExpr::Create(Context, NamingClass,
12183 NestedNameSpecifierLoc(), OpNameInfo,
12184 /*ADL*/ true, IsOverloaded(Fns),
12185 Fns.begin(), Fns.end());
12186 return new (Context)
12187 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
12188 VK_RValue, OpLoc, FPOptions());
12189 }
12190
12191 // Build an empty overload set.
12192 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12193
12194 // Add the candidates from the given function set.
12195 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12196
12197 // Add operator candidates that are member functions.
12198 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12199
12200 // Add candidates from ADL.
12201 if (PerformADL) {
12202 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12203 /*ExplicitTemplateArgs*/nullptr,
12204 CandidateSet);
12205 }
12206
12207 // Add builtin operator candidates.
12208 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12209
12210 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12211
12212 // Perform overload resolution.
12213 OverloadCandidateSet::iterator Best;
12214 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12215 case OR_Success: {
12216 // We found a built-in operator or an overloaded operator.
12217 FunctionDecl *FnDecl = Best->Function;
12218
12219 if (FnDecl) {
12220 Expr *Base = nullptr;
12221 // We matched an overloaded operator. Build a call to that
12222 // operator.
12223
12224 // Convert the arguments.
12225 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12226 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12227
12228 ExprResult InputRes =
12229 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12230 Best->FoundDecl, Method);
12231 if (InputRes.isInvalid())
12232 return ExprError();
12233 Base = Input = InputRes.get();
12234 } else {
12235 // Convert the arguments.
12236 ExprResult InputInit
12237 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12238 Context,
12239 FnDecl->getParamDecl(0)),
12240 SourceLocation(),
12241 Input);
12242 if (InputInit.isInvalid())
12243 return ExprError();
12244 Input = InputInit.get();
12245 }
12246
12247 // Build the actual expression node.
12248 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12249 Base, HadMultipleCandidates,
12250 OpLoc);
12251 if (FnExpr.isInvalid())
12252 return ExprError();
12253
12254 // Determine the result type.
12255 QualType ResultTy = FnDecl->getReturnType();
12256 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12257 ResultTy = ResultTy.getNonLValueExprType(Context);
12258
12259 Args[0] = Input;
12260 CallExpr *TheCall =
12261 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
12262 ResultTy, VK, OpLoc, FPOptions());
12263
12264 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12265 return ExprError();
12266
12267 if (CheckFunctionCall(FnDecl, TheCall,
12268 FnDecl->getType()->castAs<FunctionProtoType>()))
12269 return ExprError();
12270
12271 return MaybeBindToTemporary(TheCall);
12272 } else {
12273 // We matched a built-in operator. Convert the arguments, then
12274 // break out so that we will build the appropriate built-in
12275 // operator node.
12276 ExprResult InputRes = PerformImplicitConversion(
12277 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12278 CCK_ForBuiltinOverloadedOp);
12279 if (InputRes.isInvalid())
12280 return ExprError();
12281 Input = InputRes.get();
12282 break;
12283 }
12284 }
12285
12286 case OR_No_Viable_Function:
12287 // This is an erroneous use of an operator which can be overloaded by
12288 // a non-member function. Check for non-member operators which were
12289 // defined too late to be candidates.
12290 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12291 // FIXME: Recover by calling the found function.
12292 return ExprError();
12293
12294 // No viable function; fall through to handling this as a
12295 // built-in operator, which will produce an error message for us.
12296 break;
12297
12298 case OR_Ambiguous:
12299 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12300 << UnaryOperator::getOpcodeStr(Opc)
12301 << Input->getType()
12302 << Input->getSourceRange();
12303 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
12304 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12305 return ExprError();
12306
12307 case OR_Deleted:
12308 Diag(OpLoc, diag::err_ovl_deleted_oper)
12309 << Best->Function->isDeleted()
12310 << UnaryOperator::getOpcodeStr(Opc)
12311 << getDeletedOrUnavailableSuffix(Best->Function)
12312 << Input->getSourceRange();
12313 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
12314 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12315 return ExprError();
12316 }
12317
12318 // Either we found no viable overloaded operator or we matched a
12319 // built-in operator. In either case, fall through to trying to
12320 // build a built-in operation.
12321 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12322}
12323
12324/// Create a binary operation that may resolve to an overloaded
12325/// operator.
12326///
12327/// \param OpLoc The location of the operator itself (e.g., '+').
12328///
12329/// \param Opc The BinaryOperatorKind that describes this operator.
12330///
12331/// \param Fns The set of non-member functions that will be
12332/// considered by overload resolution. The caller needs to build this
12333/// set based on the context using, e.g.,
12334/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12335/// set should not contain any member functions; those will be added
12336/// by CreateOverloadedBinOp().
12337///
12338/// \param LHS Left-hand argument.
12339/// \param RHS Right-hand argument.
12340ExprResult
12341Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12342 BinaryOperatorKind Opc,
12343 const UnresolvedSetImpl &Fns,
12344 Expr *LHS, Expr *RHS, bool PerformADL) {
12345 Expr *Args[2] = { LHS, RHS };
12346 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12347
12348 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12349 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12350
12351 // If either side is type-dependent, create an appropriate dependent
12352 // expression.
12353 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12354 if (Fns.empty()) {
12355 // If there are no functions to store, just build a dependent
12356 // BinaryOperator or CompoundAssignment.
12357 if (Opc <= BO_Assign || Opc > BO_OrAssign)
12358 return new (Context) BinaryOperator(
12359 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12360 OpLoc, FPFeatures);
12361
12362 return new (Context) CompoundAssignOperator(
12363 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12364 Context.DependentTy, Context.DependentTy, OpLoc,
12365 FPFeatures);
12366 }
12367
12368 // FIXME: save results of ADL from here?
12369 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12370 // TODO: provide better source location info in DNLoc component.
12371 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12372 UnresolvedLookupExpr *Fn
12373 = UnresolvedLookupExpr::Create(Context, NamingClass,
12374 NestedNameSpecifierLoc(), OpNameInfo,
12375 /*ADL*/PerformADL, IsOverloaded(Fns),
12376 Fns.begin(), Fns.end());
12377 return new (Context)
12378 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
12379 VK_RValue, OpLoc, FPFeatures);
12380 }
12381
12382 // Always do placeholder-like conversions on the RHS.
12383 if (checkPlaceholderForOverload(*this, Args[1]))
12384 return ExprError();
12385
12386 // Do placeholder-like conversion on the LHS; note that we should
12387 // not get here with a PseudoObject LHS.
12388 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12388, __extension__ __PRETTY_FUNCTION__))
;
12389 if (checkPlaceholderForOverload(*this, Args[0]))
12390 return ExprError();
12391
12392 // If this is the assignment operator, we only perform overload resolution
12393 // if the left-hand side is a class or enumeration type. This is actually
12394 // a hack. The standard requires that we do overload resolution between the
12395 // various built-in candidates, but as DR507 points out, this can lead to
12396 // problems. So we do it this way, which pretty much follows what GCC does.
12397 // Note that we go the traditional code path for compound assignment forms.
12398 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12399 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12400
12401 // If this is the .* operator, which is not overloadable, just
12402 // create a built-in binary operator.
12403 if (Opc == BO_PtrMemD)
12404 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12405
12406 // Build an empty overload set.
12407 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12408
12409 // Add the candidates from the given function set.
12410 AddFunctionCandidates(Fns, Args, CandidateSet);
12411
12412 // Add operator candidates that are member functions.
12413 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12414
12415 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12416 // performed for an assignment operator (nor for operator[] nor operator->,
12417 // which don't get here).
12418 if (Opc != BO_Assign && PerformADL)
12419 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12420 /*ExplicitTemplateArgs*/ nullptr,
12421 CandidateSet);
12422
12423 // Add builtin operator candidates.
12424 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12425
12426 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12427
12428 // Perform overload resolution.
12429 OverloadCandidateSet::iterator Best;
12430 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12431 case OR_Success: {
12432 // We found a built-in operator or an overloaded operator.
12433 FunctionDecl *FnDecl = Best->Function;
12434
12435 if (FnDecl) {
12436 Expr *Base = nullptr;
12437 // We matched an overloaded operator. Build a call to that
12438 // operator.
12439
12440 // Convert the arguments.
12441 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12442 // Best->Access is only meaningful for class members.
12443 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12444
12445 ExprResult Arg1 =
12446 PerformCopyInitialization(
12447 InitializedEntity::InitializeParameter(Context,
12448 FnDecl->getParamDecl(0)),
12449 SourceLocation(), Args[1]);
12450 if (Arg1.isInvalid())
12451 return ExprError();
12452
12453 ExprResult Arg0 =
12454 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12455 Best->FoundDecl, Method);
12456 if (Arg0.isInvalid())
12457 return ExprError();
12458 Base = Args[0] = Arg0.getAs<Expr>();
12459 Args[1] = RHS = Arg1.getAs<Expr>();
12460 } else {
12461 // Convert the arguments.
12462 ExprResult Arg0 = PerformCopyInitialization(
12463 InitializedEntity::InitializeParameter(Context,
12464 FnDecl->getParamDecl(0)),
12465 SourceLocation(), Args[0]);
12466 if (Arg0.isInvalid())
12467 return ExprError();
12468
12469 ExprResult Arg1 =
12470 PerformCopyInitialization(
12471 InitializedEntity::InitializeParameter(Context,
12472 FnDecl->getParamDecl(1)),
12473 SourceLocation(), Args[1]);
12474 if (Arg1.isInvalid())
12475 return ExprError();
12476 Args[0] = LHS = Arg0.getAs<Expr>();
12477 Args[1] = RHS = Arg1.getAs<Expr>();
12478 }
12479
12480 // Build the actual expression node.
12481 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12482 Best->FoundDecl, Base,
12483 HadMultipleCandidates, OpLoc);
12484 if (FnExpr.isInvalid())
12485 return ExprError();
12486
12487 // Determine the result type.
12488 QualType ResultTy = FnDecl->getReturnType();
12489 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12490 ResultTy = ResultTy.getNonLValueExprType(Context);
12491
12492 CXXOperatorCallExpr *TheCall =
12493 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12494 Args, ResultTy, VK, OpLoc,
12495 FPFeatures);
12496
12497 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12498 FnDecl))
12499 return ExprError();
12500
12501 ArrayRef<const Expr *> ArgsArray(Args, 2);
12502 const Expr *ImplicitThis = nullptr;
12503 // Cut off the implicit 'this'.
12504 if (isa<CXXMethodDecl>(FnDecl)) {
12505 ImplicitThis = ArgsArray[0];
12506 ArgsArray = ArgsArray.slice(1);
12507 }
12508
12509 // Check for a self move.
12510 if (Op == OO_Equal)
12511 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12512
12513 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12514 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12515 VariadicDoesNotApply);
12516
12517 return MaybeBindToTemporary(TheCall);
12518 } else {
12519 // We matched a built-in operator. Convert the arguments, then
12520 // break out so that we will build the appropriate built-in
12521 // operator node.
12522 ExprResult ArgsRes0 = PerformImplicitConversion(
12523 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12524 AA_Passing, CCK_ForBuiltinOverloadedOp);
12525 if (ArgsRes0.isInvalid())
12526 return ExprError();
12527 Args[0] = ArgsRes0.get();
12528
12529 ExprResult ArgsRes1 = PerformImplicitConversion(
12530 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12531 AA_Passing, CCK_ForBuiltinOverloadedOp);
12532 if (ArgsRes1.isInvalid())
12533 return ExprError();
12534 Args[1] = ArgsRes1.get();
12535 break;
12536 }
12537 }
12538
12539 case OR_No_Viable_Function: {
12540 // C++ [over.match.oper]p9:
12541 // If the operator is the operator , [...] and there are no
12542 // viable functions, then the operator is assumed to be the
12543 // built-in operator and interpreted according to clause 5.
12544 if (Opc == BO_Comma)
12545 break;
12546
12547 // For class as left operand for assignment or compound assignment
12548 // operator do not fall through to handling in built-in, but report that
12549 // no overloaded assignment operator found
12550 ExprResult Result = ExprError();
12551 if (Args[0]->getType()->isRecordType() &&
12552 Opc >= BO_Assign && Opc <= BO_OrAssign) {
12553 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12554 << BinaryOperator::getOpcodeStr(Opc)
12555 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12556 if (Args[0]->getType()->isIncompleteType()) {
12557 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12558 << Args[0]->getType()
12559 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12560 }
12561 } else {
12562 // This is an erroneous use of an operator which can be overloaded by
12563 // a non-member function. Check for non-member operators which were
12564 // defined too late to be candidates.
12565 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12566 // FIXME: Recover by calling the found function.
12567 return ExprError();
12568
12569 // No viable function; try to create a built-in operation, which will
12570 // produce an error. Then, show the non-viable candidates.
12571 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12572 }
12573 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12574, __extension__ __PRETTY_FUNCTION__))
12574 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12574, __extension__ __PRETTY_FUNCTION__))
;
12575 if (Result.isInvalid())
12576 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12577 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12578 return Result;
12579 }
12580
12581 case OR_Ambiguous:
12582 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
12583 << BinaryOperator::getOpcodeStr(Opc)
12584 << Args[0]->getType() << Args[1]->getType()
12585 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12586 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12587 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12588 return ExprError();
12589
12590 case OR_Deleted:
12591 if (isImplicitlyDeleted(Best->Function)) {
12592 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12593 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12594 << Context.getRecordType(Method->getParent())
12595 << getSpecialMember(Method);
12596
12597 // The user probably meant to call this special member. Just
12598 // explain why it's deleted.
12599 NoteDeletedFunction(Method);
12600 return ExprError();
12601 } else {
12602 Diag(OpLoc, diag::err_ovl_deleted_oper)
12603 << Best->Function->isDeleted()
12604 << BinaryOperator::getOpcodeStr(Opc)
12605 << getDeletedOrUnavailableSuffix(Best->Function)
12606 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12607 }
12608 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12609 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12610 return ExprError();
12611 }
12612
12613 // We matched a built-in operator; build it.
12614 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12615}
12616
12617ExprResult
12618Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12619 SourceLocation RLoc,
12620 Expr *Base, Expr *Idx) {
12621 Expr *Args[2] = { Base, Idx };
12622 DeclarationName OpName =
12623 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12624
12625 // If either side is type-dependent, create an appropriate dependent
12626 // expression.
12627 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12628
12629 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12630 // CHECKME: no 'operator' keyword?
12631 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12632 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12633 UnresolvedLookupExpr *Fn
12634 = UnresolvedLookupExpr::Create(Context, NamingClass,
12635 NestedNameSpecifierLoc(), OpNameInfo,
12636 /*ADL*/ true, /*Overloaded*/ false,
12637 UnresolvedSetIterator(),
12638 UnresolvedSetIterator());
12639 // Can't add any actual overloads yet
12640
12641 return new (Context)
12642 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12643 Context.DependentTy, VK_RValue, RLoc, FPOptions());
12644 }
12645
12646 // Handle placeholders on both operands.
12647 if (checkPlaceholderForOverload(*this, Args[0]))
12648 return ExprError();
12649 if (checkPlaceholderForOverload(*this, Args[1]))
12650 return ExprError();
12651
12652 // Build an empty overload set.
12653 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12654
12655 // Subscript can only be overloaded as a member function.
12656
12657 // Add operator candidates that are member functions.
12658 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12659
12660 // Add builtin operator candidates.
12661 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12662
12663 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12664
12665 // Perform overload resolution.
12666 OverloadCandidateSet::iterator Best;
12667 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12668 case OR_Success: {
12669 // We found a built-in operator or an overloaded operator.
12670 FunctionDecl *FnDecl = Best->Function;
12671
12672 if (FnDecl) {
12673 // We matched an overloaded operator. Build a call to that
12674 // operator.
12675
12676 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12677
12678 // Convert the arguments.
12679 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12680 ExprResult Arg0 =
12681 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12682 Best->FoundDecl, Method);
12683 if (Arg0.isInvalid())
12684 return ExprError();
12685 Args[0] = Arg0.get();
12686
12687 // Convert the arguments.
12688 ExprResult InputInit
12689 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12690 Context,
12691 FnDecl->getParamDecl(0)),
12692 SourceLocation(),
12693 Args[1]);
12694 if (InputInit.isInvalid())
12695 return ExprError();
12696
12697 Args[1] = InputInit.getAs<Expr>();
12698
12699 // Build the actual expression node.
12700 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12701 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12702 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12703 Best->FoundDecl,
12704 Base,
12705 HadMultipleCandidates,
12706 OpLocInfo.getLoc(),
12707 OpLocInfo.getInfo());
12708 if (FnExpr.isInvalid())
12709 return ExprError();
12710
12711 // Determine the result type
12712 QualType ResultTy = FnDecl->getReturnType();
12713 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12714 ResultTy = ResultTy.getNonLValueExprType(Context);
12715
12716 CXXOperatorCallExpr *TheCall =
12717 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12718 FnExpr.get(), Args,
12719 ResultTy, VK, RLoc,
12720 FPOptions());
12721
12722 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12723 return ExprError();
12724
12725 if (CheckFunctionCall(Method, TheCall,
12726 Method->getType()->castAs<FunctionProtoType>()))
12727 return ExprError();
12728
12729 return MaybeBindToTemporary(TheCall);
12730 } else {
12731 // We matched a built-in operator. Convert the arguments, then
12732 // break out so that we will build the appropriate built-in
12733 // operator node.
12734 ExprResult ArgsRes0 = PerformImplicitConversion(
12735 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12736 AA_Passing, CCK_ForBuiltinOverloadedOp);
12737 if (ArgsRes0.isInvalid())
12738 return ExprError();
12739 Args[0] = ArgsRes0.get();
12740
12741 ExprResult ArgsRes1 = PerformImplicitConversion(
12742 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12743 AA_Passing, CCK_ForBuiltinOverloadedOp);
12744 if (ArgsRes1.isInvalid())
12745 return ExprError();
12746 Args[1] = ArgsRes1.get();
12747
12748 break;
12749 }
12750 }
12751
12752 case OR_No_Viable_Function: {
12753 if (CandidateSet.empty())
12754 Diag(LLoc, diag::err_ovl_no_oper)
12755 << Args[0]->getType() << /*subscript*/ 0
12756 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12757 else
12758 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12759 << Args[0]->getType()
12760 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12761 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12762 "[]", LLoc);
12763 return ExprError();
12764 }
12765
12766 case OR_Ambiguous:
12767 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
12768 << "[]"
12769 << Args[0]->getType() << Args[1]->getType()
12770 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12771 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12772 "[]", LLoc);
12773 return ExprError();
12774
12775 case OR_Deleted:
12776 Diag(LLoc, diag::err_ovl_deleted_oper)
12777 << Best->Function->isDeleted() << "[]"
12778 << getDeletedOrUnavailableSuffix(Best->Function)
12779 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12780 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12781 "[]", LLoc);
12782 return ExprError();
12783 }
12784
12785 // We matched a built-in operator; build it.
12786 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12787}
12788
12789/// BuildCallToMemberFunction - Build a call to a member
12790/// function. MemExpr is the expression that refers to the member
12791/// function (and includes the object parameter), Args/NumArgs are the
12792/// arguments to the function call (not including the object
12793/// parameter). The caller needs to validate that the member
12794/// expression refers to a non-static member function or an overloaded
12795/// member function.
12796ExprResult
12797Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12798 SourceLocation LParenLoc,
12799 MultiExprArg Args,
12800 SourceLocation RParenLoc) {
12801 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12802, __extension__ __PRETTY_FUNCTION__))
12802 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12802, __extension__ __PRETTY_FUNCTION__))
;
12803
12804 // Dig out the member expression. This holds both the object
12805 // argument and the member function we're referring to.
12806 Expr *NakedMemExpr = MemExprE->IgnoreParens();
12807
12808 // Determine whether this is a call to a pointer-to-member function.
12809 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12810 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12810, __extension__ __PRETTY_FUNCTION__))
;
12811 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12811, __extension__ __PRETTY_FUNCTION__))
;
12812
12813 QualType fnType =
12814 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12815
12816 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12817 QualType resultType = proto->getCallResultType(Context);
12818 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12819
12820 // Check that the object type isn't more qualified than the
12821 // member function we're calling.
12822 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12823
12824 QualType objectType = op->getLHS()->getType();
12825 if (op->getOpcode() == BO_PtrMemI)
12826 objectType = objectType->castAs<PointerType>()->getPointeeType();
12827 Qualifiers objectQuals = objectType.getQualifiers();
12828
12829 Qualifiers difference = objectQuals - funcQuals;
12830 difference.removeObjCGCAttr();
12831 difference.removeAddressSpace();
12832 if (difference) {
12833 std::string qualsString = difference.getAsString();
12834 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12835 << fnType.getUnqualifiedType()
12836 << qualsString
12837 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12838 }
12839
12840 CXXMemberCallExpr *call
12841 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12842 resultType, valueKind, RParenLoc);
12843
12844 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12845 call, nullptr))
12846 return ExprError();
12847
12848 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12849 return ExprError();
12850
12851 if (CheckOtherCall(call, proto))
12852 return ExprError();
12853
12854 return MaybeBindToTemporary(call);
12855 }
12856
12857 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12858 return new (Context)
12859 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12860
12861 UnbridgedCastsSet UnbridgedCasts;
12862 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12863 return ExprError();
12864
12865 MemberExpr *MemExpr;
12866 CXXMethodDecl *Method = nullptr;
12867 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12868 NestedNameSpecifier *Qualifier = nullptr;
12869 if (isa<MemberExpr>(NakedMemExpr)) {
12870 MemExpr = cast<MemberExpr>(NakedMemExpr);
12871 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12872 FoundDecl = MemExpr->getFoundDecl();
12873 Qualifier = MemExpr->getQualifier();
12874 UnbridgedCasts.restore();
12875 } else {
12876 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12877 Qualifier = UnresExpr->getQualifier();
12878
12879 QualType ObjectType = UnresExpr->getBaseType();
12880 Expr::Classification ObjectClassification
12881 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12882 : UnresExpr->getBase()->Classify(Context);
12883
12884 // Add overload candidates
12885 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12886 OverloadCandidateSet::CSK_Normal);
12887
12888 // FIXME: avoid copy.
12889 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12890 if (UnresExpr->hasExplicitTemplateArgs()) {
12891 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12892 TemplateArgs = &TemplateArgsBuffer;
12893 }
12894
12895 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12896 E = UnresExpr->decls_end(); I != E; ++I) {
12897
12898 NamedDecl *Func = *I;
12899 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12900 if (isa<UsingShadowDecl>(Func))
12901 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12902
12903
12904 // Microsoft supports direct constructor calls.
12905 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12906 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12907 Args, CandidateSet);
12908 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12909 // If explicit template arguments were provided, we can't call a
12910 // non-template member function.
12911 if (TemplateArgs)
12912 continue;
12913
12914 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12915 ObjectClassification, Args, CandidateSet,
12916 /*SuppressUserConversions=*/false);
12917 } else {
12918 AddMethodTemplateCandidate(
12919 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
12920 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
12921 /*SuppressUsedConversions=*/false);
12922 }
12923 }
12924
12925 DeclarationName DeclName = UnresExpr->getMemberName();
12926
12927 UnbridgedCasts.restore();
12928
12929 OverloadCandidateSet::iterator Best;
12930 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12931 Best)) {
12932 case OR_Success:
12933 Method = cast<CXXMethodDecl>(Best->Function);
12934 FoundDecl = Best->FoundDecl;
12935 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12936 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12937 return ExprError();
12938 // If FoundDecl is different from Method (such as if one is a template
12939 // and the other a specialization), make sure DiagnoseUseOfDecl is
12940 // called on both.
12941 // FIXME: This would be more comprehensively addressed by modifying
12942 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12943 // being used.
12944 if (Method != FoundDecl.getDecl() &&
12945 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12946 return ExprError();
12947 break;
12948
12949 case OR_No_Viable_Function:
12950 Diag(UnresExpr->getMemberLoc(),
12951 diag::err_ovl_no_viable_member_function_in_call)
12952 << DeclName << MemExprE->getSourceRange();
12953 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12954 // FIXME: Leaking incoming expressions!
12955 return ExprError();
12956
12957 case OR_Ambiguous:
12958 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12959 << DeclName << MemExprE->getSourceRange();
12960 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12961 // FIXME: Leaking incoming expressions!
12962 return ExprError();
12963
12964 case OR_Deleted:
12965 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12966 << Best->Function->isDeleted()
12967 << DeclName
12968 << getDeletedOrUnavailableSuffix(Best->Function)
12969 << MemExprE->getSourceRange();
12970 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12971 // FIXME: Leaking incoming expressions!
12972 return ExprError();
12973 }
12974
12975 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12976
12977 // If overload resolution picked a static member, build a
12978 // non-member call based on that function.
12979 if (Method->isStatic()) {
12980 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12981 RParenLoc);
12982 }
12983
12984 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12985 }
12986
12987 QualType ResultType = Method->getReturnType();
12988 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12989 ResultType = ResultType.getNonLValueExprType(Context);
12990
12991 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12991, __extension__ __PRETTY_FUNCTION__))
;
12992 CXXMemberCallExpr *TheCall =
12993 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12994 ResultType, VK, RParenLoc);
12995
12996 // Check for a valid return type.
12997 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12998 TheCall, Method))
12999 return ExprError();
13000
13001 // Convert the object argument (for a non-static member function call).
13002 // We only need to do this if there was actually an overload; otherwise
13003 // it was done at lookup.
13004 if (!Method->isStatic()) {
13005 ExprResult ObjectArg =
13006 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13007 FoundDecl, Method);
13008 if (ObjectArg.isInvalid())
13009 return ExprError();
13010 MemExpr->setBase(ObjectArg.get());
13011 }
13012
13013 // Convert the rest of the arguments
13014 const FunctionProtoType *Proto =
13015 Method->getType()->getAs<FunctionProtoType>();
13016 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13017 RParenLoc))
13018 return ExprError();
13019
13020 DiagnoseSentinelCalls(Method, LParenLoc, Args);
13021
13022 if (CheckFunctionCall(Method, TheCall, Proto))
13023 return ExprError();
13024
13025 // In the case the method to call was not selected by the overloading
13026 // resolution process, we still need to handle the enable_if attribute. Do
13027 // that here, so it will not hide previous -- and more relevant -- errors.
13028 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13029 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13030 Diag(MemE->getMemberLoc(),
13031 diag::err_ovl_no_viable_member_function_in_call)
13032 << Method << Method->getSourceRange();
13033 Diag(Method->getLocation(),
13034 diag::note_ovl_candidate_disabled_by_function_cond_attr)
13035 << Attr->getCond()->getSourceRange() << Attr->getMessage();
13036 return ExprError();
13037 }
13038 }
13039
13040 if ((isa<CXXConstructorDecl>(CurContext) ||
13041 isa<CXXDestructorDecl>(CurContext)) &&
13042 TheCall->getMethodDecl()->isPure()) {
13043 const CXXMethodDecl *MD = TheCall->getMethodDecl();
13044
13045 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13046 MemExpr->performsVirtualDispatch(getLangOpts())) {
13047 Diag(MemExpr->getLocStart(),
13048 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13049 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13050 << MD->getParent()->getDeclName();
13051
13052 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
13053 if (getLangOpts().AppleKext)
13054 Diag(MemExpr->getLocStart(),
13055 diag::note_pure_qualified_call_kext)
13056 << MD->getParent()->getDeclName()
13057 << MD->getDeclName();
13058 }
13059 }
13060
13061 if (CXXDestructorDecl *DD =
13062 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13063 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13064 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13065 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
13066 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13067 MemExpr->getMemberLoc());
13068 }
13069
13070 return MaybeBindToTemporary(TheCall);
13071}
13072
13073/// BuildCallToObjectOfClassType - Build a call to an object of class
13074/// type (C++ [over.call.object]), which can end up invoking an
13075/// overloaded function call operator (@c operator()) or performing a
13076/// user-defined conversion on the object argument.
13077ExprResult
13078Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13079 SourceLocation LParenLoc,
13080 MultiExprArg Args,
13081 SourceLocation RParenLoc) {
13082 if (checkPlaceholderForOverload(*this, Obj))
13083 return ExprError();
13084 ExprResult Object = Obj;
13085
13086 UnbridgedCastsSet UnbridgedCasts;
13087 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13088 return ExprError();
13089
13090 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13091, __extension__ __PRETTY_FUNCTION__))
13091 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13091, __extension__ __PRETTY_FUNCTION__))
;
13092 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13093
13094 // C++ [over.call.object]p1:
13095 // If the primary-expression E in the function call syntax
13096 // evaluates to a class object of type "cv T", then the set of
13097 // candidate functions includes at least the function call
13098 // operators of T. The function call operators of T are obtained by
13099 // ordinary lookup of the name operator() in the context of
13100 // (E).operator().
13101 OverloadCandidateSet CandidateSet(LParenLoc,
13102 OverloadCandidateSet::CSK_Operator);
13103 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13104
13105 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13106 diag::err_incomplete_object_call, Object.get()))
13107 return true;
13108
13109 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13110 LookupQualifiedName(R, Record->getDecl());
13111 R.suppressDiagnostics();
13112
13113 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13114 Oper != OperEnd; ++Oper) {
13115 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13116 Object.get()->Classify(Context), Args, CandidateSet,
13117 /*SuppressUserConversions=*/false);
13118 }
13119
13120 // C++ [over.call.object]p2:
13121 // In addition, for each (non-explicit in C++0x) conversion function
13122 // declared in T of the form
13123 //
13124 // operator conversion-type-id () cv-qualifier;
13125 //
13126 // where cv-qualifier is the same cv-qualification as, or a
13127 // greater cv-qualification than, cv, and where conversion-type-id
13128 // denotes the type "pointer to function of (P1,...,Pn) returning
13129 // R", or the type "reference to pointer to function of
13130 // (P1,...,Pn) returning R", or the type "reference to function
13131 // of (P1,...,Pn) returning R", a surrogate call function [...]
13132 // is also considered as a candidate function. Similarly,
13133 // surrogate call functions are added to the set of candidate
13134 // functions for each conversion function declared in an
13135 // accessible base class provided the function is not hidden
13136 // within T by another intervening declaration.
13137 const auto &Conversions =
13138 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13139 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13140 NamedDecl *D = *I;
13141 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13142 if (isa<UsingShadowDecl>(D))
13143 D = cast<UsingShadowDecl>(D)->getTargetDecl();
13144
13145 // Skip over templated conversion functions; they aren't
13146 // surrogates.
13147 if (isa<FunctionTemplateDecl>(D))
13148 continue;
13149
13150 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13151 if (!Conv->isExplicit()) {
13152 // Strip the reference type (if any) and then the pointer type (if
13153 // any) to get down to what might be a function type.
13154 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13155 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13156 ConvType = ConvPtrType->getPointeeType();
13157
13158 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13159 {
13160 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13161 Object.get(), Args, CandidateSet);
13162 }
13163 }
13164 }
13165
13166 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13167
13168 // Perform overload resolution.
13169 OverloadCandidateSet::iterator Best;
13170 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
13171 Best)) {
13172 case OR_Success:
13173 // Overload resolution succeeded; we'll build the appropriate call
13174 // below.
13175 break;
13176
13177 case OR_No_Viable_Function:
13178 if (CandidateSet.empty())
13179 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
13180 << Object.get()->getType() << /*call*/ 1
13181 << Object.get()->getSourceRange();
13182 else
13183 Diag(Object.get()->getLocStart(),
13184 diag::err_ovl_no_viable_object_call)
13185 << Object.get()->getType() << Object.get()->getSourceRange();
13186 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13187 break;
13188
13189 case OR_Ambiguous:
13190 Diag(Object.get()->getLocStart(),
13191 diag::err_ovl_ambiguous_object_call)
13192 << Object.get()->getType() << Object.get()->getSourceRange();
13193 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13194 break;
13195
13196 case OR_Deleted:
13197 Diag(Object.get()->getLocStart(),
13198 diag::err_ovl_deleted_object_call)
13199 << Best->Function->isDeleted()
13200 << Object.get()->getType()
13201 << getDeletedOrUnavailableSuffix(Best->Function)
13202 << Object.get()->getSourceRange();
13203 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13204 break;
13205 }
13206
13207 if (Best == CandidateSet.end())
13208 return true;
13209
13210 UnbridgedCasts.restore();
13211
13212 if (Best->Function == nullptr) {
13213 // Since there is no function declaration, this is one of the
13214 // surrogate candidates. Dig out the conversion function.
13215 CXXConversionDecl *Conv
13216 = cast<CXXConversionDecl>(
13217 Best->Conversions[0].UserDefined.ConversionFunction);
13218
13219 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13220 Best->FoundDecl);
13221 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13222 return ExprError();
13223 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13224, __extension__ __PRETTY_FUNCTION__))
13224 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13224, __extension__ __PRETTY_FUNCTION__))
;
13225 // We selected one of the surrogate functions that converts the
13226 // object parameter to a function pointer. Perform the conversion
13227 // on the object argument, then let ActOnCallExpr finish the job.
13228
13229 // Create an implicit member expr to refer to the conversion operator.
13230 // and then call it.
13231 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13232 Conv, HadMultipleCandidates);
13233 if (Call.isInvalid())
13234 return ExprError();
13235 // Record usage of conversion in an implicit cast.
13236 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13237 CK_UserDefinedConversion, Call.get(),
13238 nullptr, VK_RValue);
13239
13240 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13241 }
13242
13243 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13244
13245 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13246 // that calls this method, using Object for the implicit object
13247 // parameter and passing along the remaining arguments.
13248 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13249
13250 // An error diagnostic has already been printed when parsing the declaration.
13251 if (Method->isInvalidDecl())
13252 return ExprError();
13253
13254 const FunctionProtoType *Proto =
13255 Method->getType()->getAs<FunctionProtoType>();
13256
13257 unsigned NumParams = Proto->getNumParams();
13258
13259 DeclarationNameInfo OpLocInfo(
13260 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13261 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13262 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13263 Obj, HadMultipleCandidates,
13264 OpLocInfo.getLoc(),
13265 OpLocInfo.getInfo());
13266 if (NewFn.isInvalid())
13267 return true;
13268
13269 // Build the full argument list for the method call (the implicit object
13270 // parameter is placed at the beginning of the list).
13271 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
13272 MethodArgs[0] = Object.get();
13273 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
13274
13275 // Once we've built TheCall, all of the expressions are properly
13276 // owned.
13277 QualType ResultTy = Method->getReturnType();
13278 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13279 ResultTy = ResultTy.getNonLValueExprType(Context);
13280
13281 CXXOperatorCallExpr *TheCall = new (Context)
13282 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
13283 VK, RParenLoc, FPOptions());
13284
13285 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13286 return true;
13287
13288 // We may have default arguments. If so, we need to allocate more
13289 // slots in the call for them.
13290 if (Args.size() < NumParams)
13291 TheCall->setNumArgs(Context, NumParams + 1);
13292
13293 bool IsError = false;
13294
13295 // Initialize the implicit object parameter.
13296 ExprResult ObjRes =
13297 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13298 Best->FoundDecl, Method);
13299 if (ObjRes.isInvalid())
13300 IsError = true;
13301 else
13302 Object = ObjRes;
13303 TheCall->setArg(0, Object.get());
13304
13305 // Check the argument types.
13306 for (unsigned i = 0; i != NumParams; i++) {
13307 Expr *Arg;
13308 if (i < Args.size()) {
13309 Arg = Args[i];
13310
13311 // Pass the argument.
13312
13313 ExprResult InputInit
13314 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13315 Context,
13316 Method->getParamDecl(i)),
13317 SourceLocation(), Arg);
13318
13319 IsError |= InputInit.isInvalid();
13320 Arg = InputInit.getAs<Expr>();
13321 } else {
13322 ExprResult DefArg
13323 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13324 if (DefArg.isInvalid()) {
13325 IsError = true;
13326 break;
13327 }
13328
13329 Arg = DefArg.getAs<Expr>();
13330 }
13331
13332 TheCall->setArg(i + 1, Arg);
13333 }
13334
13335 // If this is a variadic call, handle args passed through "...".
13336 if (Proto->isVariadic()) {
13337 // Promote the arguments (C99 6.5.2.2p7).
13338 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13339 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13340 nullptr);
13341 IsError |= Arg.isInvalid();
13342 TheCall->setArg(i + 1, Arg.get());
13343 }
13344 }
13345
13346 if (IsError) return true;
13347
13348 DiagnoseSentinelCalls(Method, LParenLoc, Args);
13349
13350 if (CheckFunctionCall(Method, TheCall, Proto))
13351 return true;
13352
13353 return MaybeBindToTemporary(TheCall);
13354}
13355
13356/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13357/// (if one exists), where @c Base is an expression of class type and
13358/// @c Member is the name of the member we're trying to find.
13359ExprResult
13360Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13361 bool *NoArrowOperatorFound) {
13362 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13363, __extension__ __PRETTY_FUNCTION__))
13363 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13363, __extension__ __PRETTY_FUNCTION__))
;
13364
13365 if (checkPlaceholderForOverload(*this, Base))
13366 return ExprError();
13367
13368 SourceLocation Loc = Base->getExprLoc();
13369
13370 // C++ [over.ref]p1:
13371 //
13372 // [...] An expression x->m is interpreted as (x.operator->())->m
13373 // for a class object x of type T if T::operator->() exists and if
13374 // the operator is selected as the best match function by the
13375 // overload resolution mechanism (13.3).
13376 DeclarationName OpName =
13377 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13378 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13379 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13380
13381 if (RequireCompleteType(Loc, Base->getType(),
13382 diag::err_typecheck_incomplete_tag, Base))
13383 return ExprError();
13384
13385 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13386 LookupQualifiedName(R, BaseRecord->getDecl());
13387 R.suppressDiagnostics();
13388
13389 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13390 Oper != OperEnd; ++Oper) {
13391 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13392 None, CandidateSet, /*SuppressUserConversions=*/false);
13393 }
13394
13395 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13396
13397 // Perform overload resolution.
13398 OverloadCandidateSet::iterator Best;
13399 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13400 case OR_Success:
13401 // Overload resolution succeeded; we'll build the call below.
13402 break;
13403
13404 case OR_No_Viable_Function:
13405 if (CandidateSet.empty()) {
13406 QualType BaseType = Base->getType();
13407 if (NoArrowOperatorFound) {
13408 // Report this specific error to the caller instead of emitting a
13409 // diagnostic, as requested.
13410 *NoArrowOperatorFound = true;
13411 return ExprError();
13412 }
13413 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13414 << BaseType << Base->getSourceRange();
13415 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13416 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13417 << FixItHint::CreateReplacement(OpLoc, ".");
13418 }
13419 } else
13420 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13421 << "operator->" << Base->getSourceRange();
13422 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13423 return ExprError();
13424
13425 case OR_Ambiguous:
13426 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
13427 << "->" << Base->getType() << Base->getSourceRange();
13428 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
13429 return ExprError();
13430
13431 case OR_Deleted:
13432 Diag(OpLoc, diag::err_ovl_deleted_oper)
13433 << Best->Function->isDeleted()
13434 << "->"
13435 << getDeletedOrUnavailableSuffix(Best->Function)
13436 << Base->getSourceRange();
13437 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
13438 return ExprError();
13439 }
13440
13441 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13442
13443 // Convert the object parameter.
13444 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13445 ExprResult BaseResult =
13446 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13447 Best->FoundDecl, Method);
13448 if (BaseResult.isInvalid())
13449 return ExprError();
13450 Base = BaseResult.get();
13451
13452 // Build the operator call.
13453 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13454 Base, HadMultipleCandidates, OpLoc);
13455 if (FnExpr.isInvalid())
13456 return ExprError();
13457
13458 QualType ResultTy = Method->getReturnType();
13459 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13460 ResultTy = ResultTy.getNonLValueExprType(Context);
13461 CXXOperatorCallExpr *TheCall =
13462 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13463 Base, ResultTy, VK, OpLoc, FPOptions());
13464
13465 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13466 return ExprError();
13467
13468 if (CheckFunctionCall(Method, TheCall,
13469 Method->getType()->castAs<FunctionProtoType>()))
13470 return ExprError();
13471
13472 return MaybeBindToTemporary(TheCall);
13473}
13474
13475/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13476/// a literal operator described by the provided lookup results.
13477ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13478 DeclarationNameInfo &SuffixInfo,
13479 ArrayRef<Expr*> Args,
13480 SourceLocation LitEndLoc,
13481 TemplateArgumentListInfo *TemplateArgs) {
13482 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13483
13484 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13485 OverloadCandidateSet::CSK_Normal);
13486 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13487 /*SuppressUserConversions=*/true);
13488
13489 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13490
13491 // Perform overload resolution. This will usually be trivial, but might need
13492 // to perform substitutions for a literal operator template.
13493 OverloadCandidateSet::iterator Best;
13494 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13495 case OR_Success:
13496 case OR_Deleted:
13497 break;
13498
13499 case OR_No_Viable_Function:
13500 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13501 << R.getLookupName();
13502 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13503 return ExprError();
13504
13505 case OR_Ambiguous:
13506 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13507 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13508 return ExprError();
13509 }
13510
13511 FunctionDecl *FD = Best->Function;
13512 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13513 nullptr, HadMultipleCandidates,
13514 SuffixInfo.getLoc(),
13515 SuffixInfo.getInfo());
13516 if (Fn.isInvalid())
13517 return true;
13518
13519 // Check the argument types. This should almost always be a no-op, except
13520 // that array-to-pointer decay is applied to string literals.
13521 Expr *ConvArgs[2];
13522 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13523 ExprResult InputInit = PerformCopyInitialization(
13524 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13525 SourceLocation(), Args[ArgIdx]);
13526 if (InputInit.isInvalid())
13527 return true;
13528 ConvArgs[ArgIdx] = InputInit.get();
13529 }
13530
13531 QualType ResultTy = FD->getReturnType();
13532 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13533 ResultTy = ResultTy.getNonLValueExprType(Context);
13534
13535 UserDefinedLiteral *UDL =
13536 new (Context) UserDefinedLiteral(Context, Fn.get(),
13537 llvm::makeArrayRef(ConvArgs, Args.size()),
13538 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13539
13540 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13541 return ExprError();
13542
13543 if (CheckFunctionCall(FD, UDL, nullptr))
13544 return ExprError();
13545
13546 return MaybeBindToTemporary(UDL);
13547}
13548
13549/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13550/// given LookupResult is non-empty, it is assumed to describe a member which
13551/// will be invoked. Otherwise, the function will be found via argument
13552/// dependent lookup.
13553/// CallExpr is set to a valid expression and FRS_Success returned on success,
13554/// otherwise CallExpr is set to ExprError() and some non-success value
13555/// is returned.
13556Sema::ForRangeStatus
13557Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13558 SourceLocation RangeLoc,
13559 const DeclarationNameInfo &NameInfo,
13560 LookupResult &MemberLookup,
13561 OverloadCandidateSet *CandidateSet,
13562 Expr *Range, ExprResult *CallExpr) {
13563 Scope *S = nullptr;
13564
13565 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13566 if (!MemberLookup.empty()) {
13567 ExprResult MemberRef =
13568 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13569 /*IsPtr=*/false, CXXScopeSpec(),
13570 /*TemplateKWLoc=*/SourceLocation(),
13571 /*FirstQualifierInScope=*/nullptr,
13572 MemberLookup,
13573 /*TemplateArgs=*/nullptr, S);
13574 if (MemberRef.isInvalid()) {
13575 *CallExpr = ExprError();
13576 return FRS_DiagnosticIssued;
13577 }
13578 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13579 if (CallExpr->isInvalid()) {
13580 *CallExpr = ExprError();
13581 return FRS_DiagnosticIssued;
13582 }
13583 } else {
13584 UnresolvedSet<0> FoundNames;
13585 UnresolvedLookupExpr *Fn =
13586 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13587 NestedNameSpecifierLoc(), NameInfo,
13588 /*NeedsADL=*/true, /*Overloaded=*/false,
13589 FoundNames.begin(), FoundNames.end());
13590
13591 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13592 CandidateSet, CallExpr);
13593 if (CandidateSet->empty() || CandidateSetError) {
13594 *CallExpr = ExprError();
13595 return FRS_NoViableFunction;
13596 }
13597 OverloadCandidateSet::iterator Best;
13598 OverloadingResult OverloadResult =
13599 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13600
13601 if (OverloadResult == OR_No_Viable_Function) {
13602 *CallExpr = ExprError();
13603 return FRS_NoViableFunction;
13604 }
13605 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13606 Loc, nullptr, CandidateSet, &Best,
13607 OverloadResult,
13608 /*AllowTypoCorrection=*/false);
13609 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13610 *CallExpr = ExprError();
13611 return FRS_DiagnosticIssued;
13612 }
13613 }
13614 return FRS_Success;
13615}
13616
13617
13618/// FixOverloadedFunctionReference - E is an expression that refers to
13619/// a C++ overloaded function (possibly with some parentheses and
13620/// perhaps a '&' around it). We have resolved the overloaded function
13621/// to the function declaration Fn, so patch up the expression E to
13622/// refer (possibly indirectly) to Fn. Returns the new expr.
13623Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13624 FunctionDecl *Fn) {
13625 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13626 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13627 Found, Fn);
13628 if (SubExpr == PE->getSubExpr())
13629 return PE;
13630
13631 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13632 }
13633
13634 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13635 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13636 Found, Fn);
13637 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13639, __extension__ __PRETTY_FUNCTION__))
13638 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13639, __extension__ __PRETTY_FUNCTION__))
13639 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13639, __extension__ __PRETTY_FUNCTION__))
;
13640 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13640, __extension__ __PRETTY_FUNCTION__))
;
13641 if (SubExpr == ICE->getSubExpr())
13642 return ICE;
13643
13644 return ImplicitCastExpr::Create(Context, ICE->getType(),
13645 ICE->getCastKind(),
13646 SubExpr, nullptr,
13647 ICE->getValueKind());
13648 }
13649
13650 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13651 if (!GSE->isResultDependent()) {
13652 Expr *SubExpr =
13653 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13654 if (SubExpr == GSE->getResultExpr())
13655 return GSE;
13656
13657 // Replace the resulting type information before rebuilding the generic
13658 // selection expression.
13659 ArrayRef<Expr *> A = GSE->getAssocExprs();
13660 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13661 unsigned ResultIdx = GSE->getResultIndex();
13662 AssocExprs[ResultIdx] = SubExpr;
13663
13664 return new (Context) GenericSelectionExpr(
13665 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13666 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13667 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13668 ResultIdx);
13669 }
13670 // Rather than fall through to the unreachable, return the original generic
13671 // selection expression.
13672 return GSE;
13673 }
13674
13675 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13676 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13677, __extension__ __PRETTY_FUNCTION__))
13677 "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13677, __extension__ __PRETTY_FUNCTION__))
;
13678 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13679 if (Method->isStatic()) {
13680 // Do nothing: static member functions aren't any different
13681 // from non-member functions.
13682 } else {
13683 // Fix the subexpression, which really has to be an
13684 // UnresolvedLookupExpr holding an overloaded member function
13685 // or template.
13686 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13687 Found, Fn);
13688 if (SubExpr == UnOp->getSubExpr())
13689 return UnOp;
13690
13691 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13692, __extension__ __PRETTY_FUNCTION__))
13692 && "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13692, __extension__ __PRETTY_FUNCTION__))
;
13693 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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13694, __extension__ __PRETTY_FUNCTION__))
13694 && "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~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13694, __extension__ __PRETTY_FUNCTION__))
;
13695
13696 // We have taken the address of a pointer to member
13697 // function. Perform the computation here so that we get the
13698 // appropriate pointer to member type.
13699 QualType ClassType
13700 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13701 QualType MemPtrType
13702 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13703 // Under the MS ABI, lock down the inheritance model now.
13704 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13705 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13706
13707 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13708 VK_RValue, OK_Ordinary,
13709 UnOp->getOperatorLoc(), false);
13710 }
13711 }
13712 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13713 Found, Fn);
13714 if (SubExpr == UnOp->getSubExpr())
13715 return UnOp;
13716
13717 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13718 Context.getPointerType(SubExpr->getType()),
13719 VK_RValue, OK_Ordinary,
13720 UnOp->getOperatorLoc(), false);
13721 }
13722
13723 // C++ [except.spec]p17:
13724 // An exception-specification is considered to be needed when:
13725 // - in an expression the function is the unique lookup result or the
13726 // selected member of a set of overloaded functions
13727 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13728 ResolveExceptionSpec(E->getExprLoc(), FPT);
13729
13730 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13731 // FIXME: avoid copy.
13732 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13733 if (ULE->hasExplicitTemplateArgs()) {
13734 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13735 TemplateArgs = &TemplateArgsBuffer;
13736 }
13737
13738 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13739 ULE->getQualifierLoc(),
13740 ULE->getTemplateKeywordLoc(),
13741 Fn,
13742 /*enclosing*/ false, // FIXME?
13743 ULE->getNameLoc(),
13744 Fn->getType(),
13745 VK_LValue,
13746 Found.getDecl(),
13747 TemplateArgs);
13748 MarkDeclRefReferenced(DRE);
13749 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13750 return DRE;
13751 }
13752
13753 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13754 // FIXME: avoid copy.
13755 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13756 if (MemExpr->hasExplicitTemplateArgs()) {
13757 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13758 TemplateArgs = &TemplateArgsBuffer;
13759 }
13760
13761 Expr *Base;
13762
13763 // If we're filling in a static method where we used to have an
13764 // implicit member access, rewrite to a simple decl ref.
13765 if (MemExpr->isImplicitAccess()) {
13766 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13767 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13768 MemExpr->getQualifierLoc(),
13769 MemExpr->getTemplateKeywordLoc(),
13770 Fn,
13771 /*enclosing*/ false,
13772 MemExpr->getMemberLoc(),
13773 Fn->getType(),
13774 VK_LValue,
13775 Found.getDecl(),
13776 TemplateArgs);
13777 MarkDeclRefReferenced(DRE);
13778 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13779 return DRE;
13780 } else {
13781 SourceLocation Loc = MemExpr->getMemberLoc();
13782 if (MemExpr->getQualifier())
13783 Loc = MemExpr->getQualifierLoc().getBeginLoc();
13784 CheckCXXThisCapture(Loc);
13785 Base = new (Context) CXXThisExpr(Loc,
13786 MemExpr->getBaseType(),
13787 /*isImplicit=*/true);
13788 }
13789 } else
13790 Base = MemExpr->getBase();
13791
13792 ExprValueKind valueKind;
13793 QualType type;
13794 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13795 valueKind = VK_LValue;
13796 type = Fn->getType();
13797 } else {
13798 valueKind = VK_RValue;
13799 type = Context.BoundMemberTy;
13800 }
13801
13802 MemberExpr *ME = MemberExpr::Create(
13803 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13804 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13805 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13806 OK_Ordinary);
13807 ME->setHadMultipleCandidates(true);
13808 MarkMemberReferenced(ME);
13809 return ME;
13810 }
13811
13812 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaOverload.cpp"
, 13812)
;
13813}
13814
13815ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13816 DeclAccessPair Found,
13817 FunctionDecl *Fn) {
13818 return FixOverloadedFunctionReference(E.get(), Found, Fn);
13819}