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/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37
38 using namespace clang;
39 using namespace sema;
40
functionHasPassObjectSizeParams(const FunctionDecl * FD)41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42 return llvm::any_of(FD->parameters(),
43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
44 }
45
46 /// A convenience routine for creating a decayed reference to a function.
47 static ExprResult
CreateFunctionRefExpr(Sema & S,FunctionDecl * Fn,NamedDecl * FoundDecl,bool HadMultipleCandidates,SourceLocation Loc=SourceLocation (),const DeclarationNameLoc & LocInfo=DeclarationNameLoc ())48 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
49 bool HadMultipleCandidates,
50 SourceLocation Loc = SourceLocation(),
51 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
52 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
53 return ExprError();
54 // If FoundDecl is different from Fn (such as if one is a template
55 // and the other a specialization), make sure DiagnoseUseOfDecl is
56 // called on both.
57 // FIXME: This would be more comprehensively addressed by modifying
58 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
59 // being used.
60 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
61 return ExprError();
62 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
63 VK_LValue, Loc, LocInfo);
64 if (HadMultipleCandidates)
65 DRE->setHadMultipleCandidates(true);
66
67 S.MarkDeclRefReferenced(DRE);
68 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
69 CK_FunctionToPointerDecay);
70 }
71
72 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
73 bool InOverloadResolution,
74 StandardConversionSequence &SCS,
75 bool CStyle,
76 bool AllowObjCWritebackConversion);
77
78 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79 QualType &ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
82 bool CStyle);
83 static OverloadingResult
84 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
85 UserDefinedConversionSequence& User,
86 OverloadCandidateSet& Conversions,
87 bool AllowExplicit,
88 bool AllowObjCConversionOnExplicit);
89
90
91 static ImplicitConversionSequence::CompareKind
92 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
93 const StandardConversionSequence& SCS1,
94 const StandardConversionSequence& SCS2);
95
96 static ImplicitConversionSequence::CompareKind
97 CompareQualificationConversions(Sema &S,
98 const StandardConversionSequence& SCS1,
99 const StandardConversionSequence& SCS2);
100
101 static ImplicitConversionSequence::CompareKind
102 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
103 const StandardConversionSequence& SCS1,
104 const StandardConversionSequence& SCS2);
105
106 /// GetConversionRank - Retrieve the implicit conversion rank
107 /// corresponding to the given implicit conversion kind.
GetConversionRank(ImplicitConversionKind Kind)108 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
109 static const ImplicitConversionRank
110 Rank[(int)ICK_Num_Conversion_Kinds] = {
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Promotion,
118 ICR_Promotion,
119 ICR_Promotion,
120 ICR_Conversion,
121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Complex_Real_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Writeback_Conversion,
135 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
136 // it was omitted by the patch that added
137 // ICK_Zero_Event_Conversion
138 ICR_C_Conversion
139 };
140 return Rank[(int)Kind];
141 }
142
143 /// GetImplicitConversionName - Return the name of this kind of
144 /// implicit conversion.
GetImplicitConversionName(ImplicitConversionKind Kind)145 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
146 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
147 "No conversion",
148 "Lvalue-to-rvalue",
149 "Array-to-pointer",
150 "Function-to-pointer",
151 "Noreturn adjustment",
152 "Qualification",
153 "Integral promotion",
154 "Floating point promotion",
155 "Complex promotion",
156 "Integral conversion",
157 "Floating conversion",
158 "Complex conversion",
159 "Floating-integral conversion",
160 "Pointer conversion",
161 "Pointer-to-member conversion",
162 "Boolean conversion",
163 "Compatible-types conversion",
164 "Derived-to-base conversion",
165 "Vector conversion",
166 "Vector splat",
167 "Complex-real conversion",
168 "Block Pointer conversion",
169 "Transparent Union Conversion",
170 "Writeback conversion",
171 "OpenCL Zero Event Conversion",
172 "C specific type conversion"
173 };
174 return Name[Kind];
175 }
176
177 /// StandardConversionSequence - Set the standard conversion
178 /// sequence to the identity conversion.
setAsIdentityConversion()179 void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
183 DeprecatedStringLiteralToCharPtr = false;
184 QualificationIncludesObjCLifetime = false;
185 ReferenceBinding = false;
186 DirectBinding = false;
187 IsLvalueReference = true;
188 BindsToFunctionLvalue = false;
189 BindsToRvalue = false;
190 BindsImplicitObjectArgumentWithoutRefQualifier = false;
191 ObjCLifetimeConversionBinding = false;
192 CopyConstructor = nullptr;
193 }
194
195 /// getRank - Retrieve the rank of this standard conversion sequence
196 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
197 /// implicit conversions.
getRank() const198 ImplicitConversionRank StandardConversionSequence::getRank() const {
199 ImplicitConversionRank Rank = ICR_Exact_Match;
200 if (GetConversionRank(First) > Rank)
201 Rank = GetConversionRank(First);
202 if (GetConversionRank(Second) > Rank)
203 Rank = GetConversionRank(Second);
204 if (GetConversionRank(Third) > Rank)
205 Rank = GetConversionRank(Third);
206 return Rank;
207 }
208
209 /// isPointerConversionToBool - Determines whether this conversion is
210 /// a conversion of a pointer or pointer-to-member to bool. This is
211 /// used as part of the ranking of standard conversion sequences
212 /// (C++ 13.3.3.2p4).
isPointerConversionToBool() const213 bool StandardConversionSequence::isPointerConversionToBool() const {
214 // Note that FromType has not necessarily been transformed by the
215 // array-to-pointer or function-to-pointer implicit conversions, so
216 // check for their presence as well as checking whether FromType is
217 // a pointer.
218 if (getToType(1)->isBooleanType() &&
219 (getFromType()->isPointerType() ||
220 getFromType()->isObjCObjectPointerType() ||
221 getFromType()->isBlockPointerType() ||
222 getFromType()->isNullPtrType() ||
223 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
224 return true;
225
226 return false;
227 }
228
229 /// isPointerConversionToVoidPointer - Determines whether this
230 /// conversion is a conversion of a pointer to a void pointer. This is
231 /// used as part of the ranking of standard conversion sequences (C++
232 /// 13.3.3.2p4).
233 bool
234 StandardConversionSequence::
isPointerConversionToVoidPointer(ASTContext & Context) const235 isPointerConversionToVoidPointer(ASTContext& Context) const {
236 QualType FromType = getFromType();
237 QualType ToType = getToType(1);
238
239 // Note that FromType has not necessarily been transformed by the
240 // array-to-pointer implicit conversion, so check for its presence
241 // and redo the conversion to get a pointer.
242 if (First == ICK_Array_To_Pointer)
243 FromType = Context.getArrayDecayedType(FromType);
244
245 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
246 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
247 return ToPtrType->getPointeeType()->isVoidType();
248
249 return false;
250 }
251
252 /// Skip any implicit casts which could be either part of a narrowing conversion
253 /// or after one in an implicit conversion.
IgnoreNarrowingConversion(const Expr * Converted)254 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
255 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
256 switch (ICE->getCastKind()) {
257 case CK_NoOp:
258 case CK_IntegralCast:
259 case CK_IntegralToBoolean:
260 case CK_IntegralToFloating:
261 case CK_BooleanToSignedIntegral:
262 case CK_FloatingToIntegral:
263 case CK_FloatingToBoolean:
264 case CK_FloatingCast:
265 Converted = ICE->getSubExpr();
266 continue;
267
268 default:
269 return Converted;
270 }
271 }
272
273 return Converted;
274 }
275
276 /// Check if this standard conversion sequence represents a narrowing
277 /// conversion, according to C++11 [dcl.init.list]p7.
278 ///
279 /// \param Ctx The AST context.
280 /// \param Converted The result of applying this standard conversion sequence.
281 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
282 /// value of the expression prior to the narrowing conversion.
283 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
284 /// type of the expression prior to the narrowing conversion.
285 NarrowingKind
getNarrowingKind(ASTContext & Ctx,const Expr * Converted,APValue & ConstantValue,QualType & ConstantType) const286 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
287 const Expr *Converted,
288 APValue &ConstantValue,
289 QualType &ConstantType) const {
290 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
291
292 // C++11 [dcl.init.list]p7:
293 // A narrowing conversion is an implicit conversion ...
294 QualType FromType = getToType(0);
295 QualType ToType = getToType(1);
296
297 // A conversion to an enumeration type is narrowing if the conversion to
298 // the underlying type is narrowing. This only arises for expressions of
299 // the form 'Enum{init}'.
300 if (auto *ET = ToType->getAs<EnumType>())
301 ToType = ET->getDecl()->getIntegerType();
302
303 switch (Second) {
304 // 'bool' is an integral type; dispatch to the right place to handle it.
305 case ICK_Boolean_Conversion:
306 if (FromType->isRealFloatingType())
307 goto FloatingIntegralConversion;
308 if (FromType->isIntegralOrUnscopedEnumerationType())
309 goto IntegralConversion;
310 // Boolean conversions can be from pointers and pointers to members
311 // [conv.bool], and those aren't considered narrowing conversions.
312 return NK_Not_Narrowing;
313
314 // -- from a floating-point type to an integer type, or
315 //
316 // -- from an integer type or unscoped enumeration type to a floating-point
317 // type, except where the source is a constant expression and the actual
318 // value after conversion will fit into the target type and will produce
319 // the original value when converted back to the original type, or
320 case ICK_Floating_Integral:
321 FloatingIntegralConversion:
322 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
323 return NK_Type_Narrowing;
324 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
325 llvm::APSInt IntConstantValue;
326 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
327 if (Initializer &&
328 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
329 // Convert the integer to the floating type.
330 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
331 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
332 llvm::APFloat::rmNearestTiesToEven);
333 // And back.
334 llvm::APSInt ConvertedValue = IntConstantValue;
335 bool ignored;
336 Result.convertToInteger(ConvertedValue,
337 llvm::APFloat::rmTowardZero, &ignored);
338 // If the resulting value is different, this was a narrowing conversion.
339 if (IntConstantValue != ConvertedValue) {
340 ConstantValue = APValue(IntConstantValue);
341 ConstantType = Initializer->getType();
342 return NK_Constant_Narrowing;
343 }
344 } else {
345 // Variables are always narrowings.
346 return NK_Variable_Narrowing;
347 }
348 }
349 return NK_Not_Narrowing;
350
351 // -- from long double to double or float, or from double to float, except
352 // where the source is a constant expression and the actual value after
353 // conversion is within the range of values that can be represented (even
354 // if it cannot be represented exactly), or
355 case ICK_Floating_Conversion:
356 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
357 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
358 // FromType is larger than ToType.
359 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
360 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
361 // Constant!
362 assert(ConstantValue.isFloat());
363 llvm::APFloat FloatVal = ConstantValue.getFloat();
364 // Convert the source value into the target type.
365 bool ignored;
366 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
367 Ctx.getFloatTypeSemantics(ToType),
368 llvm::APFloat::rmNearestTiesToEven, &ignored);
369 // If there was no overflow, the source value is within the range of
370 // values that can be represented.
371 if (ConvertStatus & llvm::APFloat::opOverflow) {
372 ConstantType = Initializer->getType();
373 return NK_Constant_Narrowing;
374 }
375 } else {
376 return NK_Variable_Narrowing;
377 }
378 }
379 return NK_Not_Narrowing;
380
381 // -- from an integer type or unscoped enumeration type to an integer type
382 // that cannot represent all the values of the original type, except where
383 // the source is a constant expression and the actual value after
384 // conversion will fit into the target type and will produce the original
385 // value when converted back to the original type.
386 case ICK_Integral_Conversion:
387 IntegralConversion: {
388 assert(FromType->isIntegralOrUnscopedEnumerationType());
389 assert(ToType->isIntegralOrUnscopedEnumerationType());
390 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
391 const unsigned FromWidth = Ctx.getIntWidth(FromType);
392 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
393 const unsigned ToWidth = Ctx.getIntWidth(ToType);
394
395 if (FromWidth > ToWidth ||
396 (FromWidth == ToWidth && FromSigned != ToSigned) ||
397 (FromSigned && !ToSigned)) {
398 // Not all values of FromType can be represented in ToType.
399 llvm::APSInt InitializerValue;
400 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
401 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
402 // Such conversions on variables are always narrowing.
403 return NK_Variable_Narrowing;
404 }
405 bool Narrowing = false;
406 if (FromWidth < ToWidth) {
407 // Negative -> unsigned is narrowing. Otherwise, more bits is never
408 // narrowing.
409 if (InitializerValue.isSigned() && InitializerValue.isNegative())
410 Narrowing = true;
411 } else {
412 // Add a bit to the InitializerValue so we don't have to worry about
413 // signed vs. unsigned comparisons.
414 InitializerValue = InitializerValue.extend(
415 InitializerValue.getBitWidth() + 1);
416 // Convert the initializer to and from the target width and signed-ness.
417 llvm::APSInt ConvertedValue = InitializerValue;
418 ConvertedValue = ConvertedValue.trunc(ToWidth);
419 ConvertedValue.setIsSigned(ToSigned);
420 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
421 ConvertedValue.setIsSigned(InitializerValue.isSigned());
422 // If the result is different, this was a narrowing conversion.
423 if (ConvertedValue != InitializerValue)
424 Narrowing = true;
425 }
426 if (Narrowing) {
427 ConstantType = Initializer->getType();
428 ConstantValue = APValue(InitializerValue);
429 return NK_Constant_Narrowing;
430 }
431 }
432 return NK_Not_Narrowing;
433 }
434
435 default:
436 // Other kinds of conversions are not narrowings.
437 return NK_Not_Narrowing;
438 }
439 }
440
441 /// dump - Print this standard conversion sequence to standard
442 /// error. Useful for debugging overloading issues.
dump() const443 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
444 raw_ostream &OS = llvm::errs();
445 bool PrintedSomething = false;
446 if (First != ICK_Identity) {
447 OS << GetImplicitConversionName(First);
448 PrintedSomething = true;
449 }
450
451 if (Second != ICK_Identity) {
452 if (PrintedSomething) {
453 OS << " -> ";
454 }
455 OS << GetImplicitConversionName(Second);
456
457 if (CopyConstructor) {
458 OS << " (by copy constructor)";
459 } else if (DirectBinding) {
460 OS << " (direct reference binding)";
461 } else if (ReferenceBinding) {
462 OS << " (reference binding)";
463 }
464 PrintedSomething = true;
465 }
466
467 if (Third != ICK_Identity) {
468 if (PrintedSomething) {
469 OS << " -> ";
470 }
471 OS << GetImplicitConversionName(Third);
472 PrintedSomething = true;
473 }
474
475 if (!PrintedSomething) {
476 OS << "No conversions required";
477 }
478 }
479
480 /// dump - Print this user-defined conversion sequence to standard
481 /// error. Useful for debugging overloading issues.
dump() const482 void UserDefinedConversionSequence::dump() const {
483 raw_ostream &OS = llvm::errs();
484 if (Before.First || Before.Second || Before.Third) {
485 Before.dump();
486 OS << " -> ";
487 }
488 if (ConversionFunction)
489 OS << '\'' << *ConversionFunction << '\'';
490 else
491 OS << "aggregate initialization";
492 if (After.First || After.Second || After.Third) {
493 OS << " -> ";
494 After.dump();
495 }
496 }
497
498 /// dump - Print this implicit conversion sequence to standard
499 /// error. Useful for debugging overloading issues.
dump() const500 void ImplicitConversionSequence::dump() const {
501 raw_ostream &OS = llvm::errs();
502 if (isStdInitializerListElement())
503 OS << "Worst std::initializer_list element conversion: ";
504 switch (ConversionKind) {
505 case StandardConversion:
506 OS << "Standard conversion: ";
507 Standard.dump();
508 break;
509 case UserDefinedConversion:
510 OS << "User-defined conversion: ";
511 UserDefined.dump();
512 break;
513 case EllipsisConversion:
514 OS << "Ellipsis conversion";
515 break;
516 case AmbiguousConversion:
517 OS << "Ambiguous conversion";
518 break;
519 case BadConversion:
520 OS << "Bad conversion";
521 break;
522 }
523
524 OS << "\n";
525 }
526
construct()527 void AmbiguousConversionSequence::construct() {
528 new (&conversions()) ConversionSet();
529 }
530
destruct()531 void AmbiguousConversionSequence::destruct() {
532 conversions().~ConversionSet();
533 }
534
535 void
copyFrom(const AmbiguousConversionSequence & O)536 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
537 FromTypePtr = O.FromTypePtr;
538 ToTypePtr = O.ToTypePtr;
539 new (&conversions()) ConversionSet(O.conversions());
540 }
541
542 namespace {
543 // Structure used by DeductionFailureInfo to store
544 // template argument information.
545 struct DFIArguments {
546 TemplateArgument FirstArg;
547 TemplateArgument SecondArg;
548 };
549 // Structure used by DeductionFailureInfo to store
550 // template parameter and template argument information.
551 struct DFIParamWithArguments : DFIArguments {
552 TemplateParameter Param;
553 };
554 // Structure used by DeductionFailureInfo to store template argument
555 // information and the index of the problematic call argument.
556 struct DFIDeducedMismatchArgs : DFIArguments {
557 TemplateArgumentList *TemplateArgs;
558 unsigned CallArgIndex;
559 };
560 }
561
562 /// \brief Convert from Sema's representation of template deduction information
563 /// to the form used in overload-candidate information.
564 DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext & Context,Sema::TemplateDeductionResult TDK,TemplateDeductionInfo & Info)565 clang::MakeDeductionFailureInfo(ASTContext &Context,
566 Sema::TemplateDeductionResult TDK,
567 TemplateDeductionInfo &Info) {
568 DeductionFailureInfo Result;
569 Result.Result = static_cast<unsigned>(TDK);
570 Result.HasDiagnostic = false;
571 switch (TDK) {
572 case Sema::TDK_Success:
573 case Sema::TDK_Invalid:
574 case Sema::TDK_InstantiationDepth:
575 case Sema::TDK_TooManyArguments:
576 case Sema::TDK_TooFewArguments:
577 case Sema::TDK_MiscellaneousDeductionFailure:
578 Result.Data = nullptr;
579 break;
580
581 case Sema::TDK_Incomplete:
582 case Sema::TDK_InvalidExplicitArguments:
583 Result.Data = Info.Param.getOpaqueValue();
584 break;
585
586 case Sema::TDK_DeducedMismatch: {
587 // FIXME: Should allocate from normal heap so that we can free this later.
588 auto *Saved = new (Context) DFIDeducedMismatchArgs;
589 Saved->FirstArg = Info.FirstArg;
590 Saved->SecondArg = Info.SecondArg;
591 Saved->TemplateArgs = Info.take();
592 Saved->CallArgIndex = Info.CallArgIndex;
593 Result.Data = Saved;
594 break;
595 }
596
597 case Sema::TDK_NonDeducedMismatch: {
598 // FIXME: Should allocate from normal heap so that we can free this later.
599 DFIArguments *Saved = new (Context) DFIArguments;
600 Saved->FirstArg = Info.FirstArg;
601 Saved->SecondArg = Info.SecondArg;
602 Result.Data = Saved;
603 break;
604 }
605
606 case Sema::TDK_Inconsistent:
607 case Sema::TDK_Underqualified: {
608 // FIXME: Should allocate from normal heap so that we can free this later.
609 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
610 Saved->Param = Info.Param;
611 Saved->FirstArg = Info.FirstArg;
612 Saved->SecondArg = Info.SecondArg;
613 Result.Data = Saved;
614 break;
615 }
616
617 case Sema::TDK_SubstitutionFailure:
618 Result.Data = Info.take();
619 if (Info.hasSFINAEDiagnostic()) {
620 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
621 SourceLocation(), PartialDiagnostic::NullDiagnostic());
622 Info.takeSFINAEDiagnostic(*Diag);
623 Result.HasDiagnostic = true;
624 }
625 break;
626
627 case Sema::TDK_FailedOverloadResolution:
628 Result.Data = Info.Expression;
629 break;
630 }
631
632 return Result;
633 }
634
Destroy()635 void DeductionFailureInfo::Destroy() {
636 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
637 case Sema::TDK_Success:
638 case Sema::TDK_Invalid:
639 case Sema::TDK_InstantiationDepth:
640 case Sema::TDK_Incomplete:
641 case Sema::TDK_TooManyArguments:
642 case Sema::TDK_TooFewArguments:
643 case Sema::TDK_InvalidExplicitArguments:
644 case Sema::TDK_FailedOverloadResolution:
645 break;
646
647 case Sema::TDK_Inconsistent:
648 case Sema::TDK_Underqualified:
649 case Sema::TDK_DeducedMismatch:
650 case Sema::TDK_NonDeducedMismatch:
651 // FIXME: Destroy the data?
652 Data = nullptr;
653 break;
654
655 case Sema::TDK_SubstitutionFailure:
656 // FIXME: Destroy the template argument list?
657 Data = nullptr;
658 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
659 Diag->~PartialDiagnosticAt();
660 HasDiagnostic = false;
661 }
662 break;
663
664 // Unhandled
665 case Sema::TDK_MiscellaneousDeductionFailure:
666 break;
667 }
668 }
669
getSFINAEDiagnostic()670 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
671 if (HasDiagnostic)
672 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
673 return nullptr;
674 }
675
getTemplateParameter()676 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
677 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
678 case Sema::TDK_Success:
679 case Sema::TDK_Invalid:
680 case Sema::TDK_InstantiationDepth:
681 case Sema::TDK_TooManyArguments:
682 case Sema::TDK_TooFewArguments:
683 case Sema::TDK_SubstitutionFailure:
684 case Sema::TDK_DeducedMismatch:
685 case Sema::TDK_NonDeducedMismatch:
686 case Sema::TDK_FailedOverloadResolution:
687 return TemplateParameter();
688
689 case Sema::TDK_Incomplete:
690 case Sema::TDK_InvalidExplicitArguments:
691 return TemplateParameter::getFromOpaqueValue(Data);
692
693 case Sema::TDK_Inconsistent:
694 case Sema::TDK_Underqualified:
695 return static_cast<DFIParamWithArguments*>(Data)->Param;
696
697 // Unhandled
698 case Sema::TDK_MiscellaneousDeductionFailure:
699 break;
700 }
701
702 return TemplateParameter();
703 }
704
getTemplateArgumentList()705 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
706 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
707 case Sema::TDK_Success:
708 case Sema::TDK_Invalid:
709 case Sema::TDK_InstantiationDepth:
710 case Sema::TDK_TooManyArguments:
711 case Sema::TDK_TooFewArguments:
712 case Sema::TDK_Incomplete:
713 case Sema::TDK_InvalidExplicitArguments:
714 case Sema::TDK_Inconsistent:
715 case Sema::TDK_Underqualified:
716 case Sema::TDK_NonDeducedMismatch:
717 case Sema::TDK_FailedOverloadResolution:
718 return nullptr;
719
720 case Sema::TDK_DeducedMismatch:
721 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
722
723 case Sema::TDK_SubstitutionFailure:
724 return static_cast<TemplateArgumentList*>(Data);
725
726 // Unhandled
727 case Sema::TDK_MiscellaneousDeductionFailure:
728 break;
729 }
730
731 return nullptr;
732 }
733
getFirstArg()734 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
735 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
736 case Sema::TDK_Success:
737 case Sema::TDK_Invalid:
738 case Sema::TDK_InstantiationDepth:
739 case Sema::TDK_Incomplete:
740 case Sema::TDK_TooManyArguments:
741 case Sema::TDK_TooFewArguments:
742 case Sema::TDK_InvalidExplicitArguments:
743 case Sema::TDK_SubstitutionFailure:
744 case Sema::TDK_FailedOverloadResolution:
745 return nullptr;
746
747 case Sema::TDK_Inconsistent:
748 case Sema::TDK_Underqualified:
749 case Sema::TDK_DeducedMismatch:
750 case Sema::TDK_NonDeducedMismatch:
751 return &static_cast<DFIArguments*>(Data)->FirstArg;
752
753 // Unhandled
754 case Sema::TDK_MiscellaneousDeductionFailure:
755 break;
756 }
757
758 return nullptr;
759 }
760
getSecondArg()761 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
762 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
763 case Sema::TDK_Success:
764 case Sema::TDK_Invalid:
765 case Sema::TDK_InstantiationDepth:
766 case Sema::TDK_Incomplete:
767 case Sema::TDK_TooManyArguments:
768 case Sema::TDK_TooFewArguments:
769 case Sema::TDK_InvalidExplicitArguments:
770 case Sema::TDK_SubstitutionFailure:
771 case Sema::TDK_FailedOverloadResolution:
772 return nullptr;
773
774 case Sema::TDK_Inconsistent:
775 case Sema::TDK_Underqualified:
776 case Sema::TDK_DeducedMismatch:
777 case Sema::TDK_NonDeducedMismatch:
778 return &static_cast<DFIArguments*>(Data)->SecondArg;
779
780 // Unhandled
781 case Sema::TDK_MiscellaneousDeductionFailure:
782 break;
783 }
784
785 return nullptr;
786 }
787
getExpr()788 Expr *DeductionFailureInfo::getExpr() {
789 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
790 Sema::TDK_FailedOverloadResolution)
791 return static_cast<Expr*>(Data);
792
793 return nullptr;
794 }
795
getCallArgIndex()796 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
797 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
798 Sema::TDK_DeducedMismatch)
799 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
800
801 return llvm::None;
802 }
803
destroyCandidates()804 void OverloadCandidateSet::destroyCandidates() {
805 for (iterator i = begin(), e = end(); i != e; ++i) {
806 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
807 i->Conversions[ii].~ImplicitConversionSequence();
808 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
809 i->DeductionFailure.Destroy();
810 }
811 }
812
clear()813 void OverloadCandidateSet::clear() {
814 destroyCandidates();
815 NumInlineSequences = 0;
816 Candidates.clear();
817 Functions.clear();
818 }
819
820 namespace {
821 class UnbridgedCastsSet {
822 struct Entry {
823 Expr **Addr;
824 Expr *Saved;
825 };
826 SmallVector<Entry, 2> Entries;
827
828 public:
save(Sema & S,Expr * & E)829 void save(Sema &S, Expr *&E) {
830 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
831 Entry entry = { &E, E };
832 Entries.push_back(entry);
833 E = S.stripARCUnbridgedCast(E);
834 }
835
restore()836 void restore() {
837 for (SmallVectorImpl<Entry>::iterator
838 i = Entries.begin(), e = Entries.end(); i != e; ++i)
839 *i->Addr = i->Saved;
840 }
841 };
842 }
843
844 /// checkPlaceholderForOverload - Do any interesting placeholder-like
845 /// preprocessing on the given expression.
846 ///
847 /// \param unbridgedCasts a collection to which to add unbridged casts;
848 /// without this, they will be immediately diagnosed as errors
849 ///
850 /// Return true on unrecoverable error.
851 static bool
checkPlaceholderForOverload(Sema & S,Expr * & E,UnbridgedCastsSet * unbridgedCasts=nullptr)852 checkPlaceholderForOverload(Sema &S, Expr *&E,
853 UnbridgedCastsSet *unbridgedCasts = nullptr) {
854 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
855 // We can't handle overloaded expressions here because overload
856 // resolution might reasonably tweak them.
857 if (placeholder->getKind() == BuiltinType::Overload) return false;
858
859 // If the context potentially accepts unbridged ARC casts, strip
860 // the unbridged cast and add it to the collection for later restoration.
861 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
862 unbridgedCasts) {
863 unbridgedCasts->save(S, E);
864 return false;
865 }
866
867 // Go ahead and check everything else.
868 ExprResult result = S.CheckPlaceholderExpr(E);
869 if (result.isInvalid())
870 return true;
871
872 E = result.get();
873 return false;
874 }
875
876 // Nothing to do.
877 return false;
878 }
879
880 /// checkArgPlaceholdersForOverload - Check a set of call operands for
881 /// placeholders.
checkArgPlaceholdersForOverload(Sema & S,MultiExprArg Args,UnbridgedCastsSet & unbridged)882 static bool checkArgPlaceholdersForOverload(Sema &S,
883 MultiExprArg Args,
884 UnbridgedCastsSet &unbridged) {
885 for (unsigned i = 0, e = Args.size(); i != e; ++i)
886 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
887 return true;
888
889 return false;
890 }
891
892 // IsOverload - Determine whether the given New declaration is an
893 // overload of the declarations in Old. This routine returns false if
894 // New and Old cannot be overloaded, e.g., if New has the same
895 // signature as some function in Old (C++ 1.3.10) or if the Old
896 // declarations aren't functions (or function templates) at all. When
897 // it does return false, MatchedDecl will point to the decl that New
898 // cannot be overloaded with. This decl may be a UsingShadowDecl on
899 // top of the underlying declaration.
900 //
901 // Example: Given the following input:
902 //
903 // void f(int, float); // #1
904 // void f(int, int); // #2
905 // int f(int, int); // #3
906 //
907 // When we process #1, there is no previous declaration of "f",
908 // so IsOverload will not be used.
909 //
910 // When we process #2, Old contains only the FunctionDecl for #1. By
911 // comparing the parameter types, we see that #1 and #2 are overloaded
912 // (since they have different signatures), so this routine returns
913 // false; MatchedDecl is unchanged.
914 //
915 // When we process #3, Old is an overload set containing #1 and #2. We
916 // compare the signatures of #3 to #1 (they're overloaded, so we do
917 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
918 // identical (return types of functions are not part of the
919 // signature), IsOverload returns false and MatchedDecl will be set to
920 // point to the FunctionDecl for #2.
921 //
922 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
923 // into a class by a using declaration. The rules for whether to hide
924 // shadow declarations ignore some properties which otherwise figure
925 // into a function template's signature.
926 Sema::OverloadKind
CheckOverload(Scope * S,FunctionDecl * New,const LookupResult & Old,NamedDecl * & Match,bool NewIsUsingDecl)927 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
928 NamedDecl *&Match, bool NewIsUsingDecl) {
929 for (LookupResult::iterator I = Old.begin(), E = Old.end();
930 I != E; ++I) {
931 NamedDecl *OldD = *I;
932
933 bool OldIsUsingDecl = false;
934 if (isa<UsingShadowDecl>(OldD)) {
935 OldIsUsingDecl = true;
936
937 // We can always introduce two using declarations into the same
938 // context, even if they have identical signatures.
939 if (NewIsUsingDecl) continue;
940
941 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
942 }
943
944 // A using-declaration does not conflict with another declaration
945 // if one of them is hidden.
946 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
947 continue;
948
949 // If either declaration was introduced by a using declaration,
950 // we'll need to use slightly different rules for matching.
951 // Essentially, these rules are the normal rules, except that
952 // function templates hide function templates with different
953 // return types or template parameter lists.
954 bool UseMemberUsingDeclRules =
955 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
956 !New->getFriendObjectKind();
957
958 if (FunctionDecl *OldF = OldD->getAsFunction()) {
959 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
960 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
961 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
962 continue;
963 }
964
965 if (!isa<FunctionTemplateDecl>(OldD) &&
966 !shouldLinkPossiblyHiddenDecl(*I, New))
967 continue;
968
969 Match = *I;
970 return Ovl_Match;
971 }
972 } else if (isa<UsingDecl>(OldD)) {
973 // We can overload with these, which can show up when doing
974 // redeclaration checks for UsingDecls.
975 assert(Old.getLookupKind() == LookupUsingDeclName);
976 } else if (isa<TagDecl>(OldD)) {
977 // We can always overload with tags by hiding them.
978 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
979 // Optimistically assume that an unresolved using decl will
980 // overload; if it doesn't, we'll have to diagnose during
981 // template instantiation.
982 } else {
983 // (C++ 13p1):
984 // Only function declarations can be overloaded; object and type
985 // declarations cannot be overloaded.
986 Match = *I;
987 return Ovl_NonFunction;
988 }
989 }
990
991 return Ovl_Overload;
992 }
993
IsOverload(FunctionDecl * New,FunctionDecl * Old,bool UseMemberUsingDeclRules,bool ConsiderCudaAttrs)994 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
995 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
996 // C++ [basic.start.main]p2: This function shall not be overloaded.
997 if (New->isMain())
998 return false;
999
1000 // MSVCRT user defined entry points cannot be overloaded.
1001 if (New->isMSVCRTEntryPoint())
1002 return false;
1003
1004 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1005 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1006
1007 // C++ [temp.fct]p2:
1008 // A function template can be overloaded with other function templates
1009 // and with normal (non-template) functions.
1010 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1011 return true;
1012
1013 // Is the function New an overload of the function Old?
1014 QualType OldQType = Context.getCanonicalType(Old->getType());
1015 QualType NewQType = Context.getCanonicalType(New->getType());
1016
1017 // Compare the signatures (C++ 1.3.10) of the two functions to
1018 // determine whether they are overloads. If we find any mismatch
1019 // in the signature, they are overloads.
1020
1021 // If either of these functions is a K&R-style function (no
1022 // prototype), then we consider them to have matching signatures.
1023 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1024 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1025 return false;
1026
1027 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1028 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1029
1030 // The signature of a function includes the types of its
1031 // parameters (C++ 1.3.10), which includes the presence or absence
1032 // of the ellipsis; see C++ DR 357).
1033 if (OldQType != NewQType &&
1034 (OldType->getNumParams() != NewType->getNumParams() ||
1035 OldType->isVariadic() != NewType->isVariadic() ||
1036 !FunctionParamTypesAreEqual(OldType, NewType)))
1037 return true;
1038
1039 // C++ [temp.over.link]p4:
1040 // The signature of a function template consists of its function
1041 // signature, its return type and its template parameter list. The names
1042 // of the template parameters are significant only for establishing the
1043 // relationship between the template parameters and the rest of the
1044 // signature.
1045 //
1046 // We check the return type and template parameter lists for function
1047 // templates first; the remaining checks follow.
1048 //
1049 // However, we don't consider either of these when deciding whether
1050 // a member introduced by a shadow declaration is hidden.
1051 if (!UseMemberUsingDeclRules && NewTemplate &&
1052 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1053 OldTemplate->getTemplateParameters(),
1054 false, TPL_TemplateMatch) ||
1055 OldType->getReturnType() != NewType->getReturnType()))
1056 return true;
1057
1058 // If the function is a class member, its signature includes the
1059 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1060 //
1061 // As part of this, also check whether one of the member functions
1062 // is static, in which case they are not overloads (C++
1063 // 13.1p2). While not part of the definition of the signature,
1064 // this check is important to determine whether these functions
1065 // can be overloaded.
1066 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1067 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1068 if (OldMethod && NewMethod &&
1069 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1070 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1071 if (!UseMemberUsingDeclRules &&
1072 (OldMethod->getRefQualifier() == RQ_None ||
1073 NewMethod->getRefQualifier() == RQ_None)) {
1074 // C++0x [over.load]p2:
1075 // - Member function declarations with the same name and the same
1076 // parameter-type-list as well as member function template
1077 // declarations with the same name, the same parameter-type-list, and
1078 // the same template parameter lists cannot be overloaded if any of
1079 // them, but not all, have a ref-qualifier (8.3.5).
1080 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1081 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1082 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1083 }
1084 return true;
1085 }
1086
1087 // We may not have applied the implicit const for a constexpr member
1088 // function yet (because we haven't yet resolved whether this is a static
1089 // or non-static member function). Add it now, on the assumption that this
1090 // is a redeclaration of OldMethod.
1091 unsigned OldQuals = OldMethod->getTypeQualifiers();
1092 unsigned NewQuals = NewMethod->getTypeQualifiers();
1093 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1094 !isa<CXXConstructorDecl>(NewMethod))
1095 NewQuals |= Qualifiers::Const;
1096
1097 // We do not allow overloading based off of '__restrict'.
1098 OldQuals &= ~Qualifiers::Restrict;
1099 NewQuals &= ~Qualifiers::Restrict;
1100 if (OldQuals != NewQuals)
1101 return true;
1102 }
1103
1104 // Though pass_object_size is placed on parameters and takes an argument, we
1105 // consider it to be a function-level modifier for the sake of function
1106 // identity. Either the function has one or more parameters with
1107 // pass_object_size or it doesn't.
1108 if (functionHasPassObjectSizeParams(New) !=
1109 functionHasPassObjectSizeParams(Old))
1110 return true;
1111
1112 // enable_if attributes are an order-sensitive part of the signature.
1113 for (specific_attr_iterator<EnableIfAttr>
1114 NewI = New->specific_attr_begin<EnableIfAttr>(),
1115 NewE = New->specific_attr_end<EnableIfAttr>(),
1116 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1117 OldE = Old->specific_attr_end<EnableIfAttr>();
1118 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1119 if (NewI == NewE || OldI == OldE)
1120 return true;
1121 llvm::FoldingSetNodeID NewID, OldID;
1122 NewI->getCond()->Profile(NewID, Context, true);
1123 OldI->getCond()->Profile(OldID, Context, true);
1124 if (NewID != OldID)
1125 return true;
1126 }
1127
1128 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1129 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1130 OldTarget = IdentifyCUDATarget(Old);
1131 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1132 return false;
1133
1134 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1135
1136 // Don't allow mixing of HD with other kinds. This guarantees that
1137 // we have only one viable function with this signature on any
1138 // side of CUDA compilation .
1139 // __global__ functions can't be overloaded based on attribute
1140 // difference because, like HD, they also exist on both sides.
1141 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) ||
1142 (NewTarget == CFT_Global) || (OldTarget == CFT_Global))
1143 return false;
1144
1145 // Allow overloading of functions with same signature, but
1146 // different CUDA target attributes.
1147 return NewTarget != OldTarget;
1148 }
1149
1150 // The signatures match; this is not an overload.
1151 return false;
1152 }
1153
1154 /// \brief Checks availability of the function depending on the current
1155 /// function context. Inside an unavailable function, unavailability is ignored.
1156 ///
1157 /// \returns true if \arg FD is unavailable and current context is inside
1158 /// an available function, false otherwise.
isFunctionConsideredUnavailable(FunctionDecl * FD)1159 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1160 if (!FD->isUnavailable())
1161 return false;
1162
1163 // Walk up the context of the caller.
1164 Decl *C = cast<Decl>(CurContext);
1165 do {
1166 if (C->isUnavailable())
1167 return false;
1168 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1169 return true;
1170 }
1171
1172 /// \brief Tries a user-defined conversion from From to ToType.
1173 ///
1174 /// Produces an implicit conversion sequence for when a standard conversion
1175 /// is not an option. See TryImplicitConversion for more information.
1176 static ImplicitConversionSequence
TryUserDefinedConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1177 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1178 bool SuppressUserConversions,
1179 bool AllowExplicit,
1180 bool InOverloadResolution,
1181 bool CStyle,
1182 bool AllowObjCWritebackConversion,
1183 bool AllowObjCConversionOnExplicit) {
1184 ImplicitConversionSequence ICS;
1185
1186 if (SuppressUserConversions) {
1187 // We're not in the case above, so there is no conversion that
1188 // we can perform.
1189 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1190 return ICS;
1191 }
1192
1193 // Attempt user-defined conversion.
1194 OverloadCandidateSet Conversions(From->getExprLoc(),
1195 OverloadCandidateSet::CSK_Normal);
1196 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1197 Conversions, AllowExplicit,
1198 AllowObjCConversionOnExplicit)) {
1199 case OR_Success:
1200 case OR_Deleted:
1201 ICS.setUserDefined();
1202 ICS.UserDefined.Before.setAsIdentityConversion();
1203 // C++ [over.ics.user]p4:
1204 // A conversion of an expression of class type to the same class
1205 // type is given Exact Match rank, and a conversion of an
1206 // expression of class type to a base class of that type is
1207 // given Conversion rank, in spite of the fact that a copy
1208 // constructor (i.e., a user-defined conversion function) is
1209 // called for those cases.
1210 if (CXXConstructorDecl *Constructor
1211 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1212 QualType FromCanon
1213 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1214 QualType ToCanon
1215 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1216 if (Constructor->isCopyConstructor() &&
1217 (FromCanon == ToCanon ||
1218 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1219 // Turn this into a "standard" conversion sequence, so that it
1220 // gets ranked with standard conversion sequences.
1221 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1222 ICS.setStandard();
1223 ICS.Standard.setAsIdentityConversion();
1224 ICS.Standard.setFromType(From->getType());
1225 ICS.Standard.setAllToTypes(ToType);
1226 ICS.Standard.CopyConstructor = Constructor;
1227 ICS.Standard.FoundCopyConstructor = Found;
1228 if (ToCanon != FromCanon)
1229 ICS.Standard.Second = ICK_Derived_To_Base;
1230 }
1231 }
1232 break;
1233
1234 case OR_Ambiguous:
1235 ICS.setAmbiguous();
1236 ICS.Ambiguous.setFromType(From->getType());
1237 ICS.Ambiguous.setToType(ToType);
1238 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1239 Cand != Conversions.end(); ++Cand)
1240 if (Cand->Viable)
1241 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1242 break;
1243
1244 // Fall through.
1245 case OR_No_Viable_Function:
1246 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1247 break;
1248 }
1249
1250 return ICS;
1251 }
1252
1253 /// TryImplicitConversion - Attempt to perform an implicit conversion
1254 /// from the given expression (Expr) to the given type (ToType). This
1255 /// function returns an implicit conversion sequence that can be used
1256 /// to perform the initialization. Given
1257 ///
1258 /// void f(float f);
1259 /// void g(int i) { f(i); }
1260 ///
1261 /// this routine would produce an implicit conversion sequence to
1262 /// describe the initialization of f from i, which will be a standard
1263 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1264 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1265 //
1266 /// Note that this routine only determines how the conversion can be
1267 /// performed; it does not actually perform the conversion. As such,
1268 /// it will not produce any diagnostics if no conversion is available,
1269 /// but will instead return an implicit conversion sequence of kind
1270 /// "BadConversion".
1271 ///
1272 /// If @p SuppressUserConversions, then user-defined conversions are
1273 /// not permitted.
1274 /// If @p AllowExplicit, then explicit user-defined conversions are
1275 /// permitted.
1276 ///
1277 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1278 /// writeback conversion, which allows __autoreleasing id* parameters to
1279 /// be initialized with __strong id* or __weak id* arguments.
1280 static ImplicitConversionSequence
TryImplicitConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion,bool AllowObjCConversionOnExplicit)1281 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1282 bool SuppressUserConversions,
1283 bool AllowExplicit,
1284 bool InOverloadResolution,
1285 bool CStyle,
1286 bool AllowObjCWritebackConversion,
1287 bool AllowObjCConversionOnExplicit) {
1288 ImplicitConversionSequence ICS;
1289 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1290 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1291 ICS.setStandard();
1292 return ICS;
1293 }
1294
1295 if (!S.getLangOpts().CPlusPlus) {
1296 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1297 return ICS;
1298 }
1299
1300 // C++ [over.ics.user]p4:
1301 // A conversion of an expression of class type to the same class
1302 // type is given Exact Match rank, and a conversion of an
1303 // expression of class type to a base class of that type is
1304 // given Conversion rank, in spite of the fact that a copy/move
1305 // constructor (i.e., a user-defined conversion function) is
1306 // called for those cases.
1307 QualType FromType = From->getType();
1308 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1309 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1310 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1311 ICS.setStandard();
1312 ICS.Standard.setAsIdentityConversion();
1313 ICS.Standard.setFromType(FromType);
1314 ICS.Standard.setAllToTypes(ToType);
1315
1316 // We don't actually check at this point whether there is a valid
1317 // copy/move constructor, since overloading just assumes that it
1318 // exists. When we actually perform initialization, we'll find the
1319 // appropriate constructor to copy the returned object, if needed.
1320 ICS.Standard.CopyConstructor = nullptr;
1321
1322 // Determine whether this is considered a derived-to-base conversion.
1323 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1324 ICS.Standard.Second = ICK_Derived_To_Base;
1325
1326 return ICS;
1327 }
1328
1329 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1330 AllowExplicit, InOverloadResolution, CStyle,
1331 AllowObjCWritebackConversion,
1332 AllowObjCConversionOnExplicit);
1333 }
1334
1335 ImplicitConversionSequence
TryImplicitConversion(Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1336 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1337 bool SuppressUserConversions,
1338 bool AllowExplicit,
1339 bool InOverloadResolution,
1340 bool CStyle,
1341 bool AllowObjCWritebackConversion) {
1342 return ::TryImplicitConversion(*this, From, ToType,
1343 SuppressUserConversions, AllowExplicit,
1344 InOverloadResolution, CStyle,
1345 AllowObjCWritebackConversion,
1346 /*AllowObjCConversionOnExplicit=*/false);
1347 }
1348
1349 /// PerformImplicitConversion - Perform an implicit conversion of the
1350 /// expression From to the type ToType. Returns the
1351 /// converted expression. Flavor is the kind of conversion we're
1352 /// performing, used in the error message. If @p AllowExplicit,
1353 /// explicit user-defined conversions are permitted.
1354 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit)1355 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1356 AssignmentAction Action, bool AllowExplicit) {
1357 ImplicitConversionSequence ICS;
1358 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1359 }
1360
1361 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit,ImplicitConversionSequence & ICS)1362 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1363 AssignmentAction Action, bool AllowExplicit,
1364 ImplicitConversionSequence& ICS) {
1365 if (checkPlaceholderForOverload(*this, From))
1366 return ExprError();
1367
1368 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1369 bool AllowObjCWritebackConversion
1370 = getLangOpts().ObjCAutoRefCount &&
1371 (Action == AA_Passing || Action == AA_Sending);
1372 if (getLangOpts().ObjC1)
1373 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1374 ToType, From->getType(), From);
1375 ICS = ::TryImplicitConversion(*this, From, ToType,
1376 /*SuppressUserConversions=*/false,
1377 AllowExplicit,
1378 /*InOverloadResolution=*/false,
1379 /*CStyle=*/false,
1380 AllowObjCWritebackConversion,
1381 /*AllowObjCConversionOnExplicit=*/false);
1382 return PerformImplicitConversion(From, ToType, ICS, Action);
1383 }
1384
1385 /// \brief Determine whether the conversion from FromType to ToType is a valid
1386 /// conversion that strips "noreturn" off the nested function type.
IsNoReturnConversion(QualType FromType,QualType ToType,QualType & ResultTy)1387 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1388 QualType &ResultTy) {
1389 if (Context.hasSameUnqualifiedType(FromType, ToType))
1390 return false;
1391
1392 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1393 // where F adds one of the following at most once:
1394 // - a pointer
1395 // - a member pointer
1396 // - a block pointer
1397 CanQualType CanTo = Context.getCanonicalType(ToType);
1398 CanQualType CanFrom = Context.getCanonicalType(FromType);
1399 Type::TypeClass TyClass = CanTo->getTypeClass();
1400 if (TyClass != CanFrom->getTypeClass()) return false;
1401 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1402 if (TyClass == Type::Pointer) {
1403 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1404 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1405 } else if (TyClass == Type::BlockPointer) {
1406 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1407 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1408 } else if (TyClass == Type::MemberPointer) {
1409 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1410 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1411 } else {
1412 return false;
1413 }
1414
1415 TyClass = CanTo->getTypeClass();
1416 if (TyClass != CanFrom->getTypeClass()) return false;
1417 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1418 return false;
1419 }
1420
1421 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1422 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1423 if (!EInfo.getNoReturn()) return false;
1424
1425 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1426 assert(QualType(FromFn, 0).isCanonical());
1427 if (QualType(FromFn, 0) != CanTo) return false;
1428
1429 ResultTy = ToType;
1430 return true;
1431 }
1432
1433 /// \brief Determine whether the conversion from FromType to ToType is a valid
1434 /// vector conversion.
1435 ///
1436 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1437 /// conversion.
IsVectorConversion(Sema & S,QualType FromType,QualType ToType,ImplicitConversionKind & ICK)1438 static bool IsVectorConversion(Sema &S, QualType FromType,
1439 QualType ToType, ImplicitConversionKind &ICK) {
1440 // We need at least one of these types to be a vector type to have a vector
1441 // conversion.
1442 if (!ToType->isVectorType() && !FromType->isVectorType())
1443 return false;
1444
1445 // Identical types require no conversions.
1446 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1447 return false;
1448
1449 // There are no conversions between extended vector types, only identity.
1450 if (ToType->isExtVectorType()) {
1451 // There are no conversions between extended vector types other than the
1452 // identity conversion.
1453 if (FromType->isExtVectorType())
1454 return false;
1455
1456 // Vector splat from any arithmetic type to a vector.
1457 if (FromType->isArithmeticType()) {
1458 ICK = ICK_Vector_Splat;
1459 return true;
1460 }
1461 }
1462
1463 // We can perform the conversion between vector types in the following cases:
1464 // 1)vector types are equivalent AltiVec and GCC vector types
1465 // 2)lax vector conversions are permitted and the vector types are of the
1466 // same size
1467 if (ToType->isVectorType() && FromType->isVectorType()) {
1468 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1469 S.isLaxVectorConversion(FromType, ToType)) {
1470 ICK = ICK_Vector_Conversion;
1471 return true;
1472 }
1473 }
1474
1475 return false;
1476 }
1477
1478 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1479 bool InOverloadResolution,
1480 StandardConversionSequence &SCS,
1481 bool CStyle);
1482
1483 /// IsStandardConversion - Determines whether there is a standard
1484 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1485 /// expression From to the type ToType. Standard conversion sequences
1486 /// only consider non-class types; for conversions that involve class
1487 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1488 /// contain the standard conversion sequence required to perform this
1489 /// conversion and this routine will return true. Otherwise, this
1490 /// routine will return false and the value of SCS is unspecified.
IsStandardConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle,bool AllowObjCWritebackConversion)1491 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1492 bool InOverloadResolution,
1493 StandardConversionSequence &SCS,
1494 bool CStyle,
1495 bool AllowObjCWritebackConversion) {
1496 QualType FromType = From->getType();
1497
1498 // Standard conversions (C++ [conv])
1499 SCS.setAsIdentityConversion();
1500 SCS.IncompatibleObjC = false;
1501 SCS.setFromType(FromType);
1502 SCS.CopyConstructor = nullptr;
1503
1504 // There are no standard conversions for class types in C++, so
1505 // abort early. When overloading in C, however, we do permit them.
1506 if (S.getLangOpts().CPlusPlus &&
1507 (FromType->isRecordType() || ToType->isRecordType()))
1508 return false;
1509
1510 // The first conversion can be an lvalue-to-rvalue conversion,
1511 // array-to-pointer conversion, or function-to-pointer conversion
1512 // (C++ 4p1).
1513
1514 if (FromType == S.Context.OverloadTy) {
1515 DeclAccessPair AccessPair;
1516 if (FunctionDecl *Fn
1517 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1518 AccessPair)) {
1519 // We were able to resolve the address of the overloaded function,
1520 // so we can convert to the type of that function.
1521 FromType = Fn->getType();
1522 SCS.setFromType(FromType);
1523
1524 // we can sometimes resolve &foo<int> regardless of ToType, so check
1525 // if the type matches (identity) or we are converting to bool
1526 if (!S.Context.hasSameUnqualifiedType(
1527 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1528 QualType resultTy;
1529 // if the function type matches except for [[noreturn]], it's ok
1530 if (!S.IsNoReturnConversion(FromType,
1531 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1532 // otherwise, only a boolean conversion is standard
1533 if (!ToType->isBooleanType())
1534 return false;
1535 }
1536
1537 // Check if the "from" expression is taking the address of an overloaded
1538 // function and recompute the FromType accordingly. Take advantage of the
1539 // fact that non-static member functions *must* have such an address-of
1540 // expression.
1541 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1542 if (Method && !Method->isStatic()) {
1543 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1544 "Non-unary operator on non-static member address");
1545 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1546 == UO_AddrOf &&
1547 "Non-address-of operator on non-static member address");
1548 const Type *ClassType
1549 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1550 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1551 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1552 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1553 UO_AddrOf &&
1554 "Non-address-of operator for overloaded function expression");
1555 FromType = S.Context.getPointerType(FromType);
1556 }
1557
1558 // Check that we've computed the proper type after overload resolution.
1559 assert(S.Context.hasSameType(
1560 FromType,
1561 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1562 } else {
1563 return false;
1564 }
1565 }
1566 // Lvalue-to-rvalue conversion (C++11 4.1):
1567 // A glvalue (3.10) of a non-function, non-array type T can
1568 // be converted to a prvalue.
1569 bool argIsLValue = From->isGLValue();
1570 if (argIsLValue &&
1571 !FromType->isFunctionType() && !FromType->isArrayType() &&
1572 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1573 SCS.First = ICK_Lvalue_To_Rvalue;
1574
1575 // C11 6.3.2.1p2:
1576 // ... if the lvalue has atomic type, the value has the non-atomic version
1577 // of the type of the lvalue ...
1578 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1579 FromType = Atomic->getValueType();
1580
1581 // If T is a non-class type, the type of the rvalue is the
1582 // cv-unqualified version of T. Otherwise, the type of the rvalue
1583 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1584 // just strip the qualifiers because they don't matter.
1585 FromType = FromType.getUnqualifiedType();
1586 } else if (FromType->isArrayType()) {
1587 // Array-to-pointer conversion (C++ 4.2)
1588 SCS.First = ICK_Array_To_Pointer;
1589
1590 // An lvalue or rvalue of type "array of N T" or "array of unknown
1591 // bound of T" can be converted to an rvalue of type "pointer to
1592 // T" (C++ 4.2p1).
1593 FromType = S.Context.getArrayDecayedType(FromType);
1594
1595 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1596 // This conversion is deprecated in C++03 (D.4)
1597 SCS.DeprecatedStringLiteralToCharPtr = true;
1598
1599 // For the purpose of ranking in overload resolution
1600 // (13.3.3.1.1), this conversion is considered an
1601 // array-to-pointer conversion followed by a qualification
1602 // conversion (4.4). (C++ 4.2p2)
1603 SCS.Second = ICK_Identity;
1604 SCS.Third = ICK_Qualification;
1605 SCS.QualificationIncludesObjCLifetime = false;
1606 SCS.setAllToTypes(FromType);
1607 return true;
1608 }
1609 } else if (FromType->isFunctionType() && argIsLValue) {
1610 // Function-to-pointer conversion (C++ 4.3).
1611 SCS.First = ICK_Function_To_Pointer;
1612
1613 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1614 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1615 if (!S.checkAddressOfFunctionIsAvailable(FD))
1616 return false;
1617
1618 // An lvalue of function type T can be converted to an rvalue of
1619 // type "pointer to T." The result is a pointer to the
1620 // function. (C++ 4.3p1).
1621 FromType = S.Context.getPointerType(FromType);
1622 } else {
1623 // We don't require any conversions for the first step.
1624 SCS.First = ICK_Identity;
1625 }
1626 SCS.setToType(0, FromType);
1627
1628 // The second conversion can be an integral promotion, floating
1629 // point promotion, integral conversion, floating point conversion,
1630 // floating-integral conversion, pointer conversion,
1631 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1632 // For overloading in C, this can also be a "compatible-type"
1633 // conversion.
1634 bool IncompatibleObjC = false;
1635 ImplicitConversionKind SecondICK = ICK_Identity;
1636 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1637 // The unqualified versions of the types are the same: there's no
1638 // conversion to do.
1639 SCS.Second = ICK_Identity;
1640 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1641 // Integral promotion (C++ 4.5).
1642 SCS.Second = ICK_Integral_Promotion;
1643 FromType = ToType.getUnqualifiedType();
1644 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1645 // Floating point promotion (C++ 4.6).
1646 SCS.Second = ICK_Floating_Promotion;
1647 FromType = ToType.getUnqualifiedType();
1648 } else if (S.IsComplexPromotion(FromType, ToType)) {
1649 // Complex promotion (Clang extension)
1650 SCS.Second = ICK_Complex_Promotion;
1651 FromType = ToType.getUnqualifiedType();
1652 } else if (ToType->isBooleanType() &&
1653 (FromType->isArithmeticType() ||
1654 FromType->isAnyPointerType() ||
1655 FromType->isBlockPointerType() ||
1656 FromType->isMemberPointerType() ||
1657 FromType->isNullPtrType())) {
1658 // Boolean conversions (C++ 4.12).
1659 SCS.Second = ICK_Boolean_Conversion;
1660 FromType = S.Context.BoolTy;
1661 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1662 ToType->isIntegralType(S.Context)) {
1663 // Integral conversions (C++ 4.7).
1664 SCS.Second = ICK_Integral_Conversion;
1665 FromType = ToType.getUnqualifiedType();
1666 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1667 // Complex conversions (C99 6.3.1.6)
1668 SCS.Second = ICK_Complex_Conversion;
1669 FromType = ToType.getUnqualifiedType();
1670 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1671 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1672 // Complex-real conversions (C99 6.3.1.7)
1673 SCS.Second = ICK_Complex_Real;
1674 FromType = ToType.getUnqualifiedType();
1675 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1676 // FIXME: disable conversions between long double and __float128 if
1677 // their representation is different until there is back end support
1678 // We of course allow this conversion if long double is really double.
1679 if (&S.Context.getFloatTypeSemantics(FromType) !=
1680 &S.Context.getFloatTypeSemantics(ToType)) {
1681 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1682 ToType == S.Context.LongDoubleTy) ||
1683 (FromType == S.Context.LongDoubleTy &&
1684 ToType == S.Context.Float128Ty));
1685 if (Float128AndLongDouble &&
1686 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1687 &llvm::APFloat::IEEEdouble))
1688 return false;
1689 }
1690 // Floating point conversions (C++ 4.8).
1691 SCS.Second = ICK_Floating_Conversion;
1692 FromType = ToType.getUnqualifiedType();
1693 } else if ((FromType->isRealFloatingType() &&
1694 ToType->isIntegralType(S.Context)) ||
1695 (FromType->isIntegralOrUnscopedEnumerationType() &&
1696 ToType->isRealFloatingType())) {
1697 // Floating-integral conversions (C++ 4.9).
1698 SCS.Second = ICK_Floating_Integral;
1699 FromType = ToType.getUnqualifiedType();
1700 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1701 SCS.Second = ICK_Block_Pointer_Conversion;
1702 } else if (AllowObjCWritebackConversion &&
1703 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1704 SCS.Second = ICK_Writeback_Conversion;
1705 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1706 FromType, IncompatibleObjC)) {
1707 // Pointer conversions (C++ 4.10).
1708 SCS.Second = ICK_Pointer_Conversion;
1709 SCS.IncompatibleObjC = IncompatibleObjC;
1710 FromType = FromType.getUnqualifiedType();
1711 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1712 InOverloadResolution, FromType)) {
1713 // Pointer to member conversions (4.11).
1714 SCS.Second = ICK_Pointer_Member;
1715 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1716 SCS.Second = SecondICK;
1717 FromType = ToType.getUnqualifiedType();
1718 } else if (!S.getLangOpts().CPlusPlus &&
1719 S.Context.typesAreCompatible(ToType, FromType)) {
1720 // Compatible conversions (Clang extension for C function overloading)
1721 SCS.Second = ICK_Compatible_Conversion;
1722 FromType = ToType.getUnqualifiedType();
1723 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1724 // Treat a conversion that strips "noreturn" as an identity conversion.
1725 SCS.Second = ICK_NoReturn_Adjustment;
1726 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1727 InOverloadResolution,
1728 SCS, CStyle)) {
1729 SCS.Second = ICK_TransparentUnionConversion;
1730 FromType = ToType;
1731 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1732 CStyle)) {
1733 // tryAtomicConversion has updated the standard conversion sequence
1734 // appropriately.
1735 return true;
1736 } else if (ToType->isEventT() &&
1737 From->isIntegerConstantExpr(S.getASTContext()) &&
1738 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1739 SCS.Second = ICK_Zero_Event_Conversion;
1740 FromType = ToType;
1741 } else {
1742 // No second conversion required.
1743 SCS.Second = ICK_Identity;
1744 }
1745 SCS.setToType(1, FromType);
1746
1747 QualType CanonFrom;
1748 QualType CanonTo;
1749 // The third conversion can be a qualification conversion (C++ 4p1).
1750 bool ObjCLifetimeConversion;
1751 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1752 ObjCLifetimeConversion)) {
1753 SCS.Third = ICK_Qualification;
1754 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1755 FromType = ToType;
1756 CanonFrom = S.Context.getCanonicalType(FromType);
1757 CanonTo = S.Context.getCanonicalType(ToType);
1758 } else {
1759 // No conversion required
1760 SCS.Third = ICK_Identity;
1761
1762 // C++ [over.best.ics]p6:
1763 // [...] Any difference in top-level cv-qualification is
1764 // subsumed by the initialization itself and does not constitute
1765 // a conversion. [...]
1766 CanonFrom = S.Context.getCanonicalType(FromType);
1767 CanonTo = S.Context.getCanonicalType(ToType);
1768 if (CanonFrom.getLocalUnqualifiedType()
1769 == CanonTo.getLocalUnqualifiedType() &&
1770 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1771 FromType = ToType;
1772 CanonFrom = CanonTo;
1773 }
1774 }
1775 SCS.setToType(2, FromType);
1776
1777 if (CanonFrom == CanonTo)
1778 return true;
1779
1780 // If we have not converted the argument type to the parameter type,
1781 // this is a bad conversion sequence, unless we're resolving an overload in C.
1782 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1783 return false;
1784
1785 ExprResult ER = ExprResult{From};
1786 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1787 /*Diagnose=*/false,
1788 /*DiagnoseCFAudited=*/false,
1789 /*ConvertRHS=*/false);
1790 if (Conv != Sema::Compatible)
1791 return false;
1792
1793 SCS.setAllToTypes(ToType);
1794 // We need to set all three because we want this conversion to rank terribly,
1795 // and we don't know what conversions it may overlap with.
1796 SCS.First = ICK_C_Only_Conversion;
1797 SCS.Second = ICK_C_Only_Conversion;
1798 SCS.Third = ICK_C_Only_Conversion;
1799 return true;
1800 }
1801
1802 static bool
IsTransparentUnionStandardConversion(Sema & S,Expr * From,QualType & ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)1803 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1804 QualType &ToType,
1805 bool InOverloadResolution,
1806 StandardConversionSequence &SCS,
1807 bool CStyle) {
1808
1809 const RecordType *UT = ToType->getAsUnionType();
1810 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1811 return false;
1812 // The field to initialize within the transparent union.
1813 RecordDecl *UD = UT->getDecl();
1814 // It's compatible if the expression matches any of the fields.
1815 for (const auto *it : UD->fields()) {
1816 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1817 CStyle, /*ObjCWritebackConversion=*/false)) {
1818 ToType = it->getType();
1819 return true;
1820 }
1821 }
1822 return false;
1823 }
1824
1825 /// IsIntegralPromotion - Determines whether the conversion from the
1826 /// expression From (whose potentially-adjusted type is FromType) to
1827 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1828 /// sets PromotedType to the promoted type.
IsIntegralPromotion(Expr * From,QualType FromType,QualType ToType)1829 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1830 const BuiltinType *To = ToType->getAs<BuiltinType>();
1831 // All integers are built-in.
1832 if (!To) {
1833 return false;
1834 }
1835
1836 // An rvalue of type char, signed char, unsigned char, short int, or
1837 // unsigned short int can be converted to an rvalue of type int if
1838 // int can represent all the values of the source type; otherwise,
1839 // the source rvalue can be converted to an rvalue of type unsigned
1840 // int (C++ 4.5p1).
1841 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1842 !FromType->isEnumeralType()) {
1843 if (// We can promote any signed, promotable integer type to an int
1844 (FromType->isSignedIntegerType() ||
1845 // We can promote any unsigned integer type whose size is
1846 // less than int to an int.
1847 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1848 return To->getKind() == BuiltinType::Int;
1849 }
1850
1851 return To->getKind() == BuiltinType::UInt;
1852 }
1853
1854 // C++11 [conv.prom]p3:
1855 // A prvalue of an unscoped enumeration type whose underlying type is not
1856 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1857 // following types that can represent all the values of the enumeration
1858 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1859 // unsigned int, long int, unsigned long int, long long int, or unsigned
1860 // long long int. If none of the types in that list can represent all the
1861 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1862 // type can be converted to an rvalue a prvalue of the extended integer type
1863 // with lowest integer conversion rank (4.13) greater than the rank of long
1864 // long in which all the values of the enumeration can be represented. If
1865 // there are two such extended types, the signed one is chosen.
1866 // C++11 [conv.prom]p4:
1867 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1868 // can be converted to a prvalue of its underlying type. Moreover, if
1869 // integral promotion can be applied to its underlying type, a prvalue of an
1870 // unscoped enumeration type whose underlying type is fixed can also be
1871 // converted to a prvalue of the promoted underlying type.
1872 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1873 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1874 // provided for a scoped enumeration.
1875 if (FromEnumType->getDecl()->isScoped())
1876 return false;
1877
1878 // We can perform an integral promotion to the underlying type of the enum,
1879 // even if that's not the promoted type. Note that the check for promoting
1880 // the underlying type is based on the type alone, and does not consider
1881 // the bitfield-ness of the actual source expression.
1882 if (FromEnumType->getDecl()->isFixed()) {
1883 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1884 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1885 IsIntegralPromotion(nullptr, Underlying, ToType);
1886 }
1887
1888 // We have already pre-calculated the promotion type, so this is trivial.
1889 if (ToType->isIntegerType() &&
1890 isCompleteType(From->getLocStart(), FromType))
1891 return Context.hasSameUnqualifiedType(
1892 ToType, FromEnumType->getDecl()->getPromotionType());
1893 }
1894
1895 // C++0x [conv.prom]p2:
1896 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1897 // to an rvalue a prvalue of the first of the following types that can
1898 // represent all the values of its underlying type: int, unsigned int,
1899 // long int, unsigned long int, long long int, or unsigned long long int.
1900 // If none of the types in that list can represent all the values of its
1901 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1902 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1903 // type.
1904 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1905 ToType->isIntegerType()) {
1906 // Determine whether the type we're converting from is signed or
1907 // unsigned.
1908 bool FromIsSigned = FromType->isSignedIntegerType();
1909 uint64_t FromSize = Context.getTypeSize(FromType);
1910
1911 // The types we'll try to promote to, in the appropriate
1912 // order. Try each of these types.
1913 QualType PromoteTypes[6] = {
1914 Context.IntTy, Context.UnsignedIntTy,
1915 Context.LongTy, Context.UnsignedLongTy ,
1916 Context.LongLongTy, Context.UnsignedLongLongTy
1917 };
1918 for (int Idx = 0; Idx < 6; ++Idx) {
1919 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1920 if (FromSize < ToSize ||
1921 (FromSize == ToSize &&
1922 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1923 // We found the type that we can promote to. If this is the
1924 // type we wanted, we have a promotion. Otherwise, no
1925 // promotion.
1926 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1927 }
1928 }
1929 }
1930
1931 // An rvalue for an integral bit-field (9.6) can be converted to an
1932 // rvalue of type int if int can represent all the values of the
1933 // bit-field; otherwise, it can be converted to unsigned int if
1934 // unsigned int can represent all the values of the bit-field. If
1935 // the bit-field is larger yet, no integral promotion applies to
1936 // it. If the bit-field has an enumerated type, it is treated as any
1937 // other value of that type for promotion purposes (C++ 4.5p3).
1938 // FIXME: We should delay checking of bit-fields until we actually perform the
1939 // conversion.
1940 if (From) {
1941 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1942 llvm::APSInt BitWidth;
1943 if (FromType->isIntegralType(Context) &&
1944 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1945 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1946 ToSize = Context.getTypeSize(ToType);
1947
1948 // Are we promoting to an int from a bitfield that fits in an int?
1949 if (BitWidth < ToSize ||
1950 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1951 return To->getKind() == BuiltinType::Int;
1952 }
1953
1954 // Are we promoting to an unsigned int from an unsigned bitfield
1955 // that fits into an unsigned int?
1956 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1957 return To->getKind() == BuiltinType::UInt;
1958 }
1959
1960 return false;
1961 }
1962 }
1963 }
1964
1965 // An rvalue of type bool can be converted to an rvalue of type int,
1966 // with false becoming zero and true becoming one (C++ 4.5p4).
1967 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1968 return true;
1969 }
1970
1971 return false;
1972 }
1973
1974 /// IsFloatingPointPromotion - Determines whether the conversion from
1975 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1976 /// returns true and sets PromotedType to the promoted type.
IsFloatingPointPromotion(QualType FromType,QualType ToType)1977 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1978 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1979 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1980 /// An rvalue of type float can be converted to an rvalue of type
1981 /// double. (C++ 4.6p1).
1982 if (FromBuiltin->getKind() == BuiltinType::Float &&
1983 ToBuiltin->getKind() == BuiltinType::Double)
1984 return true;
1985
1986 // C99 6.3.1.5p1:
1987 // When a float is promoted to double or long double, or a
1988 // double is promoted to long double [...].
1989 if (!getLangOpts().CPlusPlus &&
1990 (FromBuiltin->getKind() == BuiltinType::Float ||
1991 FromBuiltin->getKind() == BuiltinType::Double) &&
1992 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
1993 ToBuiltin->getKind() == BuiltinType::Float128))
1994 return true;
1995
1996 // Half can be promoted to float.
1997 if (!getLangOpts().NativeHalfType &&
1998 FromBuiltin->getKind() == BuiltinType::Half &&
1999 ToBuiltin->getKind() == BuiltinType::Float)
2000 return true;
2001 }
2002
2003 return false;
2004 }
2005
2006 /// \brief Determine if a conversion is a complex promotion.
2007 ///
2008 /// A complex promotion is defined as a complex -> complex conversion
2009 /// where the conversion between the underlying real types is a
2010 /// floating-point or integral promotion.
IsComplexPromotion(QualType FromType,QualType ToType)2011 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2012 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2013 if (!FromComplex)
2014 return false;
2015
2016 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2017 if (!ToComplex)
2018 return false;
2019
2020 return IsFloatingPointPromotion(FromComplex->getElementType(),
2021 ToComplex->getElementType()) ||
2022 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2023 ToComplex->getElementType());
2024 }
2025
2026 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2027 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2028 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2029 /// if non-empty, will be a pointer to ToType that may or may not have
2030 /// the right set of qualifiers on its pointee.
2031 ///
2032 static QualType
BuildSimilarlyQualifiedPointerType(const Type * FromPtr,QualType ToPointee,QualType ToType,ASTContext & Context,bool StripObjCLifetime=false)2033 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2034 QualType ToPointee, QualType ToType,
2035 ASTContext &Context,
2036 bool StripObjCLifetime = false) {
2037 assert((FromPtr->getTypeClass() == Type::Pointer ||
2038 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2039 "Invalid similarly-qualified pointer type");
2040
2041 /// Conversions to 'id' subsume cv-qualifier conversions.
2042 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2043 return ToType.getUnqualifiedType();
2044
2045 QualType CanonFromPointee
2046 = Context.getCanonicalType(FromPtr->getPointeeType());
2047 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2048 Qualifiers Quals = CanonFromPointee.getQualifiers();
2049
2050 if (StripObjCLifetime)
2051 Quals.removeObjCLifetime();
2052
2053 // Exact qualifier match -> return the pointer type we're converting to.
2054 if (CanonToPointee.getLocalQualifiers() == Quals) {
2055 // ToType is exactly what we need. Return it.
2056 if (!ToType.isNull())
2057 return ToType.getUnqualifiedType();
2058
2059 // Build a pointer to ToPointee. It has the right qualifiers
2060 // already.
2061 if (isa<ObjCObjectPointerType>(ToType))
2062 return Context.getObjCObjectPointerType(ToPointee);
2063 return Context.getPointerType(ToPointee);
2064 }
2065
2066 // Just build a canonical type that has the right qualifiers.
2067 QualType QualifiedCanonToPointee
2068 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2069
2070 if (isa<ObjCObjectPointerType>(ToType))
2071 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2072 return Context.getPointerType(QualifiedCanonToPointee);
2073 }
2074
isNullPointerConstantForConversion(Expr * Expr,bool InOverloadResolution,ASTContext & Context)2075 static bool isNullPointerConstantForConversion(Expr *Expr,
2076 bool InOverloadResolution,
2077 ASTContext &Context) {
2078 // Handle value-dependent integral null pointer constants correctly.
2079 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2080 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2081 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2082 return !InOverloadResolution;
2083
2084 return Expr->isNullPointerConstant(Context,
2085 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2086 : Expr::NPC_ValueDependentIsNull);
2087 }
2088
2089 /// IsPointerConversion - Determines whether the conversion of the
2090 /// expression From, which has the (possibly adjusted) type FromType,
2091 /// can be converted to the type ToType via a pointer conversion (C++
2092 /// 4.10). If so, returns true and places the converted type (that
2093 /// might differ from ToType in its cv-qualifiers at some level) into
2094 /// ConvertedType.
2095 ///
2096 /// This routine also supports conversions to and from block pointers
2097 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2098 /// pointers to interfaces. FIXME: Once we've determined the
2099 /// appropriate overloading rules for Objective-C, we may want to
2100 /// split the Objective-C checks into a different routine; however,
2101 /// GCC seems to consider all of these conversions to be pointer
2102 /// conversions, so for now they live here. IncompatibleObjC will be
2103 /// set if the conversion is an allowed Objective-C conversion that
2104 /// should result in a warning.
IsPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType,bool & IncompatibleObjC)2105 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2106 bool InOverloadResolution,
2107 QualType& ConvertedType,
2108 bool &IncompatibleObjC) {
2109 IncompatibleObjC = false;
2110 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2111 IncompatibleObjC))
2112 return true;
2113
2114 // Conversion from a null pointer constant to any Objective-C pointer type.
2115 if (ToType->isObjCObjectPointerType() &&
2116 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2117 ConvertedType = ToType;
2118 return true;
2119 }
2120
2121 // Blocks: Block pointers can be converted to void*.
2122 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2123 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2124 ConvertedType = ToType;
2125 return true;
2126 }
2127 // Blocks: A null pointer constant can be converted to a block
2128 // pointer type.
2129 if (ToType->isBlockPointerType() &&
2130 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2131 ConvertedType = ToType;
2132 return true;
2133 }
2134
2135 // If the left-hand-side is nullptr_t, the right side can be a null
2136 // pointer constant.
2137 if (ToType->isNullPtrType() &&
2138 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2139 ConvertedType = ToType;
2140 return true;
2141 }
2142
2143 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2144 if (!ToTypePtr)
2145 return false;
2146
2147 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2148 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2149 ConvertedType = ToType;
2150 return true;
2151 }
2152
2153 // Beyond this point, both types need to be pointers
2154 // , including objective-c pointers.
2155 QualType ToPointeeType = ToTypePtr->getPointeeType();
2156 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2157 !getLangOpts().ObjCAutoRefCount) {
2158 ConvertedType = BuildSimilarlyQualifiedPointerType(
2159 FromType->getAs<ObjCObjectPointerType>(),
2160 ToPointeeType,
2161 ToType, Context);
2162 return true;
2163 }
2164 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2165 if (!FromTypePtr)
2166 return false;
2167
2168 QualType FromPointeeType = FromTypePtr->getPointeeType();
2169
2170 // If the unqualified pointee types are the same, this can't be a
2171 // pointer conversion, so don't do all of the work below.
2172 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2173 return false;
2174
2175 // An rvalue of type "pointer to cv T," where T is an object type,
2176 // can be converted to an rvalue of type "pointer to cv void" (C++
2177 // 4.10p2).
2178 if (FromPointeeType->isIncompleteOrObjectType() &&
2179 ToPointeeType->isVoidType()) {
2180 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2181 ToPointeeType,
2182 ToType, Context,
2183 /*StripObjCLifetime=*/true);
2184 return true;
2185 }
2186
2187 // MSVC allows implicit function to void* type conversion.
2188 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2189 ToPointeeType->isVoidType()) {
2190 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2191 ToPointeeType,
2192 ToType, Context);
2193 return true;
2194 }
2195
2196 // When we're overloading in C, we allow a special kind of pointer
2197 // conversion for compatible-but-not-identical pointee types.
2198 if (!getLangOpts().CPlusPlus &&
2199 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2200 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2201 ToPointeeType,
2202 ToType, Context);
2203 return true;
2204 }
2205
2206 // C++ [conv.ptr]p3:
2207 //
2208 // An rvalue of type "pointer to cv D," where D is a class type,
2209 // can be converted to an rvalue of type "pointer to cv B," where
2210 // B is a base class (clause 10) of D. If B is an inaccessible
2211 // (clause 11) or ambiguous (10.2) base class of D, a program that
2212 // necessitates this conversion is ill-formed. The result of the
2213 // conversion is a pointer to the base class sub-object of the
2214 // derived class object. The null pointer value is converted to
2215 // the null pointer value of the destination type.
2216 //
2217 // Note that we do not check for ambiguity or inaccessibility
2218 // here. That is handled by CheckPointerConversion.
2219 if (getLangOpts().CPlusPlus &&
2220 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2221 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2222 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2223 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2224 ToPointeeType,
2225 ToType, Context);
2226 return true;
2227 }
2228
2229 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2230 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2231 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2232 ToPointeeType,
2233 ToType, Context);
2234 return true;
2235 }
2236
2237 return false;
2238 }
2239
2240 /// \brief Adopt the given qualifiers for the given type.
AdoptQualifiers(ASTContext & Context,QualType T,Qualifiers Qs)2241 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2242 Qualifiers TQs = T.getQualifiers();
2243
2244 // Check whether qualifiers already match.
2245 if (TQs == Qs)
2246 return T;
2247
2248 if (Qs.compatiblyIncludes(TQs))
2249 return Context.getQualifiedType(T, Qs);
2250
2251 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2252 }
2253
2254 /// isObjCPointerConversion - Determines whether this is an
2255 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2256 /// with the same arguments and return values.
isObjCPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType,bool & IncompatibleObjC)2257 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2258 QualType& ConvertedType,
2259 bool &IncompatibleObjC) {
2260 if (!getLangOpts().ObjC1)
2261 return false;
2262
2263 // The set of qualifiers on the type we're converting from.
2264 Qualifiers FromQualifiers = FromType.getQualifiers();
2265
2266 // First, we handle all conversions on ObjC object pointer types.
2267 const ObjCObjectPointerType* ToObjCPtr =
2268 ToType->getAs<ObjCObjectPointerType>();
2269 const ObjCObjectPointerType *FromObjCPtr =
2270 FromType->getAs<ObjCObjectPointerType>();
2271
2272 if (ToObjCPtr && FromObjCPtr) {
2273 // If the pointee types are the same (ignoring qualifications),
2274 // then this is not a pointer conversion.
2275 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2276 FromObjCPtr->getPointeeType()))
2277 return false;
2278
2279 // Conversion between Objective-C pointers.
2280 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2281 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2282 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2283 if (getLangOpts().CPlusPlus && LHS && RHS &&
2284 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2285 FromObjCPtr->getPointeeType()))
2286 return false;
2287 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2288 ToObjCPtr->getPointeeType(),
2289 ToType, Context);
2290 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2291 return true;
2292 }
2293
2294 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2295 // Okay: this is some kind of implicit downcast of Objective-C
2296 // interfaces, which is permitted. However, we're going to
2297 // complain about it.
2298 IncompatibleObjC = true;
2299 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2300 ToObjCPtr->getPointeeType(),
2301 ToType, Context);
2302 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2303 return true;
2304 }
2305 }
2306 // Beyond this point, both types need to be C pointers or block pointers.
2307 QualType ToPointeeType;
2308 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2309 ToPointeeType = ToCPtr->getPointeeType();
2310 else if (const BlockPointerType *ToBlockPtr =
2311 ToType->getAs<BlockPointerType>()) {
2312 // Objective C++: We're able to convert from a pointer to any object
2313 // to a block pointer type.
2314 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2315 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2316 return true;
2317 }
2318 ToPointeeType = ToBlockPtr->getPointeeType();
2319 }
2320 else if (FromType->getAs<BlockPointerType>() &&
2321 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2322 // Objective C++: We're able to convert from a block pointer type to a
2323 // pointer to any object.
2324 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2325 return true;
2326 }
2327 else
2328 return false;
2329
2330 QualType FromPointeeType;
2331 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2332 FromPointeeType = FromCPtr->getPointeeType();
2333 else if (const BlockPointerType *FromBlockPtr =
2334 FromType->getAs<BlockPointerType>())
2335 FromPointeeType = FromBlockPtr->getPointeeType();
2336 else
2337 return false;
2338
2339 // If we have pointers to pointers, recursively check whether this
2340 // is an Objective-C conversion.
2341 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2342 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2343 IncompatibleObjC)) {
2344 // We always complain about this conversion.
2345 IncompatibleObjC = true;
2346 ConvertedType = Context.getPointerType(ConvertedType);
2347 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2348 return true;
2349 }
2350 // Allow conversion of pointee being objective-c pointer to another one;
2351 // as in I* to id.
2352 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2353 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2354 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2355 IncompatibleObjC)) {
2356
2357 ConvertedType = Context.getPointerType(ConvertedType);
2358 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2359 return true;
2360 }
2361
2362 // If we have pointers to functions or blocks, check whether the only
2363 // differences in the argument and result types are in Objective-C
2364 // pointer conversions. If so, we permit the conversion (but
2365 // complain about it).
2366 const FunctionProtoType *FromFunctionType
2367 = FromPointeeType->getAs<FunctionProtoType>();
2368 const FunctionProtoType *ToFunctionType
2369 = ToPointeeType->getAs<FunctionProtoType>();
2370 if (FromFunctionType && ToFunctionType) {
2371 // If the function types are exactly the same, this isn't an
2372 // Objective-C pointer conversion.
2373 if (Context.getCanonicalType(FromPointeeType)
2374 == Context.getCanonicalType(ToPointeeType))
2375 return false;
2376
2377 // Perform the quick checks that will tell us whether these
2378 // function types are obviously different.
2379 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2380 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2381 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2382 return false;
2383
2384 bool HasObjCConversion = false;
2385 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2386 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2387 // Okay, the types match exactly. Nothing to do.
2388 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2389 ToFunctionType->getReturnType(),
2390 ConvertedType, IncompatibleObjC)) {
2391 // Okay, we have an Objective-C pointer conversion.
2392 HasObjCConversion = true;
2393 } else {
2394 // Function types are too different. Abort.
2395 return false;
2396 }
2397
2398 // Check argument types.
2399 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2400 ArgIdx != NumArgs; ++ArgIdx) {
2401 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2402 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2403 if (Context.getCanonicalType(FromArgType)
2404 == Context.getCanonicalType(ToArgType)) {
2405 // Okay, the types match exactly. Nothing to do.
2406 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2407 ConvertedType, IncompatibleObjC)) {
2408 // Okay, we have an Objective-C pointer conversion.
2409 HasObjCConversion = true;
2410 } else {
2411 // Argument types are too different. Abort.
2412 return false;
2413 }
2414 }
2415
2416 if (HasObjCConversion) {
2417 // We had an Objective-C conversion. Allow this pointer
2418 // conversion, but complain about it.
2419 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2420 IncompatibleObjC = true;
2421 return true;
2422 }
2423 }
2424
2425 return false;
2426 }
2427
2428 /// \brief Determine whether this is an Objective-C writeback conversion,
2429 /// used for parameter passing when performing automatic reference counting.
2430 ///
2431 /// \param FromType The type we're converting form.
2432 ///
2433 /// \param ToType The type we're converting to.
2434 ///
2435 /// \param ConvertedType The type that will be produced after applying
2436 /// this conversion.
isObjCWritebackConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2437 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2438 QualType &ConvertedType) {
2439 if (!getLangOpts().ObjCAutoRefCount ||
2440 Context.hasSameUnqualifiedType(FromType, ToType))
2441 return false;
2442
2443 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2444 QualType ToPointee;
2445 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2446 ToPointee = ToPointer->getPointeeType();
2447 else
2448 return false;
2449
2450 Qualifiers ToQuals = ToPointee.getQualifiers();
2451 if (!ToPointee->isObjCLifetimeType() ||
2452 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2453 !ToQuals.withoutObjCLifetime().empty())
2454 return false;
2455
2456 // Argument must be a pointer to __strong to __weak.
2457 QualType FromPointee;
2458 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2459 FromPointee = FromPointer->getPointeeType();
2460 else
2461 return false;
2462
2463 Qualifiers FromQuals = FromPointee.getQualifiers();
2464 if (!FromPointee->isObjCLifetimeType() ||
2465 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2466 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2467 return false;
2468
2469 // Make sure that we have compatible qualifiers.
2470 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2471 if (!ToQuals.compatiblyIncludes(FromQuals))
2472 return false;
2473
2474 // Remove qualifiers from the pointee type we're converting from; they
2475 // aren't used in the compatibility check belong, and we'll be adding back
2476 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2477 FromPointee = FromPointee.getUnqualifiedType();
2478
2479 // The unqualified form of the pointee types must be compatible.
2480 ToPointee = ToPointee.getUnqualifiedType();
2481 bool IncompatibleObjC;
2482 if (Context.typesAreCompatible(FromPointee, ToPointee))
2483 FromPointee = ToPointee;
2484 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2485 IncompatibleObjC))
2486 return false;
2487
2488 /// \brief Construct the type we're converting to, which is a pointer to
2489 /// __autoreleasing pointee.
2490 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2491 ConvertedType = Context.getPointerType(FromPointee);
2492 return true;
2493 }
2494
IsBlockPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2495 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2496 QualType& ConvertedType) {
2497 QualType ToPointeeType;
2498 if (const BlockPointerType *ToBlockPtr =
2499 ToType->getAs<BlockPointerType>())
2500 ToPointeeType = ToBlockPtr->getPointeeType();
2501 else
2502 return false;
2503
2504 QualType FromPointeeType;
2505 if (const BlockPointerType *FromBlockPtr =
2506 FromType->getAs<BlockPointerType>())
2507 FromPointeeType = FromBlockPtr->getPointeeType();
2508 else
2509 return false;
2510 // We have pointer to blocks, check whether the only
2511 // differences in the argument and result types are in Objective-C
2512 // pointer conversions. If so, we permit the conversion.
2513
2514 const FunctionProtoType *FromFunctionType
2515 = FromPointeeType->getAs<FunctionProtoType>();
2516 const FunctionProtoType *ToFunctionType
2517 = ToPointeeType->getAs<FunctionProtoType>();
2518
2519 if (!FromFunctionType || !ToFunctionType)
2520 return false;
2521
2522 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2523 return true;
2524
2525 // Perform the quick checks that will tell us whether these
2526 // function types are obviously different.
2527 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2528 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2529 return false;
2530
2531 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2532 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2533 if (FromEInfo != ToEInfo)
2534 return false;
2535
2536 bool IncompatibleObjC = false;
2537 if (Context.hasSameType(FromFunctionType->getReturnType(),
2538 ToFunctionType->getReturnType())) {
2539 // Okay, the types match exactly. Nothing to do.
2540 } else {
2541 QualType RHS = FromFunctionType->getReturnType();
2542 QualType LHS = ToFunctionType->getReturnType();
2543 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2544 !RHS.hasQualifiers() && LHS.hasQualifiers())
2545 LHS = LHS.getUnqualifiedType();
2546
2547 if (Context.hasSameType(RHS,LHS)) {
2548 // OK exact match.
2549 } else if (isObjCPointerConversion(RHS, LHS,
2550 ConvertedType, IncompatibleObjC)) {
2551 if (IncompatibleObjC)
2552 return false;
2553 // Okay, we have an Objective-C pointer conversion.
2554 }
2555 else
2556 return false;
2557 }
2558
2559 // Check argument types.
2560 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2561 ArgIdx != NumArgs; ++ArgIdx) {
2562 IncompatibleObjC = false;
2563 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2564 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2565 if (Context.hasSameType(FromArgType, ToArgType)) {
2566 // Okay, the types match exactly. Nothing to do.
2567 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2568 ConvertedType, IncompatibleObjC)) {
2569 if (IncompatibleObjC)
2570 return false;
2571 // Okay, we have an Objective-C pointer conversion.
2572 } else
2573 // Argument types are too different. Abort.
2574 return false;
2575 }
2576 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2577 ToFunctionType))
2578 return false;
2579
2580 ConvertedType = ToType;
2581 return true;
2582 }
2583
2584 enum {
2585 ft_default,
2586 ft_different_class,
2587 ft_parameter_arity,
2588 ft_parameter_mismatch,
2589 ft_return_type,
2590 ft_qualifer_mismatch
2591 };
2592
2593 /// Attempts to get the FunctionProtoType from a Type. Handles
2594 /// MemberFunctionPointers properly.
tryGetFunctionProtoType(QualType FromType)2595 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2596 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2597 return FPT;
2598
2599 if (auto *MPT = FromType->getAs<MemberPointerType>())
2600 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2601
2602 return nullptr;
2603 }
2604
2605 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2606 /// function types. Catches different number of parameter, mismatch in
2607 /// parameter types, and different return types.
HandleFunctionTypeMismatch(PartialDiagnostic & PDiag,QualType FromType,QualType ToType)2608 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2609 QualType FromType, QualType ToType) {
2610 // If either type is not valid, include no extra info.
2611 if (FromType.isNull() || ToType.isNull()) {
2612 PDiag << ft_default;
2613 return;
2614 }
2615
2616 // Get the function type from the pointers.
2617 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2618 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2619 *ToMember = ToType->getAs<MemberPointerType>();
2620 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2621 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2622 << QualType(FromMember->getClass(), 0);
2623 return;
2624 }
2625 FromType = FromMember->getPointeeType();
2626 ToType = ToMember->getPointeeType();
2627 }
2628
2629 if (FromType->isPointerType())
2630 FromType = FromType->getPointeeType();
2631 if (ToType->isPointerType())
2632 ToType = ToType->getPointeeType();
2633
2634 // Remove references.
2635 FromType = FromType.getNonReferenceType();
2636 ToType = ToType.getNonReferenceType();
2637
2638 // Don't print extra info for non-specialized template functions.
2639 if (FromType->isInstantiationDependentType() &&
2640 !FromType->getAs<TemplateSpecializationType>()) {
2641 PDiag << ft_default;
2642 return;
2643 }
2644
2645 // No extra info for same types.
2646 if (Context.hasSameType(FromType, ToType)) {
2647 PDiag << ft_default;
2648 return;
2649 }
2650
2651 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2652 *ToFunction = tryGetFunctionProtoType(ToType);
2653
2654 // Both types need to be function types.
2655 if (!FromFunction || !ToFunction) {
2656 PDiag << ft_default;
2657 return;
2658 }
2659
2660 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2661 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2662 << FromFunction->getNumParams();
2663 return;
2664 }
2665
2666 // Handle different parameter types.
2667 unsigned ArgPos;
2668 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2669 PDiag << ft_parameter_mismatch << ArgPos + 1
2670 << ToFunction->getParamType(ArgPos)
2671 << FromFunction->getParamType(ArgPos);
2672 return;
2673 }
2674
2675 // Handle different return type.
2676 if (!Context.hasSameType(FromFunction->getReturnType(),
2677 ToFunction->getReturnType())) {
2678 PDiag << ft_return_type << ToFunction->getReturnType()
2679 << FromFunction->getReturnType();
2680 return;
2681 }
2682
2683 unsigned FromQuals = FromFunction->getTypeQuals(),
2684 ToQuals = ToFunction->getTypeQuals();
2685 if (FromQuals != ToQuals) {
2686 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2687 return;
2688 }
2689
2690 // Unable to find a difference, so add no extra info.
2691 PDiag << ft_default;
2692 }
2693
2694 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2695 /// for equality of their argument types. Caller has already checked that
2696 /// they have same number of arguments. If the parameters are different,
2697 /// ArgPos will have the parameter index of the first different parameter.
FunctionParamTypesAreEqual(const FunctionProtoType * OldType,const FunctionProtoType * NewType,unsigned * ArgPos)2698 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2699 const FunctionProtoType *NewType,
2700 unsigned *ArgPos) {
2701 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2702 N = NewType->param_type_begin(),
2703 E = OldType->param_type_end();
2704 O && (O != E); ++O, ++N) {
2705 if (!Context.hasSameType(O->getUnqualifiedType(),
2706 N->getUnqualifiedType())) {
2707 if (ArgPos)
2708 *ArgPos = O - OldType->param_type_begin();
2709 return false;
2710 }
2711 }
2712 return true;
2713 }
2714
2715 /// CheckPointerConversion - Check the pointer conversion from the
2716 /// expression From to the type ToType. This routine checks for
2717 /// ambiguous or inaccessible derived-to-base pointer
2718 /// conversions for which IsPointerConversion has already returned
2719 /// true. It returns true and produces a diagnostic if there was an
2720 /// error, or returns false otherwise.
CheckPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess,bool Diagnose)2721 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2722 CastKind &Kind,
2723 CXXCastPath& BasePath,
2724 bool IgnoreBaseAccess,
2725 bool Diagnose) {
2726 QualType FromType = From->getType();
2727 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2728
2729 Kind = CK_BitCast;
2730
2731 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2732 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2733 Expr::NPCK_ZeroExpression) {
2734 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2735 DiagRuntimeBehavior(From->getExprLoc(), From,
2736 PDiag(diag::warn_impcast_bool_to_null_pointer)
2737 << ToType << From->getSourceRange());
2738 else if (!isUnevaluatedContext())
2739 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2740 << ToType << From->getSourceRange();
2741 }
2742 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2743 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2744 QualType FromPointeeType = FromPtrType->getPointeeType(),
2745 ToPointeeType = ToPtrType->getPointeeType();
2746
2747 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2748 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2749 // We must have a derived-to-base conversion. Check an
2750 // ambiguous or inaccessible conversion.
2751 unsigned InaccessibleID = 0;
2752 unsigned AmbigiousID = 0;
2753 if (Diagnose) {
2754 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2755 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2756 }
2757 if (CheckDerivedToBaseConversion(
2758 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2759 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2760 &BasePath, IgnoreBaseAccess))
2761 return true;
2762
2763 // The conversion was successful.
2764 Kind = CK_DerivedToBase;
2765 }
2766
2767 if (Diagnose && !IsCStyleOrFunctionalCast &&
2768 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2769 assert(getLangOpts().MSVCCompat &&
2770 "this should only be possible with MSVCCompat!");
2771 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2772 << From->getSourceRange();
2773 }
2774 }
2775 } else if (const ObjCObjectPointerType *ToPtrType =
2776 ToType->getAs<ObjCObjectPointerType>()) {
2777 if (const ObjCObjectPointerType *FromPtrType =
2778 FromType->getAs<ObjCObjectPointerType>()) {
2779 // Objective-C++ conversions are always okay.
2780 // FIXME: We should have a different class of conversions for the
2781 // Objective-C++ implicit conversions.
2782 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2783 return false;
2784 } else if (FromType->isBlockPointerType()) {
2785 Kind = CK_BlockPointerToObjCPointerCast;
2786 } else {
2787 Kind = CK_CPointerToObjCPointerCast;
2788 }
2789 } else if (ToType->isBlockPointerType()) {
2790 if (!FromType->isBlockPointerType())
2791 Kind = CK_AnyPointerToBlockPointerCast;
2792 }
2793
2794 // We shouldn't fall into this case unless it's valid for other
2795 // reasons.
2796 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2797 Kind = CK_NullToPointer;
2798
2799 return false;
2800 }
2801
2802 /// IsMemberPointerConversion - Determines whether the conversion of the
2803 /// expression From, which has the (possibly adjusted) type FromType, can be
2804 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2805 /// If so, returns true and places the converted type (that might differ from
2806 /// ToType in its cv-qualifiers at some level) into ConvertedType.
IsMemberPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType)2807 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2808 QualType ToType,
2809 bool InOverloadResolution,
2810 QualType &ConvertedType) {
2811 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2812 if (!ToTypePtr)
2813 return false;
2814
2815 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2816 if (From->isNullPointerConstant(Context,
2817 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2818 : Expr::NPC_ValueDependentIsNull)) {
2819 ConvertedType = ToType;
2820 return true;
2821 }
2822
2823 // Otherwise, both types have to be member pointers.
2824 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2825 if (!FromTypePtr)
2826 return false;
2827
2828 // A pointer to member of B can be converted to a pointer to member of D,
2829 // where D is derived from B (C++ 4.11p2).
2830 QualType FromClass(FromTypePtr->getClass(), 0);
2831 QualType ToClass(ToTypePtr->getClass(), 0);
2832
2833 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2834 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2835 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2836 ToClass.getTypePtr());
2837 return true;
2838 }
2839
2840 return false;
2841 }
2842
2843 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2844 /// expression From to the type ToType. This routine checks for ambiguous or
2845 /// virtual or inaccessible base-to-derived member pointer conversions
2846 /// for which IsMemberPointerConversion has already returned true. It returns
2847 /// true and produces a diagnostic if there was an error, or returns false
2848 /// otherwise.
CheckMemberPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess)2849 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2850 CastKind &Kind,
2851 CXXCastPath &BasePath,
2852 bool IgnoreBaseAccess) {
2853 QualType FromType = From->getType();
2854 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2855 if (!FromPtrType) {
2856 // This must be a null pointer to member pointer conversion
2857 assert(From->isNullPointerConstant(Context,
2858 Expr::NPC_ValueDependentIsNull) &&
2859 "Expr must be null pointer constant!");
2860 Kind = CK_NullToMemberPointer;
2861 return false;
2862 }
2863
2864 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2865 assert(ToPtrType && "No member pointer cast has a target type "
2866 "that is not a member pointer.");
2867
2868 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2869 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2870
2871 // FIXME: What about dependent types?
2872 assert(FromClass->isRecordType() && "Pointer into non-class.");
2873 assert(ToClass->isRecordType() && "Pointer into non-class.");
2874
2875 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2876 /*DetectVirtual=*/true);
2877 bool DerivationOkay =
2878 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2879 assert(DerivationOkay &&
2880 "Should not have been called if derivation isn't OK.");
2881 (void)DerivationOkay;
2882
2883 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2884 getUnqualifiedType())) {
2885 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2886 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2887 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2888 return true;
2889 }
2890
2891 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2892 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2893 << FromClass << ToClass << QualType(VBase, 0)
2894 << From->getSourceRange();
2895 return true;
2896 }
2897
2898 if (!IgnoreBaseAccess)
2899 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2900 Paths.front(),
2901 diag::err_downcast_from_inaccessible_base);
2902
2903 // Must be a base to derived member conversion.
2904 BuildBasePathArray(Paths, BasePath);
2905 Kind = CK_BaseToDerivedMemberPointer;
2906 return false;
2907 }
2908
2909 /// Determine whether the lifetime conversion between the two given
2910 /// qualifiers sets is nontrivial.
isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,Qualifiers ToQuals)2911 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2912 Qualifiers ToQuals) {
2913 // Converting anything to const __unsafe_unretained is trivial.
2914 if (ToQuals.hasConst() &&
2915 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2916 return false;
2917
2918 return true;
2919 }
2920
2921 /// IsQualificationConversion - Determines whether the conversion from
2922 /// an rvalue of type FromType to ToType is a qualification conversion
2923 /// (C++ 4.4).
2924 ///
2925 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2926 /// when the qualification conversion involves a change in the Objective-C
2927 /// object lifetime.
2928 bool
IsQualificationConversion(QualType FromType,QualType ToType,bool CStyle,bool & ObjCLifetimeConversion)2929 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2930 bool CStyle, bool &ObjCLifetimeConversion) {
2931 FromType = Context.getCanonicalType(FromType);
2932 ToType = Context.getCanonicalType(ToType);
2933 ObjCLifetimeConversion = false;
2934
2935 // If FromType and ToType are the same type, this is not a
2936 // qualification conversion.
2937 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2938 return false;
2939
2940 // (C++ 4.4p4):
2941 // A conversion can add cv-qualifiers at levels other than the first
2942 // in multi-level pointers, subject to the following rules: [...]
2943 bool PreviousToQualsIncludeConst = true;
2944 bool UnwrappedAnyPointer = false;
2945 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2946 // Within each iteration of the loop, we check the qualifiers to
2947 // determine if this still looks like a qualification
2948 // conversion. Then, if all is well, we unwrap one more level of
2949 // pointers or pointers-to-members and do it all again
2950 // until there are no more pointers or pointers-to-members left to
2951 // unwrap.
2952 UnwrappedAnyPointer = true;
2953
2954 Qualifiers FromQuals = FromType.getQualifiers();
2955 Qualifiers ToQuals = ToType.getQualifiers();
2956
2957 // Ignore __unaligned qualifier if this type is void.
2958 if (ToType.getUnqualifiedType()->isVoidType())
2959 FromQuals.removeUnaligned();
2960
2961 // Objective-C ARC:
2962 // Check Objective-C lifetime conversions.
2963 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2964 UnwrappedAnyPointer) {
2965 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2966 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2967 ObjCLifetimeConversion = true;
2968 FromQuals.removeObjCLifetime();
2969 ToQuals.removeObjCLifetime();
2970 } else {
2971 // Qualification conversions cannot cast between different
2972 // Objective-C lifetime qualifiers.
2973 return false;
2974 }
2975 }
2976
2977 // Allow addition/removal of GC attributes but not changing GC attributes.
2978 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2979 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2980 FromQuals.removeObjCGCAttr();
2981 ToQuals.removeObjCGCAttr();
2982 }
2983
2984 // -- for every j > 0, if const is in cv 1,j then const is in cv
2985 // 2,j, and similarly for volatile.
2986 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2987 return false;
2988
2989 // -- if the cv 1,j and cv 2,j are different, then const is in
2990 // every cv for 0 < k < j.
2991 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2992 && !PreviousToQualsIncludeConst)
2993 return false;
2994
2995 // Keep track of whether all prior cv-qualifiers in the "to" type
2996 // include const.
2997 PreviousToQualsIncludeConst
2998 = PreviousToQualsIncludeConst && ToQuals.hasConst();
2999 }
3000
3001 // We are left with FromType and ToType being the pointee types
3002 // after unwrapping the original FromType and ToType the same number
3003 // of types. If we unwrapped any pointers, and if FromType and
3004 // ToType have the same unqualified type (since we checked
3005 // qualifiers above), then this is a qualification conversion.
3006 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3007 }
3008
3009 /// \brief - Determine whether this is a conversion from a scalar type to an
3010 /// atomic type.
3011 ///
3012 /// If successful, updates \c SCS's second and third steps in the conversion
3013 /// sequence to finish the conversion.
tryAtomicConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)3014 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3015 bool InOverloadResolution,
3016 StandardConversionSequence &SCS,
3017 bool CStyle) {
3018 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3019 if (!ToAtomic)
3020 return false;
3021
3022 StandardConversionSequence InnerSCS;
3023 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3024 InOverloadResolution, InnerSCS,
3025 CStyle, /*AllowObjCWritebackConversion=*/false))
3026 return false;
3027
3028 SCS.Second = InnerSCS.Second;
3029 SCS.setToType(1, InnerSCS.getToType(1));
3030 SCS.Third = InnerSCS.Third;
3031 SCS.QualificationIncludesObjCLifetime
3032 = InnerSCS.QualificationIncludesObjCLifetime;
3033 SCS.setToType(2, InnerSCS.getToType(2));
3034 return true;
3035 }
3036
isFirstArgumentCompatibleWithType(ASTContext & Context,CXXConstructorDecl * Constructor,QualType Type)3037 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3038 CXXConstructorDecl *Constructor,
3039 QualType Type) {
3040 const FunctionProtoType *CtorType =
3041 Constructor->getType()->getAs<FunctionProtoType>();
3042 if (CtorType->getNumParams() > 0) {
3043 QualType FirstArg = CtorType->getParamType(0);
3044 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3045 return true;
3046 }
3047 return false;
3048 }
3049
3050 static OverloadingResult
IsInitializerListConstructorConversion(Sema & S,Expr * From,QualType ToType,CXXRecordDecl * To,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit)3051 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3052 CXXRecordDecl *To,
3053 UserDefinedConversionSequence &User,
3054 OverloadCandidateSet &CandidateSet,
3055 bool AllowExplicit) {
3056 for (auto *D : S.LookupConstructors(To)) {
3057 auto Info = getConstructorInfo(D);
3058 if (!Info)
3059 continue;
3060
3061 bool Usable = !Info.Constructor->isInvalidDecl() &&
3062 S.isInitListConstructor(Info.Constructor) &&
3063 (AllowExplicit || !Info.Constructor->isExplicit());
3064 if (Usable) {
3065 // If the first argument is (a reference to) the target type,
3066 // suppress conversions.
3067 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3068 S.Context, Info.Constructor, ToType);
3069 if (Info.ConstructorTmpl)
3070 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3071 /*ExplicitArgs*/ nullptr, From,
3072 CandidateSet, SuppressUserConversions);
3073 else
3074 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3075 CandidateSet, SuppressUserConversions);
3076 }
3077 }
3078
3079 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3080
3081 OverloadCandidateSet::iterator Best;
3082 switch (auto Result =
3083 CandidateSet.BestViableFunction(S, From->getLocStart(),
3084 Best, true)) {
3085 case OR_Deleted:
3086 case OR_Success: {
3087 // Record the standard conversion we used and the conversion function.
3088 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3089 QualType ThisType = Constructor->getThisType(S.Context);
3090 // Initializer lists don't have conversions as such.
3091 User.Before.setAsIdentityConversion();
3092 User.HadMultipleCandidates = HadMultipleCandidates;
3093 User.ConversionFunction = Constructor;
3094 User.FoundConversionFunction = Best->FoundDecl;
3095 User.After.setAsIdentityConversion();
3096 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3097 User.After.setAllToTypes(ToType);
3098 return Result;
3099 }
3100
3101 case OR_No_Viable_Function:
3102 return OR_No_Viable_Function;
3103 case OR_Ambiguous:
3104 return OR_Ambiguous;
3105 }
3106
3107 llvm_unreachable("Invalid OverloadResult!");
3108 }
3109
3110 /// Determines whether there is a user-defined conversion sequence
3111 /// (C++ [over.ics.user]) that converts expression From to the type
3112 /// ToType. If such a conversion exists, User will contain the
3113 /// user-defined conversion sequence that performs such a conversion
3114 /// and this routine will return true. Otherwise, this routine returns
3115 /// false and User is unspecified.
3116 ///
3117 /// \param AllowExplicit true if the conversion should consider C++0x
3118 /// "explicit" conversion functions as well as non-explicit conversion
3119 /// functions (C++0x [class.conv.fct]p2).
3120 ///
3121 /// \param AllowObjCConversionOnExplicit true if the conversion should
3122 /// allow an extra Objective-C pointer conversion on uses of explicit
3123 /// constructors. Requires \c AllowExplicit to also be set.
3124 static OverloadingResult
IsUserDefinedConversion(Sema & S,Expr * From,QualType ToType,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit,bool AllowObjCConversionOnExplicit)3125 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3126 UserDefinedConversionSequence &User,
3127 OverloadCandidateSet &CandidateSet,
3128 bool AllowExplicit,
3129 bool AllowObjCConversionOnExplicit) {
3130 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3131
3132 // Whether we will only visit constructors.
3133 bool ConstructorsOnly = false;
3134
3135 // If the type we are conversion to is a class type, enumerate its
3136 // constructors.
3137 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3138 // C++ [over.match.ctor]p1:
3139 // When objects of class type are direct-initialized (8.5), or
3140 // copy-initialized from an expression of the same or a
3141 // derived class type (8.5), overload resolution selects the
3142 // constructor. [...] For copy-initialization, the candidate
3143 // functions are all the converting constructors (12.3.1) of
3144 // that class. The argument list is the expression-list within
3145 // the parentheses of the initializer.
3146 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3147 (From->getType()->getAs<RecordType>() &&
3148 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3149 ConstructorsOnly = true;
3150
3151 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3152 // We're not going to find any constructors.
3153 } else if (CXXRecordDecl *ToRecordDecl
3154 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3155
3156 Expr **Args = &From;
3157 unsigned NumArgs = 1;
3158 bool ListInitializing = false;
3159 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3160 // But first, see if there is an init-list-constructor that will work.
3161 OverloadingResult Result = IsInitializerListConstructorConversion(
3162 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3163 if (Result != OR_No_Viable_Function)
3164 return Result;
3165 // Never mind.
3166 CandidateSet.clear();
3167
3168 // If we're list-initializing, we pass the individual elements as
3169 // arguments, not the entire list.
3170 Args = InitList->getInits();
3171 NumArgs = InitList->getNumInits();
3172 ListInitializing = true;
3173 }
3174
3175 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3176 auto Info = getConstructorInfo(D);
3177 if (!Info)
3178 continue;
3179
3180 bool Usable = !Info.Constructor->isInvalidDecl();
3181 if (ListInitializing)
3182 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3183 else
3184 Usable = Usable &&
3185 Info.Constructor->isConvertingConstructor(AllowExplicit);
3186 if (Usable) {
3187 bool SuppressUserConversions = !ConstructorsOnly;
3188 if (SuppressUserConversions && ListInitializing) {
3189 SuppressUserConversions = false;
3190 if (NumArgs == 1) {
3191 // If the first argument is (a reference to) the target type,
3192 // suppress conversions.
3193 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3194 S.Context, Info.Constructor, ToType);
3195 }
3196 }
3197 if (Info.ConstructorTmpl)
3198 S.AddTemplateOverloadCandidate(
3199 Info.ConstructorTmpl, Info.FoundDecl,
3200 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3201 CandidateSet, SuppressUserConversions);
3202 else
3203 // Allow one user-defined conversion when user specifies a
3204 // From->ToType conversion via an static cast (c-style, etc).
3205 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3206 llvm::makeArrayRef(Args, NumArgs),
3207 CandidateSet, SuppressUserConversions);
3208 }
3209 }
3210 }
3211 }
3212
3213 // Enumerate conversion functions, if we're allowed to.
3214 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3215 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3216 // No conversion functions from incomplete types.
3217 } else if (const RecordType *FromRecordType
3218 = From->getType()->getAs<RecordType>()) {
3219 if (CXXRecordDecl *FromRecordDecl
3220 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3221 // Add all of the conversion functions as candidates.
3222 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3223 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3224 DeclAccessPair FoundDecl = I.getPair();
3225 NamedDecl *D = FoundDecl.getDecl();
3226 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3227 if (isa<UsingShadowDecl>(D))
3228 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3229
3230 CXXConversionDecl *Conv;
3231 FunctionTemplateDecl *ConvTemplate;
3232 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3233 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3234 else
3235 Conv = cast<CXXConversionDecl>(D);
3236
3237 if (AllowExplicit || !Conv->isExplicit()) {
3238 if (ConvTemplate)
3239 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3240 ActingContext, From, ToType,
3241 CandidateSet,
3242 AllowObjCConversionOnExplicit);
3243 else
3244 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3245 From, ToType, CandidateSet,
3246 AllowObjCConversionOnExplicit);
3247 }
3248 }
3249 }
3250 }
3251
3252 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3253
3254 OverloadCandidateSet::iterator Best;
3255 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3256 Best, true)) {
3257 case OR_Success:
3258 case OR_Deleted:
3259 // Record the standard conversion we used and the conversion function.
3260 if (CXXConstructorDecl *Constructor
3261 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3262 // C++ [over.ics.user]p1:
3263 // If the user-defined conversion is specified by a
3264 // constructor (12.3.1), the initial standard conversion
3265 // sequence converts the source type to the type required by
3266 // the argument of the constructor.
3267 //
3268 QualType ThisType = Constructor->getThisType(S.Context);
3269 if (isa<InitListExpr>(From)) {
3270 // Initializer lists don't have conversions as such.
3271 User.Before.setAsIdentityConversion();
3272 } else {
3273 if (Best->Conversions[0].isEllipsis())
3274 User.EllipsisConversion = true;
3275 else {
3276 User.Before = Best->Conversions[0].Standard;
3277 User.EllipsisConversion = false;
3278 }
3279 }
3280 User.HadMultipleCandidates = HadMultipleCandidates;
3281 User.ConversionFunction = Constructor;
3282 User.FoundConversionFunction = Best->FoundDecl;
3283 User.After.setAsIdentityConversion();
3284 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3285 User.After.setAllToTypes(ToType);
3286 return Result;
3287 }
3288 if (CXXConversionDecl *Conversion
3289 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3290 // C++ [over.ics.user]p1:
3291 //
3292 // [...] If the user-defined conversion is specified by a
3293 // conversion function (12.3.2), the initial standard
3294 // conversion sequence converts the source type to the
3295 // implicit object parameter of the conversion function.
3296 User.Before = Best->Conversions[0].Standard;
3297 User.HadMultipleCandidates = HadMultipleCandidates;
3298 User.ConversionFunction = Conversion;
3299 User.FoundConversionFunction = Best->FoundDecl;
3300 User.EllipsisConversion = false;
3301
3302 // C++ [over.ics.user]p2:
3303 // The second standard conversion sequence converts the
3304 // result of the user-defined conversion to the target type
3305 // for the sequence. Since an implicit conversion sequence
3306 // is an initialization, the special rules for
3307 // initialization by user-defined conversion apply when
3308 // selecting the best user-defined conversion for a
3309 // user-defined conversion sequence (see 13.3.3 and
3310 // 13.3.3.1).
3311 User.After = Best->FinalConversion;
3312 return Result;
3313 }
3314 llvm_unreachable("Not a constructor or conversion function?");
3315
3316 case OR_No_Viable_Function:
3317 return OR_No_Viable_Function;
3318
3319 case OR_Ambiguous:
3320 return OR_Ambiguous;
3321 }
3322
3323 llvm_unreachable("Invalid OverloadResult!");
3324 }
3325
3326 bool
DiagnoseMultipleUserDefinedConversion(Expr * From,QualType ToType)3327 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3328 ImplicitConversionSequence ICS;
3329 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3330 OverloadCandidateSet::CSK_Normal);
3331 OverloadingResult OvResult =
3332 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3333 CandidateSet, false, false);
3334 if (OvResult == OR_Ambiguous)
3335 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3336 << From->getType() << ToType << From->getSourceRange();
3337 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3338 if (!RequireCompleteType(From->getLocStart(), ToType,
3339 diag::err_typecheck_nonviable_condition_incomplete,
3340 From->getType(), From->getSourceRange()))
3341 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3342 << false << From->getType() << From->getSourceRange() << ToType;
3343 } else
3344 return false;
3345 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3346 return true;
3347 }
3348
3349 /// \brief Compare the user-defined conversion functions or constructors
3350 /// of two user-defined conversion sequences to determine whether any ordering
3351 /// is possible.
3352 static ImplicitConversionSequence::CompareKind
compareConversionFunctions(Sema & S,FunctionDecl * Function1,FunctionDecl * Function2)3353 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3354 FunctionDecl *Function2) {
3355 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3356 return ImplicitConversionSequence::Indistinguishable;
3357
3358 // Objective-C++:
3359 // If both conversion functions are implicitly-declared conversions from
3360 // a lambda closure type to a function pointer and a block pointer,
3361 // respectively, always prefer the conversion to a function pointer,
3362 // because the function pointer is more lightweight and is more likely
3363 // to keep code working.
3364 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3365 if (!Conv1)
3366 return ImplicitConversionSequence::Indistinguishable;
3367
3368 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3369 if (!Conv2)
3370 return ImplicitConversionSequence::Indistinguishable;
3371
3372 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3373 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3374 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3375 if (Block1 != Block2)
3376 return Block1 ? ImplicitConversionSequence::Worse
3377 : ImplicitConversionSequence::Better;
3378 }
3379
3380 return ImplicitConversionSequence::Indistinguishable;
3381 }
3382
hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence & ICS)3383 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3384 const ImplicitConversionSequence &ICS) {
3385 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3386 (ICS.isUserDefined() &&
3387 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3388 }
3389
3390 /// CompareImplicitConversionSequences - Compare two implicit
3391 /// conversion sequences to determine whether one is better than the
3392 /// other or if they are indistinguishable (C++ 13.3.3.2).
3393 static ImplicitConversionSequence::CompareKind
CompareImplicitConversionSequences(Sema & S,SourceLocation Loc,const ImplicitConversionSequence & ICS1,const ImplicitConversionSequence & ICS2)3394 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3395 const ImplicitConversionSequence& ICS1,
3396 const ImplicitConversionSequence& ICS2)
3397 {
3398 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3399 // conversion sequences (as defined in 13.3.3.1)
3400 // -- a standard conversion sequence (13.3.3.1.1) is a better
3401 // conversion sequence than a user-defined conversion sequence or
3402 // an ellipsis conversion sequence, and
3403 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3404 // conversion sequence than an ellipsis conversion sequence
3405 // (13.3.3.1.3).
3406 //
3407 // C++0x [over.best.ics]p10:
3408 // For the purpose of ranking implicit conversion sequences as
3409 // described in 13.3.3.2, the ambiguous conversion sequence is
3410 // treated as a user-defined sequence that is indistinguishable
3411 // from any other user-defined conversion sequence.
3412
3413 // String literal to 'char *' conversion has been deprecated in C++03. It has
3414 // been removed from C++11. We still accept this conversion, if it happens at
3415 // the best viable function. Otherwise, this conversion is considered worse
3416 // than ellipsis conversion. Consider this as an extension; this is not in the
3417 // standard. For example:
3418 //
3419 // int &f(...); // #1
3420 // void f(char*); // #2
3421 // void g() { int &r = f("foo"); }
3422 //
3423 // In C++03, we pick #2 as the best viable function.
3424 // In C++11, we pick #1 as the best viable function, because ellipsis
3425 // conversion is better than string-literal to char* conversion (since there
3426 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3427 // convert arguments, #2 would be the best viable function in C++11.
3428 // If the best viable function has this conversion, a warning will be issued
3429 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3430
3431 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3432 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3433 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3434 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3435 ? ImplicitConversionSequence::Worse
3436 : ImplicitConversionSequence::Better;
3437
3438 if (ICS1.getKindRank() < ICS2.getKindRank())
3439 return ImplicitConversionSequence::Better;
3440 if (ICS2.getKindRank() < ICS1.getKindRank())
3441 return ImplicitConversionSequence::Worse;
3442
3443 // The following checks require both conversion sequences to be of
3444 // the same kind.
3445 if (ICS1.getKind() != ICS2.getKind())
3446 return ImplicitConversionSequence::Indistinguishable;
3447
3448 ImplicitConversionSequence::CompareKind Result =
3449 ImplicitConversionSequence::Indistinguishable;
3450
3451 // Two implicit conversion sequences of the same form are
3452 // indistinguishable conversion sequences unless one of the
3453 // following rules apply: (C++ 13.3.3.2p3):
3454
3455 // List-initialization sequence L1 is a better conversion sequence than
3456 // list-initialization sequence L2 if:
3457 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3458 // if not that,
3459 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3460 // and N1 is smaller than N2.,
3461 // even if one of the other rules in this paragraph would otherwise apply.
3462 if (!ICS1.isBad()) {
3463 if (ICS1.isStdInitializerListElement() &&
3464 !ICS2.isStdInitializerListElement())
3465 return ImplicitConversionSequence::Better;
3466 if (!ICS1.isStdInitializerListElement() &&
3467 ICS2.isStdInitializerListElement())
3468 return ImplicitConversionSequence::Worse;
3469 }
3470
3471 if (ICS1.isStandard())
3472 // Standard conversion sequence S1 is a better conversion sequence than
3473 // standard conversion sequence S2 if [...]
3474 Result = CompareStandardConversionSequences(S, Loc,
3475 ICS1.Standard, ICS2.Standard);
3476 else if (ICS1.isUserDefined()) {
3477 // User-defined conversion sequence U1 is a better conversion
3478 // sequence than another user-defined conversion sequence U2 if
3479 // they contain the same user-defined conversion function or
3480 // constructor and if the second standard conversion sequence of
3481 // U1 is better than the second standard conversion sequence of
3482 // U2 (C++ 13.3.3.2p3).
3483 if (ICS1.UserDefined.ConversionFunction ==
3484 ICS2.UserDefined.ConversionFunction)
3485 Result = CompareStandardConversionSequences(S, Loc,
3486 ICS1.UserDefined.After,
3487 ICS2.UserDefined.After);
3488 else
3489 Result = compareConversionFunctions(S,
3490 ICS1.UserDefined.ConversionFunction,
3491 ICS2.UserDefined.ConversionFunction);
3492 }
3493
3494 return Result;
3495 }
3496
hasSimilarType(ASTContext & Context,QualType T1,QualType T2)3497 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3498 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3499 Qualifiers Quals;
3500 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3501 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3502 }
3503
3504 return Context.hasSameUnqualifiedType(T1, T2);
3505 }
3506
3507 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3508 // determine if one is a proper subset of the other.
3509 static ImplicitConversionSequence::CompareKind
compareStandardConversionSubsets(ASTContext & Context,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3510 compareStandardConversionSubsets(ASTContext &Context,
3511 const StandardConversionSequence& SCS1,
3512 const StandardConversionSequence& SCS2) {
3513 ImplicitConversionSequence::CompareKind Result
3514 = ImplicitConversionSequence::Indistinguishable;
3515
3516 // the identity conversion sequence is considered to be a subsequence of
3517 // any non-identity conversion sequence
3518 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3519 return ImplicitConversionSequence::Better;
3520 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3521 return ImplicitConversionSequence::Worse;
3522
3523 if (SCS1.Second != SCS2.Second) {
3524 if (SCS1.Second == ICK_Identity)
3525 Result = ImplicitConversionSequence::Better;
3526 else if (SCS2.Second == ICK_Identity)
3527 Result = ImplicitConversionSequence::Worse;
3528 else
3529 return ImplicitConversionSequence::Indistinguishable;
3530 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3531 return ImplicitConversionSequence::Indistinguishable;
3532
3533 if (SCS1.Third == SCS2.Third) {
3534 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3535 : ImplicitConversionSequence::Indistinguishable;
3536 }
3537
3538 if (SCS1.Third == ICK_Identity)
3539 return Result == ImplicitConversionSequence::Worse
3540 ? ImplicitConversionSequence::Indistinguishable
3541 : ImplicitConversionSequence::Better;
3542
3543 if (SCS2.Third == ICK_Identity)
3544 return Result == ImplicitConversionSequence::Better
3545 ? ImplicitConversionSequence::Indistinguishable
3546 : ImplicitConversionSequence::Worse;
3547
3548 return ImplicitConversionSequence::Indistinguishable;
3549 }
3550
3551 /// \brief Determine whether one of the given reference bindings is better
3552 /// than the other based on what kind of bindings they are.
3553 static bool
isBetterReferenceBindingKind(const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3554 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3555 const StandardConversionSequence &SCS2) {
3556 // C++0x [over.ics.rank]p3b4:
3557 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3558 // implicit object parameter of a non-static member function declared
3559 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3560 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3561 // lvalue reference to a function lvalue and S2 binds an rvalue
3562 // reference*.
3563 //
3564 // FIXME: Rvalue references. We're going rogue with the above edits,
3565 // because the semantics in the current C++0x working paper (N3225 at the
3566 // time of this writing) break the standard definition of std::forward
3567 // and std::reference_wrapper when dealing with references to functions.
3568 // Proposed wording changes submitted to CWG for consideration.
3569 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3570 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3571 return false;
3572
3573 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3574 SCS2.IsLvalueReference) ||
3575 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3576 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3577 }
3578
3579 /// CompareStandardConversionSequences - Compare two standard
3580 /// conversion sequences to determine whether one is better than the
3581 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3582 static ImplicitConversionSequence::CompareKind
CompareStandardConversionSequences(Sema & S,SourceLocation Loc,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3583 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3584 const StandardConversionSequence& SCS1,
3585 const StandardConversionSequence& SCS2)
3586 {
3587 // Standard conversion sequence S1 is a better conversion sequence
3588 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3589
3590 // -- S1 is a proper subsequence of S2 (comparing the conversion
3591 // sequences in the canonical form defined by 13.3.3.1.1,
3592 // excluding any Lvalue Transformation; the identity conversion
3593 // sequence is considered to be a subsequence of any
3594 // non-identity conversion sequence) or, if not that,
3595 if (ImplicitConversionSequence::CompareKind CK
3596 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3597 return CK;
3598
3599 // -- the rank of S1 is better than the rank of S2 (by the rules
3600 // defined below), or, if not that,
3601 ImplicitConversionRank Rank1 = SCS1.getRank();
3602 ImplicitConversionRank Rank2 = SCS2.getRank();
3603 if (Rank1 < Rank2)
3604 return ImplicitConversionSequence::Better;
3605 else if (Rank2 < Rank1)
3606 return ImplicitConversionSequence::Worse;
3607
3608 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3609 // are indistinguishable unless one of the following rules
3610 // applies:
3611
3612 // A conversion that is not a conversion of a pointer, or
3613 // pointer to member, to bool is better than another conversion
3614 // that is such a conversion.
3615 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3616 return SCS2.isPointerConversionToBool()
3617 ? ImplicitConversionSequence::Better
3618 : ImplicitConversionSequence::Worse;
3619
3620 // C++ [over.ics.rank]p4b2:
3621 //
3622 // If class B is derived directly or indirectly from class A,
3623 // conversion of B* to A* is better than conversion of B* to
3624 // void*, and conversion of A* to void* is better than conversion
3625 // of B* to void*.
3626 bool SCS1ConvertsToVoid
3627 = SCS1.isPointerConversionToVoidPointer(S.Context);
3628 bool SCS2ConvertsToVoid
3629 = SCS2.isPointerConversionToVoidPointer(S.Context);
3630 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3631 // Exactly one of the conversion sequences is a conversion to
3632 // a void pointer; it's the worse conversion.
3633 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3634 : ImplicitConversionSequence::Worse;
3635 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3636 // Neither conversion sequence converts to a void pointer; compare
3637 // their derived-to-base conversions.
3638 if (ImplicitConversionSequence::CompareKind DerivedCK
3639 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3640 return DerivedCK;
3641 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3642 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3643 // Both conversion sequences are conversions to void
3644 // pointers. Compare the source types to determine if there's an
3645 // inheritance relationship in their sources.
3646 QualType FromType1 = SCS1.getFromType();
3647 QualType FromType2 = SCS2.getFromType();
3648
3649 // Adjust the types we're converting from via the array-to-pointer
3650 // conversion, if we need to.
3651 if (SCS1.First == ICK_Array_To_Pointer)
3652 FromType1 = S.Context.getArrayDecayedType(FromType1);
3653 if (SCS2.First == ICK_Array_To_Pointer)
3654 FromType2 = S.Context.getArrayDecayedType(FromType2);
3655
3656 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3657 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3658
3659 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3660 return ImplicitConversionSequence::Better;
3661 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3662 return ImplicitConversionSequence::Worse;
3663
3664 // Objective-C++: If one interface is more specific than the
3665 // other, it is the better one.
3666 const ObjCObjectPointerType* FromObjCPtr1
3667 = FromType1->getAs<ObjCObjectPointerType>();
3668 const ObjCObjectPointerType* FromObjCPtr2
3669 = FromType2->getAs<ObjCObjectPointerType>();
3670 if (FromObjCPtr1 && FromObjCPtr2) {
3671 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3672 FromObjCPtr2);
3673 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3674 FromObjCPtr1);
3675 if (AssignLeft != AssignRight) {
3676 return AssignLeft? ImplicitConversionSequence::Better
3677 : ImplicitConversionSequence::Worse;
3678 }
3679 }
3680 }
3681
3682 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3683 // bullet 3).
3684 if (ImplicitConversionSequence::CompareKind QualCK
3685 = CompareQualificationConversions(S, SCS1, SCS2))
3686 return QualCK;
3687
3688 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3689 // Check for a better reference binding based on the kind of bindings.
3690 if (isBetterReferenceBindingKind(SCS1, SCS2))
3691 return ImplicitConversionSequence::Better;
3692 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3693 return ImplicitConversionSequence::Worse;
3694
3695 // C++ [over.ics.rank]p3b4:
3696 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3697 // which the references refer are the same type except for
3698 // top-level cv-qualifiers, and the type to which the reference
3699 // initialized by S2 refers is more cv-qualified than the type
3700 // to which the reference initialized by S1 refers.
3701 QualType T1 = SCS1.getToType(2);
3702 QualType T2 = SCS2.getToType(2);
3703 T1 = S.Context.getCanonicalType(T1);
3704 T2 = S.Context.getCanonicalType(T2);
3705 Qualifiers T1Quals, T2Quals;
3706 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3707 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3708 if (UnqualT1 == UnqualT2) {
3709 // Objective-C++ ARC: If the references refer to objects with different
3710 // lifetimes, prefer bindings that don't change lifetime.
3711 if (SCS1.ObjCLifetimeConversionBinding !=
3712 SCS2.ObjCLifetimeConversionBinding) {
3713 return SCS1.ObjCLifetimeConversionBinding
3714 ? ImplicitConversionSequence::Worse
3715 : ImplicitConversionSequence::Better;
3716 }
3717
3718 // If the type is an array type, promote the element qualifiers to the
3719 // type for comparison.
3720 if (isa<ArrayType>(T1) && T1Quals)
3721 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3722 if (isa<ArrayType>(T2) && T2Quals)
3723 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3724 if (T2.isMoreQualifiedThan(T1))
3725 return ImplicitConversionSequence::Better;
3726 else if (T1.isMoreQualifiedThan(T2))
3727 return ImplicitConversionSequence::Worse;
3728 }
3729 }
3730
3731 // In Microsoft mode, prefer an integral conversion to a
3732 // floating-to-integral conversion if the integral conversion
3733 // is between types of the same size.
3734 // For example:
3735 // void f(float);
3736 // void f(int);
3737 // int main {
3738 // long a;
3739 // f(a);
3740 // }
3741 // Here, MSVC will call f(int) instead of generating a compile error
3742 // as clang will do in standard mode.
3743 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3744 SCS2.Second == ICK_Floating_Integral &&
3745 S.Context.getTypeSize(SCS1.getFromType()) ==
3746 S.Context.getTypeSize(SCS1.getToType(2)))
3747 return ImplicitConversionSequence::Better;
3748
3749 return ImplicitConversionSequence::Indistinguishable;
3750 }
3751
3752 /// CompareQualificationConversions - Compares two standard conversion
3753 /// sequences to determine whether they can be ranked based on their
3754 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3755 static ImplicitConversionSequence::CompareKind
CompareQualificationConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3756 CompareQualificationConversions(Sema &S,
3757 const StandardConversionSequence& SCS1,
3758 const StandardConversionSequence& SCS2) {
3759 // C++ 13.3.3.2p3:
3760 // -- S1 and S2 differ only in their qualification conversion and
3761 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3762 // cv-qualification signature of type T1 is a proper subset of
3763 // the cv-qualification signature of type T2, and S1 is not the
3764 // deprecated string literal array-to-pointer conversion (4.2).
3765 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3766 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3767 return ImplicitConversionSequence::Indistinguishable;
3768
3769 // FIXME: the example in the standard doesn't use a qualification
3770 // conversion (!)
3771 QualType T1 = SCS1.getToType(2);
3772 QualType T2 = SCS2.getToType(2);
3773 T1 = S.Context.getCanonicalType(T1);
3774 T2 = S.Context.getCanonicalType(T2);
3775 Qualifiers T1Quals, T2Quals;
3776 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3777 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3778
3779 // If the types are the same, we won't learn anything by unwrapped
3780 // them.
3781 if (UnqualT1 == UnqualT2)
3782 return ImplicitConversionSequence::Indistinguishable;
3783
3784 // If the type is an array type, promote the element qualifiers to the type
3785 // for comparison.
3786 if (isa<ArrayType>(T1) && T1Quals)
3787 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3788 if (isa<ArrayType>(T2) && T2Quals)
3789 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3790
3791 ImplicitConversionSequence::CompareKind Result
3792 = ImplicitConversionSequence::Indistinguishable;
3793
3794 // Objective-C++ ARC:
3795 // Prefer qualification conversions not involving a change in lifetime
3796 // to qualification conversions that do not change lifetime.
3797 if (SCS1.QualificationIncludesObjCLifetime !=
3798 SCS2.QualificationIncludesObjCLifetime) {
3799 Result = SCS1.QualificationIncludesObjCLifetime
3800 ? ImplicitConversionSequence::Worse
3801 : ImplicitConversionSequence::Better;
3802 }
3803
3804 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3805 // Within each iteration of the loop, we check the qualifiers to
3806 // determine if this still looks like a qualification
3807 // conversion. Then, if all is well, we unwrap one more level of
3808 // pointers or pointers-to-members and do it all again
3809 // until there are no more pointers or pointers-to-members left
3810 // to unwrap. This essentially mimics what
3811 // IsQualificationConversion does, but here we're checking for a
3812 // strict subset of qualifiers.
3813 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3814 // The qualifiers are the same, so this doesn't tell us anything
3815 // about how the sequences rank.
3816 ;
3817 else if (T2.isMoreQualifiedThan(T1)) {
3818 // T1 has fewer qualifiers, so it could be the better sequence.
3819 if (Result == ImplicitConversionSequence::Worse)
3820 // Neither has qualifiers that are a subset of the other's
3821 // qualifiers.
3822 return ImplicitConversionSequence::Indistinguishable;
3823
3824 Result = ImplicitConversionSequence::Better;
3825 } else if (T1.isMoreQualifiedThan(T2)) {
3826 // T2 has fewer qualifiers, so it could be the better sequence.
3827 if (Result == ImplicitConversionSequence::Better)
3828 // Neither has qualifiers that are a subset of the other's
3829 // qualifiers.
3830 return ImplicitConversionSequence::Indistinguishable;
3831
3832 Result = ImplicitConversionSequence::Worse;
3833 } else {
3834 // Qualifiers are disjoint.
3835 return ImplicitConversionSequence::Indistinguishable;
3836 }
3837
3838 // If the types after this point are equivalent, we're done.
3839 if (S.Context.hasSameUnqualifiedType(T1, T2))
3840 break;
3841 }
3842
3843 // Check that the winning standard conversion sequence isn't using
3844 // the deprecated string literal array to pointer conversion.
3845 switch (Result) {
3846 case ImplicitConversionSequence::Better:
3847 if (SCS1.DeprecatedStringLiteralToCharPtr)
3848 Result = ImplicitConversionSequence::Indistinguishable;
3849 break;
3850
3851 case ImplicitConversionSequence::Indistinguishable:
3852 break;
3853
3854 case ImplicitConversionSequence::Worse:
3855 if (SCS2.DeprecatedStringLiteralToCharPtr)
3856 Result = ImplicitConversionSequence::Indistinguishable;
3857 break;
3858 }
3859
3860 return Result;
3861 }
3862
3863 /// CompareDerivedToBaseConversions - Compares two standard conversion
3864 /// sequences to determine whether they can be ranked based on their
3865 /// various kinds of derived-to-base conversions (C++
3866 /// [over.ics.rank]p4b3). As part of these checks, we also look at
3867 /// conversions between Objective-C interface types.
3868 static ImplicitConversionSequence::CompareKind
CompareDerivedToBaseConversions(Sema & S,SourceLocation Loc,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3869 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3870 const StandardConversionSequence& SCS1,
3871 const StandardConversionSequence& SCS2) {
3872 QualType FromType1 = SCS1.getFromType();
3873 QualType ToType1 = SCS1.getToType(1);
3874 QualType FromType2 = SCS2.getFromType();
3875 QualType ToType2 = SCS2.getToType(1);
3876
3877 // Adjust the types we're converting from via the array-to-pointer
3878 // conversion, if we need to.
3879 if (SCS1.First == ICK_Array_To_Pointer)
3880 FromType1 = S.Context.getArrayDecayedType(FromType1);
3881 if (SCS2.First == ICK_Array_To_Pointer)
3882 FromType2 = S.Context.getArrayDecayedType(FromType2);
3883
3884 // Canonicalize all of the types.
3885 FromType1 = S.Context.getCanonicalType(FromType1);
3886 ToType1 = S.Context.getCanonicalType(ToType1);
3887 FromType2 = S.Context.getCanonicalType(FromType2);
3888 ToType2 = S.Context.getCanonicalType(ToType2);
3889
3890 // C++ [over.ics.rank]p4b3:
3891 //
3892 // If class B is derived directly or indirectly from class A and
3893 // class C is derived directly or indirectly from B,
3894 //
3895 // Compare based on pointer conversions.
3896 if (SCS1.Second == ICK_Pointer_Conversion &&
3897 SCS2.Second == ICK_Pointer_Conversion &&
3898 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3899 FromType1->isPointerType() && FromType2->isPointerType() &&
3900 ToType1->isPointerType() && ToType2->isPointerType()) {
3901 QualType FromPointee1
3902 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3903 QualType ToPointee1
3904 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3905 QualType FromPointee2
3906 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3907 QualType ToPointee2
3908 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3909
3910 // -- conversion of C* to B* is better than conversion of C* to A*,
3911 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3912 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3913 return ImplicitConversionSequence::Better;
3914 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3915 return ImplicitConversionSequence::Worse;
3916 }
3917
3918 // -- conversion of B* to A* is better than conversion of C* to A*,
3919 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3920 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3921 return ImplicitConversionSequence::Better;
3922 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3923 return ImplicitConversionSequence::Worse;
3924 }
3925 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3926 SCS2.Second == ICK_Pointer_Conversion) {
3927 const ObjCObjectPointerType *FromPtr1
3928 = FromType1->getAs<ObjCObjectPointerType>();
3929 const ObjCObjectPointerType *FromPtr2
3930 = FromType2->getAs<ObjCObjectPointerType>();
3931 const ObjCObjectPointerType *ToPtr1
3932 = ToType1->getAs<ObjCObjectPointerType>();
3933 const ObjCObjectPointerType *ToPtr2
3934 = ToType2->getAs<ObjCObjectPointerType>();
3935
3936 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3937 // Apply the same conversion ranking rules for Objective-C pointer types
3938 // that we do for C++ pointers to class types. However, we employ the
3939 // Objective-C pseudo-subtyping relationship used for assignment of
3940 // Objective-C pointer types.
3941 bool FromAssignLeft
3942 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3943 bool FromAssignRight
3944 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3945 bool ToAssignLeft
3946 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3947 bool ToAssignRight
3948 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3949
3950 // A conversion to an a non-id object pointer type or qualified 'id'
3951 // type is better than a conversion to 'id'.
3952 if (ToPtr1->isObjCIdType() &&
3953 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3954 return ImplicitConversionSequence::Worse;
3955 if (ToPtr2->isObjCIdType() &&
3956 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3957 return ImplicitConversionSequence::Better;
3958
3959 // A conversion to a non-id object pointer type is better than a
3960 // conversion to a qualified 'id' type
3961 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3962 return ImplicitConversionSequence::Worse;
3963 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3964 return ImplicitConversionSequence::Better;
3965
3966 // A conversion to an a non-Class object pointer type or qualified 'Class'
3967 // type is better than a conversion to 'Class'.
3968 if (ToPtr1->isObjCClassType() &&
3969 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3970 return ImplicitConversionSequence::Worse;
3971 if (ToPtr2->isObjCClassType() &&
3972 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3973 return ImplicitConversionSequence::Better;
3974
3975 // A conversion to a non-Class object pointer type is better than a
3976 // conversion to a qualified 'Class' type.
3977 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3978 return ImplicitConversionSequence::Worse;
3979 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3980 return ImplicitConversionSequence::Better;
3981
3982 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3983 if (S.Context.hasSameType(FromType1, FromType2) &&
3984 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3985 (ToAssignLeft != ToAssignRight))
3986 return ToAssignLeft? ImplicitConversionSequence::Worse
3987 : ImplicitConversionSequence::Better;
3988
3989 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3990 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3991 (FromAssignLeft != FromAssignRight))
3992 return FromAssignLeft? ImplicitConversionSequence::Better
3993 : ImplicitConversionSequence::Worse;
3994 }
3995 }
3996
3997 // Ranking of member-pointer types.
3998 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3999 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4000 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4001 const MemberPointerType * FromMemPointer1 =
4002 FromType1->getAs<MemberPointerType>();
4003 const MemberPointerType * ToMemPointer1 =
4004 ToType1->getAs<MemberPointerType>();
4005 const MemberPointerType * FromMemPointer2 =
4006 FromType2->getAs<MemberPointerType>();
4007 const MemberPointerType * ToMemPointer2 =
4008 ToType2->getAs<MemberPointerType>();
4009 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4010 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4011 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4012 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4013 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4014 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4015 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4016 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4017 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4018 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4019 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4020 return ImplicitConversionSequence::Worse;
4021 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4022 return ImplicitConversionSequence::Better;
4023 }
4024 // conversion of B::* to C::* is better than conversion of A::* to C::*
4025 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4026 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4027 return ImplicitConversionSequence::Better;
4028 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4029 return ImplicitConversionSequence::Worse;
4030 }
4031 }
4032
4033 if (SCS1.Second == ICK_Derived_To_Base) {
4034 // -- conversion of C to B is better than conversion of C to A,
4035 // -- binding of an expression of type C to a reference of type
4036 // B& is better than binding an expression of type C to a
4037 // reference of type A&,
4038 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4039 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4040 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4041 return ImplicitConversionSequence::Better;
4042 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4043 return ImplicitConversionSequence::Worse;
4044 }
4045
4046 // -- conversion of B to A is better than conversion of C to A.
4047 // -- binding of an expression of type B to a reference of type
4048 // A& is better than binding an expression of type C to a
4049 // reference of type A&,
4050 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4051 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4052 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4053 return ImplicitConversionSequence::Better;
4054 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4055 return ImplicitConversionSequence::Worse;
4056 }
4057 }
4058
4059 return ImplicitConversionSequence::Indistinguishable;
4060 }
4061
4062 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4063 /// C++ class.
isTypeValid(QualType T)4064 static bool isTypeValid(QualType T) {
4065 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4066 return !Record->isInvalidDecl();
4067
4068 return true;
4069 }
4070
4071 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4072 /// determine whether they are reference-related,
4073 /// reference-compatible, reference-compatible with added
4074 /// qualification, or incompatible, for use in C++ initialization by
4075 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4076 /// type, and the first type (T1) is the pointee type of the reference
4077 /// type being initialized.
4078 Sema::ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc,QualType OrigT1,QualType OrigT2,bool & DerivedToBase,bool & ObjCConversion,bool & ObjCLifetimeConversion)4079 Sema::CompareReferenceRelationship(SourceLocation Loc,
4080 QualType OrigT1, QualType OrigT2,
4081 bool &DerivedToBase,
4082 bool &ObjCConversion,
4083 bool &ObjCLifetimeConversion) {
4084 assert(!OrigT1->isReferenceType() &&
4085 "T1 must be the pointee type of the reference type");
4086 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4087
4088 QualType T1 = Context.getCanonicalType(OrigT1);
4089 QualType T2 = Context.getCanonicalType(OrigT2);
4090 Qualifiers T1Quals, T2Quals;
4091 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4092 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4093
4094 // C++ [dcl.init.ref]p4:
4095 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4096 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4097 // T1 is a base class of T2.
4098 DerivedToBase = false;
4099 ObjCConversion = false;
4100 ObjCLifetimeConversion = false;
4101 if (UnqualT1 == UnqualT2) {
4102 // Nothing to do.
4103 } else if (isCompleteType(Loc, OrigT2) &&
4104 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4105 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4106 DerivedToBase = true;
4107 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4108 UnqualT2->isObjCObjectOrInterfaceType() &&
4109 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4110 ObjCConversion = true;
4111 else
4112 return Ref_Incompatible;
4113
4114 // At this point, we know that T1 and T2 are reference-related (at
4115 // least).
4116
4117 // If the type is an array type, promote the element qualifiers to the type
4118 // for comparison.
4119 if (isa<ArrayType>(T1) && T1Quals)
4120 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4121 if (isa<ArrayType>(T2) && T2Quals)
4122 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4123
4124 // C++ [dcl.init.ref]p4:
4125 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4126 // reference-related to T2 and cv1 is the same cv-qualification
4127 // as, or greater cv-qualification than, cv2. For purposes of
4128 // overload resolution, cases for which cv1 is greater
4129 // cv-qualification than cv2 are identified as
4130 // reference-compatible with added qualification (see 13.3.3.2).
4131 //
4132 // Note that we also require equivalence of Objective-C GC and address-space
4133 // qualifiers when performing these computations, so that e.g., an int in
4134 // address space 1 is not reference-compatible with an int in address
4135 // space 2.
4136 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4137 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4138 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4139 ObjCLifetimeConversion = true;
4140
4141 T1Quals.removeObjCLifetime();
4142 T2Quals.removeObjCLifetime();
4143 }
4144
4145 // MS compiler ignores __unaligned qualifier for references; do the same.
4146 T1Quals.removeUnaligned();
4147 T2Quals.removeUnaligned();
4148
4149 if (T1Quals == T2Quals)
4150 return Ref_Compatible;
4151 else if (T1Quals.compatiblyIncludes(T2Quals))
4152 return Ref_Compatible_With_Added_Qualification;
4153 else
4154 return Ref_Related;
4155 }
4156
4157 /// \brief Look for a user-defined conversion to an value reference-compatible
4158 /// with DeclType. Return true if something definite is found.
4159 static bool
FindConversionForRefInit(Sema & S,ImplicitConversionSequence & ICS,QualType DeclType,SourceLocation DeclLoc,Expr * Init,QualType T2,bool AllowRvalues,bool AllowExplicit)4160 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4161 QualType DeclType, SourceLocation DeclLoc,
4162 Expr *Init, QualType T2, bool AllowRvalues,
4163 bool AllowExplicit) {
4164 assert(T2->isRecordType() && "Can only find conversions of record types.");
4165 CXXRecordDecl *T2RecordDecl
4166 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4167
4168 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4169 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4170 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4171 NamedDecl *D = *I;
4172 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4173 if (isa<UsingShadowDecl>(D))
4174 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4175
4176 FunctionTemplateDecl *ConvTemplate
4177 = dyn_cast<FunctionTemplateDecl>(D);
4178 CXXConversionDecl *Conv;
4179 if (ConvTemplate)
4180 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4181 else
4182 Conv = cast<CXXConversionDecl>(D);
4183
4184 // If this is an explicit conversion, and we're not allowed to consider
4185 // explicit conversions, skip it.
4186 if (!AllowExplicit && Conv->isExplicit())
4187 continue;
4188
4189 if (AllowRvalues) {
4190 bool DerivedToBase = false;
4191 bool ObjCConversion = false;
4192 bool ObjCLifetimeConversion = false;
4193
4194 // If we are initializing an rvalue reference, don't permit conversion
4195 // functions that return lvalues.
4196 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4197 const ReferenceType *RefType
4198 = Conv->getConversionType()->getAs<LValueReferenceType>();
4199 if (RefType && !RefType->getPointeeType()->isFunctionType())
4200 continue;
4201 }
4202
4203 if (!ConvTemplate &&
4204 S.CompareReferenceRelationship(
4205 DeclLoc,
4206 Conv->getConversionType().getNonReferenceType()
4207 .getUnqualifiedType(),
4208 DeclType.getNonReferenceType().getUnqualifiedType(),
4209 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4210 Sema::Ref_Incompatible)
4211 continue;
4212 } else {
4213 // If the conversion function doesn't return a reference type,
4214 // it can't be considered for this conversion. An rvalue reference
4215 // is only acceptable if its referencee is a function type.
4216
4217 const ReferenceType *RefType =
4218 Conv->getConversionType()->getAs<ReferenceType>();
4219 if (!RefType ||
4220 (!RefType->isLValueReferenceType() &&
4221 !RefType->getPointeeType()->isFunctionType()))
4222 continue;
4223 }
4224
4225 if (ConvTemplate)
4226 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4227 Init, DeclType, CandidateSet,
4228 /*AllowObjCConversionOnExplicit=*/false);
4229 else
4230 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4231 DeclType, CandidateSet,
4232 /*AllowObjCConversionOnExplicit=*/false);
4233 }
4234
4235 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4236
4237 OverloadCandidateSet::iterator Best;
4238 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4239 case OR_Success:
4240 // C++ [over.ics.ref]p1:
4241 //
4242 // [...] If the parameter binds directly to the result of
4243 // applying a conversion function to the argument
4244 // expression, the implicit conversion sequence is a
4245 // user-defined conversion sequence (13.3.3.1.2), with the
4246 // second standard conversion sequence either an identity
4247 // conversion or, if the conversion function returns an
4248 // entity of a type that is a derived class of the parameter
4249 // type, a derived-to-base Conversion.
4250 if (!Best->FinalConversion.DirectBinding)
4251 return false;
4252
4253 ICS.setUserDefined();
4254 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4255 ICS.UserDefined.After = Best->FinalConversion;
4256 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4257 ICS.UserDefined.ConversionFunction = Best->Function;
4258 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4259 ICS.UserDefined.EllipsisConversion = false;
4260 assert(ICS.UserDefined.After.ReferenceBinding &&
4261 ICS.UserDefined.After.DirectBinding &&
4262 "Expected a direct reference binding!");
4263 return true;
4264
4265 case OR_Ambiguous:
4266 ICS.setAmbiguous();
4267 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4268 Cand != CandidateSet.end(); ++Cand)
4269 if (Cand->Viable)
4270 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4271 return true;
4272
4273 case OR_No_Viable_Function:
4274 case OR_Deleted:
4275 // There was no suitable conversion, or we found a deleted
4276 // conversion; continue with other checks.
4277 return false;
4278 }
4279
4280 llvm_unreachable("Invalid OverloadResult!");
4281 }
4282
4283 /// \brief Compute an implicit conversion sequence for reference
4284 /// initialization.
4285 static ImplicitConversionSequence
TryReferenceInit(Sema & S,Expr * Init,QualType DeclType,SourceLocation DeclLoc,bool SuppressUserConversions,bool AllowExplicit)4286 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4287 SourceLocation DeclLoc,
4288 bool SuppressUserConversions,
4289 bool AllowExplicit) {
4290 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4291
4292 // Most paths end in a failed conversion.
4293 ImplicitConversionSequence ICS;
4294 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4295
4296 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4297 QualType T2 = Init->getType();
4298
4299 // If the initializer is the address of an overloaded function, try
4300 // to resolve the overloaded function. If all goes well, T2 is the
4301 // type of the resulting function.
4302 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4303 DeclAccessPair Found;
4304 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4305 false, Found))
4306 T2 = Fn->getType();
4307 }
4308
4309 // Compute some basic properties of the types and the initializer.
4310 bool isRValRef = DeclType->isRValueReferenceType();
4311 bool DerivedToBase = false;
4312 bool ObjCConversion = false;
4313 bool ObjCLifetimeConversion = false;
4314 Expr::Classification InitCategory = Init->Classify(S.Context);
4315 Sema::ReferenceCompareResult RefRelationship
4316 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4317 ObjCConversion, ObjCLifetimeConversion);
4318
4319
4320 // C++0x [dcl.init.ref]p5:
4321 // A reference to type "cv1 T1" is initialized by an expression
4322 // of type "cv2 T2" as follows:
4323
4324 // -- If reference is an lvalue reference and the initializer expression
4325 if (!isRValRef) {
4326 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4327 // reference-compatible with "cv2 T2," or
4328 //
4329 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4330 if (InitCategory.isLValue() &&
4331 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4332 // C++ [over.ics.ref]p1:
4333 // When a parameter of reference type binds directly (8.5.3)
4334 // to an argument expression, the implicit conversion sequence
4335 // is the identity conversion, unless the argument expression
4336 // has a type that is a derived class of the parameter type,
4337 // in which case the implicit conversion sequence is a
4338 // derived-to-base Conversion (13.3.3.1).
4339 ICS.setStandard();
4340 ICS.Standard.First = ICK_Identity;
4341 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4342 : ObjCConversion? ICK_Compatible_Conversion
4343 : ICK_Identity;
4344 ICS.Standard.Third = ICK_Identity;
4345 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4346 ICS.Standard.setToType(0, T2);
4347 ICS.Standard.setToType(1, T1);
4348 ICS.Standard.setToType(2, T1);
4349 ICS.Standard.ReferenceBinding = true;
4350 ICS.Standard.DirectBinding = true;
4351 ICS.Standard.IsLvalueReference = !isRValRef;
4352 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4353 ICS.Standard.BindsToRvalue = false;
4354 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4355 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4356 ICS.Standard.CopyConstructor = nullptr;
4357 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4358
4359 // Nothing more to do: the inaccessibility/ambiguity check for
4360 // derived-to-base conversions is suppressed when we're
4361 // computing the implicit conversion sequence (C++
4362 // [over.best.ics]p2).
4363 return ICS;
4364 }
4365
4366 // -- has a class type (i.e., T2 is a class type), where T1 is
4367 // not reference-related to T2, and can be implicitly
4368 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4369 // is reference-compatible with "cv3 T3" 92) (this
4370 // conversion is selected by enumerating the applicable
4371 // conversion functions (13.3.1.6) and choosing the best
4372 // one through overload resolution (13.3)),
4373 if (!SuppressUserConversions && T2->isRecordType() &&
4374 S.isCompleteType(DeclLoc, T2) &&
4375 RefRelationship == Sema::Ref_Incompatible) {
4376 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4377 Init, T2, /*AllowRvalues=*/false,
4378 AllowExplicit))
4379 return ICS;
4380 }
4381 }
4382
4383 // -- Otherwise, the reference shall be an lvalue reference to a
4384 // non-volatile const type (i.e., cv1 shall be const), or the reference
4385 // shall be an rvalue reference.
4386 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4387 return ICS;
4388
4389 // -- If the initializer expression
4390 //
4391 // -- is an xvalue, class prvalue, array prvalue or function
4392 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4393 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4394 (InitCategory.isXValue() ||
4395 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4396 (InitCategory.isLValue() && T2->isFunctionType()))) {
4397 ICS.setStandard();
4398 ICS.Standard.First = ICK_Identity;
4399 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4400 : ObjCConversion? ICK_Compatible_Conversion
4401 : ICK_Identity;
4402 ICS.Standard.Third = ICK_Identity;
4403 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4404 ICS.Standard.setToType(0, T2);
4405 ICS.Standard.setToType(1, T1);
4406 ICS.Standard.setToType(2, T1);
4407 ICS.Standard.ReferenceBinding = true;
4408 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4409 // binding unless we're binding to a class prvalue.
4410 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4411 // allow the use of rvalue references in C++98/03 for the benefit of
4412 // standard library implementors; therefore, we need the xvalue check here.
4413 ICS.Standard.DirectBinding =
4414 S.getLangOpts().CPlusPlus11 ||
4415 !(InitCategory.isPRValue() || T2->isRecordType());
4416 ICS.Standard.IsLvalueReference = !isRValRef;
4417 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4418 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4419 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4420 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4421 ICS.Standard.CopyConstructor = nullptr;
4422 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4423 return ICS;
4424 }
4425
4426 // -- has a class type (i.e., T2 is a class type), where T1 is not
4427 // reference-related to T2, and can be implicitly converted to
4428 // an xvalue, class prvalue, or function lvalue of type
4429 // "cv3 T3", where "cv1 T1" is reference-compatible with
4430 // "cv3 T3",
4431 //
4432 // then the reference is bound to the value of the initializer
4433 // expression in the first case and to the result of the conversion
4434 // in the second case (or, in either case, to an appropriate base
4435 // class subobject).
4436 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4437 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4438 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4439 Init, T2, /*AllowRvalues=*/true,
4440 AllowExplicit)) {
4441 // In the second case, if the reference is an rvalue reference
4442 // and the second standard conversion sequence of the
4443 // user-defined conversion sequence includes an lvalue-to-rvalue
4444 // conversion, the program is ill-formed.
4445 if (ICS.isUserDefined() && isRValRef &&
4446 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4447 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4448
4449 return ICS;
4450 }
4451
4452 // A temporary of function type cannot be created; don't even try.
4453 if (T1->isFunctionType())
4454 return ICS;
4455
4456 // -- Otherwise, a temporary of type "cv1 T1" is created and
4457 // initialized from the initializer expression using the
4458 // rules for a non-reference copy initialization (8.5). The
4459 // reference is then bound to the temporary. If T1 is
4460 // reference-related to T2, cv1 must be the same
4461 // cv-qualification as, or greater cv-qualification than,
4462 // cv2; otherwise, the program is ill-formed.
4463 if (RefRelationship == Sema::Ref_Related) {
4464 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4465 // we would be reference-compatible or reference-compatible with
4466 // added qualification. But that wasn't the case, so the reference
4467 // initialization fails.
4468 //
4469 // Note that we only want to check address spaces and cvr-qualifiers here.
4470 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4471 Qualifiers T1Quals = T1.getQualifiers();
4472 Qualifiers T2Quals = T2.getQualifiers();
4473 T1Quals.removeObjCGCAttr();
4474 T1Quals.removeObjCLifetime();
4475 T2Quals.removeObjCGCAttr();
4476 T2Quals.removeObjCLifetime();
4477 // MS compiler ignores __unaligned qualifier for references; do the same.
4478 T1Quals.removeUnaligned();
4479 T2Quals.removeUnaligned();
4480 if (!T1Quals.compatiblyIncludes(T2Quals))
4481 return ICS;
4482 }
4483
4484 // If at least one of the types is a class type, the types are not
4485 // related, and we aren't allowed any user conversions, the
4486 // reference binding fails. This case is important for breaking
4487 // recursion, since TryImplicitConversion below will attempt to
4488 // create a temporary through the use of a copy constructor.
4489 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4490 (T1->isRecordType() || T2->isRecordType()))
4491 return ICS;
4492
4493 // If T1 is reference-related to T2 and the reference is an rvalue
4494 // reference, the initializer expression shall not be an lvalue.
4495 if (RefRelationship >= Sema::Ref_Related &&
4496 isRValRef && Init->Classify(S.Context).isLValue())
4497 return ICS;
4498
4499 // C++ [over.ics.ref]p2:
4500 // When a parameter of reference type is not bound directly to
4501 // an argument expression, the conversion sequence is the one
4502 // required to convert the argument expression to the
4503 // underlying type of the reference according to
4504 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4505 // to copy-initializing a temporary of the underlying type with
4506 // the argument expression. Any difference in top-level
4507 // cv-qualification is subsumed by the initialization itself
4508 // and does not constitute a conversion.
4509 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4510 /*AllowExplicit=*/false,
4511 /*InOverloadResolution=*/false,
4512 /*CStyle=*/false,
4513 /*AllowObjCWritebackConversion=*/false,
4514 /*AllowObjCConversionOnExplicit=*/false);
4515
4516 // Of course, that's still a reference binding.
4517 if (ICS.isStandard()) {
4518 ICS.Standard.ReferenceBinding = true;
4519 ICS.Standard.IsLvalueReference = !isRValRef;
4520 ICS.Standard.BindsToFunctionLvalue = false;
4521 ICS.Standard.BindsToRvalue = true;
4522 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4523 ICS.Standard.ObjCLifetimeConversionBinding = false;
4524 } else if (ICS.isUserDefined()) {
4525 const ReferenceType *LValRefType =
4526 ICS.UserDefined.ConversionFunction->getReturnType()
4527 ->getAs<LValueReferenceType>();
4528
4529 // C++ [over.ics.ref]p3:
4530 // Except for an implicit object parameter, for which see 13.3.1, a
4531 // standard conversion sequence cannot be formed if it requires [...]
4532 // binding an rvalue reference to an lvalue other than a function
4533 // lvalue.
4534 // Note that the function case is not possible here.
4535 if (DeclType->isRValueReferenceType() && LValRefType) {
4536 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4537 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4538 // reference to an rvalue!
4539 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4540 return ICS;
4541 }
4542
4543 ICS.UserDefined.Before.setAsIdentityConversion();
4544 ICS.UserDefined.After.ReferenceBinding = true;
4545 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4546 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4547 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4548 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4549 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4550 }
4551
4552 return ICS;
4553 }
4554
4555 static ImplicitConversionSequence
4556 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4557 bool SuppressUserConversions,
4558 bool InOverloadResolution,
4559 bool AllowObjCWritebackConversion,
4560 bool AllowExplicit = false);
4561
4562 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4563 /// initializer list From.
4564 static ImplicitConversionSequence
TryListConversion(Sema & S,InitListExpr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion)4565 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4566 bool SuppressUserConversions,
4567 bool InOverloadResolution,
4568 bool AllowObjCWritebackConversion) {
4569 // C++11 [over.ics.list]p1:
4570 // When an argument is an initializer list, it is not an expression and
4571 // special rules apply for converting it to a parameter type.
4572
4573 ImplicitConversionSequence Result;
4574 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4575
4576 // We need a complete type for what follows. Incomplete types can never be
4577 // initialized from init lists.
4578 if (!S.isCompleteType(From->getLocStart(), ToType))
4579 return Result;
4580
4581 // Per DR1467:
4582 // If the parameter type is a class X and the initializer list has a single
4583 // element of type cv U, where U is X or a class derived from X, the
4584 // implicit conversion sequence is the one required to convert the element
4585 // to the parameter type.
4586 //
4587 // Otherwise, if the parameter type is a character array [... ]
4588 // and the initializer list has a single element that is an
4589 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4590 // implicit conversion sequence is the identity conversion.
4591 if (From->getNumInits() == 1) {
4592 if (ToType->isRecordType()) {
4593 QualType InitType = From->getInit(0)->getType();
4594 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4595 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4596 return TryCopyInitialization(S, From->getInit(0), ToType,
4597 SuppressUserConversions,
4598 InOverloadResolution,
4599 AllowObjCWritebackConversion);
4600 }
4601 // FIXME: Check the other conditions here: array of character type,
4602 // initializer is a string literal.
4603 if (ToType->isArrayType()) {
4604 InitializedEntity Entity =
4605 InitializedEntity::InitializeParameter(S.Context, ToType,
4606 /*Consumed=*/false);
4607 if (S.CanPerformCopyInitialization(Entity, From)) {
4608 Result.setStandard();
4609 Result.Standard.setAsIdentityConversion();
4610 Result.Standard.setFromType(ToType);
4611 Result.Standard.setAllToTypes(ToType);
4612 return Result;
4613 }
4614 }
4615 }
4616
4617 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4618 // C++11 [over.ics.list]p2:
4619 // If the parameter type is std::initializer_list<X> or "array of X" and
4620 // all the elements can be implicitly converted to X, the implicit
4621 // conversion sequence is the worst conversion necessary to convert an
4622 // element of the list to X.
4623 //
4624 // C++14 [over.ics.list]p3:
4625 // Otherwise, if the parameter type is "array of N X", if the initializer
4626 // list has exactly N elements or if it has fewer than N elements and X is
4627 // default-constructible, and if all the elements of the initializer list
4628 // can be implicitly converted to X, the implicit conversion sequence is
4629 // the worst conversion necessary to convert an element of the list to X.
4630 //
4631 // FIXME: We're missing a lot of these checks.
4632 bool toStdInitializerList = false;
4633 QualType X;
4634 if (ToType->isArrayType())
4635 X = S.Context.getAsArrayType(ToType)->getElementType();
4636 else
4637 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4638 if (!X.isNull()) {
4639 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4640 Expr *Init = From->getInit(i);
4641 ImplicitConversionSequence ICS =
4642 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4643 InOverloadResolution,
4644 AllowObjCWritebackConversion);
4645 // If a single element isn't convertible, fail.
4646 if (ICS.isBad()) {
4647 Result = ICS;
4648 break;
4649 }
4650 // Otherwise, look for the worst conversion.
4651 if (Result.isBad() ||
4652 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4653 Result) ==
4654 ImplicitConversionSequence::Worse)
4655 Result = ICS;
4656 }
4657
4658 // For an empty list, we won't have computed any conversion sequence.
4659 // Introduce the identity conversion sequence.
4660 if (From->getNumInits() == 0) {
4661 Result.setStandard();
4662 Result.Standard.setAsIdentityConversion();
4663 Result.Standard.setFromType(ToType);
4664 Result.Standard.setAllToTypes(ToType);
4665 }
4666
4667 Result.setStdInitializerListElement(toStdInitializerList);
4668 return Result;
4669 }
4670
4671 // C++14 [over.ics.list]p4:
4672 // C++11 [over.ics.list]p3:
4673 // Otherwise, if the parameter is a non-aggregate class X and overload
4674 // resolution chooses a single best constructor [...] the implicit
4675 // conversion sequence is a user-defined conversion sequence. If multiple
4676 // constructors are viable but none is better than the others, the
4677 // implicit conversion sequence is a user-defined conversion sequence.
4678 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4679 // This function can deal with initializer lists.
4680 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4681 /*AllowExplicit=*/false,
4682 InOverloadResolution, /*CStyle=*/false,
4683 AllowObjCWritebackConversion,
4684 /*AllowObjCConversionOnExplicit=*/false);
4685 }
4686
4687 // C++14 [over.ics.list]p5:
4688 // C++11 [over.ics.list]p4:
4689 // Otherwise, if the parameter has an aggregate type which can be
4690 // initialized from the initializer list [...] the implicit conversion
4691 // sequence is a user-defined conversion sequence.
4692 if (ToType->isAggregateType()) {
4693 // Type is an aggregate, argument is an init list. At this point it comes
4694 // down to checking whether the initialization works.
4695 // FIXME: Find out whether this parameter is consumed or not.
4696 InitializedEntity Entity =
4697 InitializedEntity::InitializeParameter(S.Context, ToType,
4698 /*Consumed=*/false);
4699 if (S.CanPerformCopyInitialization(Entity, From)) {
4700 Result.setUserDefined();
4701 Result.UserDefined.Before.setAsIdentityConversion();
4702 // Initializer lists don't have a type.
4703 Result.UserDefined.Before.setFromType(QualType());
4704 Result.UserDefined.Before.setAllToTypes(QualType());
4705
4706 Result.UserDefined.After.setAsIdentityConversion();
4707 Result.UserDefined.After.setFromType(ToType);
4708 Result.UserDefined.After.setAllToTypes(ToType);
4709 Result.UserDefined.ConversionFunction = nullptr;
4710 }
4711 return Result;
4712 }
4713
4714 // C++14 [over.ics.list]p6:
4715 // C++11 [over.ics.list]p5:
4716 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4717 if (ToType->isReferenceType()) {
4718 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4719 // mention initializer lists in any way. So we go by what list-
4720 // initialization would do and try to extrapolate from that.
4721
4722 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4723
4724 // If the initializer list has a single element that is reference-related
4725 // to the parameter type, we initialize the reference from that.
4726 if (From->getNumInits() == 1) {
4727 Expr *Init = From->getInit(0);
4728
4729 QualType T2 = Init->getType();
4730
4731 // If the initializer is the address of an overloaded function, try
4732 // to resolve the overloaded function. If all goes well, T2 is the
4733 // type of the resulting function.
4734 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4735 DeclAccessPair Found;
4736 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4737 Init, ToType, false, Found))
4738 T2 = Fn->getType();
4739 }
4740
4741 // Compute some basic properties of the types and the initializer.
4742 bool dummy1 = false;
4743 bool dummy2 = false;
4744 bool dummy3 = false;
4745 Sema::ReferenceCompareResult RefRelationship
4746 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4747 dummy2, dummy3);
4748
4749 if (RefRelationship >= Sema::Ref_Related) {
4750 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4751 SuppressUserConversions,
4752 /*AllowExplicit=*/false);
4753 }
4754 }
4755
4756 // Otherwise, we bind the reference to a temporary created from the
4757 // initializer list.
4758 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4759 InOverloadResolution,
4760 AllowObjCWritebackConversion);
4761 if (Result.isFailure())
4762 return Result;
4763 assert(!Result.isEllipsis() &&
4764 "Sub-initialization cannot result in ellipsis conversion.");
4765
4766 // Can we even bind to a temporary?
4767 if (ToType->isRValueReferenceType() ||
4768 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4769 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4770 Result.UserDefined.After;
4771 SCS.ReferenceBinding = true;
4772 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4773 SCS.BindsToRvalue = true;
4774 SCS.BindsToFunctionLvalue = false;
4775 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4776 SCS.ObjCLifetimeConversionBinding = false;
4777 } else
4778 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4779 From, ToType);
4780 return Result;
4781 }
4782
4783 // C++14 [over.ics.list]p7:
4784 // C++11 [over.ics.list]p6:
4785 // Otherwise, if the parameter type is not a class:
4786 if (!ToType->isRecordType()) {
4787 // - if the initializer list has one element that is not itself an
4788 // initializer list, the implicit conversion sequence is the one
4789 // required to convert the element to the parameter type.
4790 unsigned NumInits = From->getNumInits();
4791 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4792 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4793 SuppressUserConversions,
4794 InOverloadResolution,
4795 AllowObjCWritebackConversion);
4796 // - if the initializer list has no elements, the implicit conversion
4797 // sequence is the identity conversion.
4798 else if (NumInits == 0) {
4799 Result.setStandard();
4800 Result.Standard.setAsIdentityConversion();
4801 Result.Standard.setFromType(ToType);
4802 Result.Standard.setAllToTypes(ToType);
4803 }
4804 return Result;
4805 }
4806
4807 // C++14 [over.ics.list]p8:
4808 // C++11 [over.ics.list]p7:
4809 // In all cases other than those enumerated above, no conversion is possible
4810 return Result;
4811 }
4812
4813 /// TryCopyInitialization - Try to copy-initialize a value of type
4814 /// ToType from the expression From. Return the implicit conversion
4815 /// sequence required to pass this argument, which may be a bad
4816 /// conversion sequence (meaning that the argument cannot be passed to
4817 /// a parameter of this type). If @p SuppressUserConversions, then we
4818 /// do not permit any user-defined conversion sequences.
4819 static ImplicitConversionSequence
TryCopyInitialization(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion,bool AllowExplicit)4820 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4821 bool SuppressUserConversions,
4822 bool InOverloadResolution,
4823 bool AllowObjCWritebackConversion,
4824 bool AllowExplicit) {
4825 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4826 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4827 InOverloadResolution,AllowObjCWritebackConversion);
4828
4829 if (ToType->isReferenceType())
4830 return TryReferenceInit(S, From, ToType,
4831 /*FIXME:*/From->getLocStart(),
4832 SuppressUserConversions,
4833 AllowExplicit);
4834
4835 return TryImplicitConversion(S, From, ToType,
4836 SuppressUserConversions,
4837 /*AllowExplicit=*/false,
4838 InOverloadResolution,
4839 /*CStyle=*/false,
4840 AllowObjCWritebackConversion,
4841 /*AllowObjCConversionOnExplicit=*/false);
4842 }
4843
TryCopyInitialization(const CanQualType FromQTy,const CanQualType ToQTy,Sema & S,SourceLocation Loc,ExprValueKind FromVK)4844 static bool TryCopyInitialization(const CanQualType FromQTy,
4845 const CanQualType ToQTy,
4846 Sema &S,
4847 SourceLocation Loc,
4848 ExprValueKind FromVK) {
4849 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4850 ImplicitConversionSequence ICS =
4851 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4852
4853 return !ICS.isBad();
4854 }
4855
4856 /// TryObjectArgumentInitialization - Try to initialize the object
4857 /// parameter of the given member function (@c Method) from the
4858 /// expression @p From.
4859 static ImplicitConversionSequence
TryObjectArgumentInitialization(Sema & S,SourceLocation Loc,QualType FromType,Expr::Classification FromClassification,CXXMethodDecl * Method,CXXRecordDecl * ActingContext)4860 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4861 Expr::Classification FromClassification,
4862 CXXMethodDecl *Method,
4863 CXXRecordDecl *ActingContext) {
4864 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4865 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4866 // const volatile object.
4867 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4868 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4869 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4870
4871 // Set up the conversion sequence as a "bad" conversion, to allow us
4872 // to exit early.
4873 ImplicitConversionSequence ICS;
4874
4875 // We need to have an object of class type.
4876 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4877 FromType = PT->getPointeeType();
4878
4879 // When we had a pointer, it's implicitly dereferenced, so we
4880 // better have an lvalue.
4881 assert(FromClassification.isLValue());
4882 }
4883
4884 assert(FromType->isRecordType());
4885
4886 // C++0x [over.match.funcs]p4:
4887 // For non-static member functions, the type of the implicit object
4888 // parameter is
4889 //
4890 // - "lvalue reference to cv X" for functions declared without a
4891 // ref-qualifier or with the & ref-qualifier
4892 // - "rvalue reference to cv X" for functions declared with the &&
4893 // ref-qualifier
4894 //
4895 // where X is the class of which the function is a member and cv is the
4896 // cv-qualification on the member function declaration.
4897 //
4898 // However, when finding an implicit conversion sequence for the argument, we
4899 // are not allowed to create temporaries or perform user-defined conversions
4900 // (C++ [over.match.funcs]p5). We perform a simplified version of
4901 // reference binding here, that allows class rvalues to bind to
4902 // non-constant references.
4903
4904 // First check the qualifiers.
4905 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4906 if (ImplicitParamType.getCVRQualifiers()
4907 != FromTypeCanon.getLocalCVRQualifiers() &&
4908 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4909 ICS.setBad(BadConversionSequence::bad_qualifiers,
4910 FromType, ImplicitParamType);
4911 return ICS;
4912 }
4913
4914 // Check that we have either the same type or a derived type. It
4915 // affects the conversion rank.
4916 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4917 ImplicitConversionKind SecondKind;
4918 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4919 SecondKind = ICK_Identity;
4920 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
4921 SecondKind = ICK_Derived_To_Base;
4922 else {
4923 ICS.setBad(BadConversionSequence::unrelated_class,
4924 FromType, ImplicitParamType);
4925 return ICS;
4926 }
4927
4928 // Check the ref-qualifier.
4929 switch (Method->getRefQualifier()) {
4930 case RQ_None:
4931 // Do nothing; we don't care about lvalueness or rvalueness.
4932 break;
4933
4934 case RQ_LValue:
4935 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4936 // non-const lvalue reference cannot bind to an rvalue
4937 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4938 ImplicitParamType);
4939 return ICS;
4940 }
4941 break;
4942
4943 case RQ_RValue:
4944 if (!FromClassification.isRValue()) {
4945 // rvalue reference cannot bind to an lvalue
4946 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4947 ImplicitParamType);
4948 return ICS;
4949 }
4950 break;
4951 }
4952
4953 // Success. Mark this as a reference binding.
4954 ICS.setStandard();
4955 ICS.Standard.setAsIdentityConversion();
4956 ICS.Standard.Second = SecondKind;
4957 ICS.Standard.setFromType(FromType);
4958 ICS.Standard.setAllToTypes(ImplicitParamType);
4959 ICS.Standard.ReferenceBinding = true;
4960 ICS.Standard.DirectBinding = true;
4961 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4962 ICS.Standard.BindsToFunctionLvalue = false;
4963 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4964 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4965 = (Method->getRefQualifier() == RQ_None);
4966 return ICS;
4967 }
4968
4969 /// PerformObjectArgumentInitialization - Perform initialization of
4970 /// the implicit object parameter for the given Method with the given
4971 /// expression.
4972 ExprResult
PerformObjectArgumentInitialization(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,CXXMethodDecl * Method)4973 Sema::PerformObjectArgumentInitialization(Expr *From,
4974 NestedNameSpecifier *Qualifier,
4975 NamedDecl *FoundDecl,
4976 CXXMethodDecl *Method) {
4977 QualType FromRecordType, DestType;
4978 QualType ImplicitParamRecordType =
4979 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4980
4981 Expr::Classification FromClassification;
4982 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4983 FromRecordType = PT->getPointeeType();
4984 DestType = Method->getThisType(Context);
4985 FromClassification = Expr::Classification::makeSimpleLValue();
4986 } else {
4987 FromRecordType = From->getType();
4988 DestType = ImplicitParamRecordType;
4989 FromClassification = From->Classify(Context);
4990 }
4991
4992 // Note that we always use the true parent context when performing
4993 // the actual argument initialization.
4994 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4995 *this, From->getLocStart(), From->getType(), FromClassification, Method,
4996 Method->getParent());
4997 if (ICS.isBad()) {
4998 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4999 Qualifiers FromQs = FromRecordType.getQualifiers();
5000 Qualifiers ToQs = DestType.getQualifiers();
5001 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5002 if (CVR) {
5003 Diag(From->getLocStart(),
5004 diag::err_member_function_call_bad_cvr)
5005 << Method->getDeclName() << FromRecordType << (CVR - 1)
5006 << From->getSourceRange();
5007 Diag(Method->getLocation(), diag::note_previous_decl)
5008 << Method->getDeclName();
5009 return ExprError();
5010 }
5011 }
5012
5013 return Diag(From->getLocStart(),
5014 diag::err_implicit_object_parameter_init)
5015 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5016 }
5017
5018 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5019 ExprResult FromRes =
5020 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5021 if (FromRes.isInvalid())
5022 return ExprError();
5023 From = FromRes.get();
5024 }
5025
5026 if (!Context.hasSameType(From->getType(), DestType))
5027 From = ImpCastExprToType(From, DestType, CK_NoOp,
5028 From->getValueKind()).get();
5029 return From;
5030 }
5031
5032 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5033 /// expression From to bool (C++0x [conv]p3).
5034 static ImplicitConversionSequence
TryContextuallyConvertToBool(Sema & S,Expr * From)5035 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5036 return TryImplicitConversion(S, From, S.Context.BoolTy,
5037 /*SuppressUserConversions=*/false,
5038 /*AllowExplicit=*/true,
5039 /*InOverloadResolution=*/false,
5040 /*CStyle=*/false,
5041 /*AllowObjCWritebackConversion=*/false,
5042 /*AllowObjCConversionOnExplicit=*/false);
5043 }
5044
5045 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5046 /// of the expression From to bool (C++0x [conv]p3).
PerformContextuallyConvertToBool(Expr * From)5047 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5048 if (checkPlaceholderForOverload(*this, From))
5049 return ExprError();
5050
5051 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5052 if (!ICS.isBad())
5053 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5054
5055 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5056 return Diag(From->getLocStart(),
5057 diag::err_typecheck_bool_condition)
5058 << From->getType() << From->getSourceRange();
5059 return ExprError();
5060 }
5061
5062 /// Check that the specified conversion is permitted in a converted constant
5063 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5064 /// is acceptable.
CheckConvertedConstantConversions(Sema & S,StandardConversionSequence & SCS)5065 static bool CheckConvertedConstantConversions(Sema &S,
5066 StandardConversionSequence &SCS) {
5067 // Since we know that the target type is an integral or unscoped enumeration
5068 // type, most conversion kinds are impossible. All possible First and Third
5069 // conversions are fine.
5070 switch (SCS.Second) {
5071 case ICK_Identity:
5072 case ICK_NoReturn_Adjustment:
5073 case ICK_Integral_Promotion:
5074 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5075 return true;
5076
5077 case ICK_Boolean_Conversion:
5078 // Conversion from an integral or unscoped enumeration type to bool is
5079 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5080 // conversion, so we allow it in a converted constant expression.
5081 //
5082 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5083 // a lot of popular code. We should at least add a warning for this
5084 // (non-conforming) extension.
5085 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5086 SCS.getToType(2)->isBooleanType();
5087
5088 case ICK_Pointer_Conversion:
5089 case ICK_Pointer_Member:
5090 // C++1z: null pointer conversions and null member pointer conversions are
5091 // only permitted if the source type is std::nullptr_t.
5092 return SCS.getFromType()->isNullPtrType();
5093
5094 case ICK_Floating_Promotion:
5095 case ICK_Complex_Promotion:
5096 case ICK_Floating_Conversion:
5097 case ICK_Complex_Conversion:
5098 case ICK_Floating_Integral:
5099 case ICK_Compatible_Conversion:
5100 case ICK_Derived_To_Base:
5101 case ICK_Vector_Conversion:
5102 case ICK_Vector_Splat:
5103 case ICK_Complex_Real:
5104 case ICK_Block_Pointer_Conversion:
5105 case ICK_TransparentUnionConversion:
5106 case ICK_Writeback_Conversion:
5107 case ICK_Zero_Event_Conversion:
5108 case ICK_C_Only_Conversion:
5109 return false;
5110
5111 case ICK_Lvalue_To_Rvalue:
5112 case ICK_Array_To_Pointer:
5113 case ICK_Function_To_Pointer:
5114 llvm_unreachable("found a first conversion kind in Second");
5115
5116 case ICK_Qualification:
5117 llvm_unreachable("found a third conversion kind in Second");
5118
5119 case ICK_Num_Conversion_Kinds:
5120 break;
5121 }
5122
5123 llvm_unreachable("unknown conversion kind");
5124 }
5125
5126 /// CheckConvertedConstantExpression - Check that the expression From is a
5127 /// converted constant expression of type T, perform the conversion and produce
5128 /// the converted expression, per C++11 [expr.const]p3.
CheckConvertedConstantExpression(Sema & S,Expr * From,QualType T,APValue & Value,Sema::CCEKind CCE,bool RequireInt)5129 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5130 QualType T, APValue &Value,
5131 Sema::CCEKind CCE,
5132 bool RequireInt) {
5133 assert(S.getLangOpts().CPlusPlus11 &&
5134 "converted constant expression outside C++11");
5135
5136 if (checkPlaceholderForOverload(S, From))
5137 return ExprError();
5138
5139 // C++1z [expr.const]p3:
5140 // A converted constant expression of type T is an expression,
5141 // implicitly converted to type T, where the converted
5142 // expression is a constant expression and the implicit conversion
5143 // sequence contains only [... list of conversions ...].
5144 ImplicitConversionSequence ICS =
5145 TryCopyInitialization(S, From, T,
5146 /*SuppressUserConversions=*/false,
5147 /*InOverloadResolution=*/false,
5148 /*AllowObjcWritebackConversion=*/false,
5149 /*AllowExplicit=*/false);
5150 StandardConversionSequence *SCS = nullptr;
5151 switch (ICS.getKind()) {
5152 case ImplicitConversionSequence::StandardConversion:
5153 SCS = &ICS.Standard;
5154 break;
5155 case ImplicitConversionSequence::UserDefinedConversion:
5156 // We are converting to a non-class type, so the Before sequence
5157 // must be trivial.
5158 SCS = &ICS.UserDefined.After;
5159 break;
5160 case ImplicitConversionSequence::AmbiguousConversion:
5161 case ImplicitConversionSequence::BadConversion:
5162 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5163 return S.Diag(From->getLocStart(),
5164 diag::err_typecheck_converted_constant_expression)
5165 << From->getType() << From->getSourceRange() << T;
5166 return ExprError();
5167
5168 case ImplicitConversionSequence::EllipsisConversion:
5169 llvm_unreachable("ellipsis conversion in converted constant expression");
5170 }
5171
5172 // Check that we would only use permitted conversions.
5173 if (!CheckConvertedConstantConversions(S, *SCS)) {
5174 return S.Diag(From->getLocStart(),
5175 diag::err_typecheck_converted_constant_expression_disallowed)
5176 << From->getType() << From->getSourceRange() << T;
5177 }
5178 // [...] and where the reference binding (if any) binds directly.
5179 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5180 return S.Diag(From->getLocStart(),
5181 diag::err_typecheck_converted_constant_expression_indirect)
5182 << From->getType() << From->getSourceRange() << T;
5183 }
5184
5185 ExprResult Result =
5186 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5187 if (Result.isInvalid())
5188 return Result;
5189
5190 // Check for a narrowing implicit conversion.
5191 APValue PreNarrowingValue;
5192 QualType PreNarrowingType;
5193 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5194 PreNarrowingType)) {
5195 case NK_Variable_Narrowing:
5196 // Implicit conversion to a narrower type, and the value is not a constant
5197 // expression. We'll diagnose this in a moment.
5198 case NK_Not_Narrowing:
5199 break;
5200
5201 case NK_Constant_Narrowing:
5202 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5203 << CCE << /*Constant*/1
5204 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5205 break;
5206
5207 case NK_Type_Narrowing:
5208 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5209 << CCE << /*Constant*/0 << From->getType() << T;
5210 break;
5211 }
5212
5213 // Check the expression is a constant expression.
5214 SmallVector<PartialDiagnosticAt, 8> Notes;
5215 Expr::EvalResult Eval;
5216 Eval.Diag = &Notes;
5217
5218 if ((T->isReferenceType()
5219 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5220 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5221 (RequireInt && !Eval.Val.isInt())) {
5222 // The expression can't be folded, so we can't keep it at this position in
5223 // the AST.
5224 Result = ExprError();
5225 } else {
5226 Value = Eval.Val;
5227
5228 if (Notes.empty()) {
5229 // It's a constant expression.
5230 return Result;
5231 }
5232 }
5233
5234 // It's not a constant expression. Produce an appropriate diagnostic.
5235 if (Notes.size() == 1 &&
5236 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5237 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5238 else {
5239 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5240 << CCE << From->getSourceRange();
5241 for (unsigned I = 0; I < Notes.size(); ++I)
5242 S.Diag(Notes[I].first, Notes[I].second);
5243 }
5244 return ExprError();
5245 }
5246
CheckConvertedConstantExpression(Expr * From,QualType T,APValue & Value,CCEKind CCE)5247 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5248 APValue &Value, CCEKind CCE) {
5249 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5250 }
5251
CheckConvertedConstantExpression(Expr * From,QualType T,llvm::APSInt & Value,CCEKind CCE)5252 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5253 llvm::APSInt &Value,
5254 CCEKind CCE) {
5255 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5256
5257 APValue V;
5258 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5259 if (!R.isInvalid())
5260 Value = V.getInt();
5261 return R;
5262 }
5263
5264
5265 /// dropPointerConversions - If the given standard conversion sequence
5266 /// involves any pointer conversions, remove them. This may change
5267 /// the result type of the conversion sequence.
dropPointerConversion(StandardConversionSequence & SCS)5268 static void dropPointerConversion(StandardConversionSequence &SCS) {
5269 if (SCS.Second == ICK_Pointer_Conversion) {
5270 SCS.Second = ICK_Identity;
5271 SCS.Third = ICK_Identity;
5272 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5273 }
5274 }
5275
5276 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5277 /// convert the expression From to an Objective-C pointer type.
5278 static ImplicitConversionSequence
TryContextuallyConvertToObjCPointer(Sema & S,Expr * From)5279 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5280 // Do an implicit conversion to 'id'.
5281 QualType Ty = S.Context.getObjCIdType();
5282 ImplicitConversionSequence ICS
5283 = TryImplicitConversion(S, From, Ty,
5284 // FIXME: Are these flags correct?
5285 /*SuppressUserConversions=*/false,
5286 /*AllowExplicit=*/true,
5287 /*InOverloadResolution=*/false,
5288 /*CStyle=*/false,
5289 /*AllowObjCWritebackConversion=*/false,
5290 /*AllowObjCConversionOnExplicit=*/true);
5291
5292 // Strip off any final conversions to 'id'.
5293 switch (ICS.getKind()) {
5294 case ImplicitConversionSequence::BadConversion:
5295 case ImplicitConversionSequence::AmbiguousConversion:
5296 case ImplicitConversionSequence::EllipsisConversion:
5297 break;
5298
5299 case ImplicitConversionSequence::UserDefinedConversion:
5300 dropPointerConversion(ICS.UserDefined.After);
5301 break;
5302
5303 case ImplicitConversionSequence::StandardConversion:
5304 dropPointerConversion(ICS.Standard);
5305 break;
5306 }
5307
5308 return ICS;
5309 }
5310
5311 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5312 /// conversion of the expression From to an Objective-C pointer type.
PerformContextuallyConvertToObjCPointer(Expr * From)5313 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5314 if (checkPlaceholderForOverload(*this, From))
5315 return ExprError();
5316
5317 QualType Ty = Context.getObjCIdType();
5318 ImplicitConversionSequence ICS =
5319 TryContextuallyConvertToObjCPointer(*this, From);
5320 if (!ICS.isBad())
5321 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5322 return ExprError();
5323 }
5324
5325 /// Determine whether the provided type is an integral type, or an enumeration
5326 /// type of a permitted flavor.
match(QualType T)5327 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5328 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5329 : T->isIntegralOrUnscopedEnumerationType();
5330 }
5331
5332 static ExprResult
diagnoseAmbiguousConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter,QualType T,UnresolvedSetImpl & ViableConversions)5333 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5334 Sema::ContextualImplicitConverter &Converter,
5335 QualType T, UnresolvedSetImpl &ViableConversions) {
5336
5337 if (Converter.Suppress)
5338 return ExprError();
5339
5340 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5341 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5342 CXXConversionDecl *Conv =
5343 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5344 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5345 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5346 }
5347 return From;
5348 }
5349
5350 static bool
diagnoseNoViableConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,UnresolvedSetImpl & ExplicitConversions)5351 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5352 Sema::ContextualImplicitConverter &Converter,
5353 QualType T, bool HadMultipleCandidates,
5354 UnresolvedSetImpl &ExplicitConversions) {
5355 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5356 DeclAccessPair Found = ExplicitConversions[0];
5357 CXXConversionDecl *Conversion =
5358 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5359
5360 // The user probably meant to invoke the given explicit
5361 // conversion; use it.
5362 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5363 std::string TypeStr;
5364 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5365
5366 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5367 << FixItHint::CreateInsertion(From->getLocStart(),
5368 "static_cast<" + TypeStr + ">(")
5369 << FixItHint::CreateInsertion(
5370 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5371 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5372
5373 // If we aren't in a SFINAE context, build a call to the
5374 // explicit conversion function.
5375 if (SemaRef.isSFINAEContext())
5376 return true;
5377
5378 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5379 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5380 HadMultipleCandidates);
5381 if (Result.isInvalid())
5382 return true;
5383 // Record usage of conversion in an implicit cast.
5384 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5385 CK_UserDefinedConversion, Result.get(),
5386 nullptr, Result.get()->getValueKind());
5387 }
5388 return false;
5389 }
5390
recordConversion(Sema & SemaRef,SourceLocation Loc,Expr * & From,Sema::ContextualImplicitConverter & Converter,QualType T,bool HadMultipleCandidates,DeclAccessPair & Found)5391 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5392 Sema::ContextualImplicitConverter &Converter,
5393 QualType T, bool HadMultipleCandidates,
5394 DeclAccessPair &Found) {
5395 CXXConversionDecl *Conversion =
5396 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5397 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5398
5399 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5400 if (!Converter.SuppressConversion) {
5401 if (SemaRef.isSFINAEContext())
5402 return true;
5403
5404 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5405 << From->getSourceRange();
5406 }
5407
5408 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5409 HadMultipleCandidates);
5410 if (Result.isInvalid())
5411 return true;
5412 // Record usage of conversion in an implicit cast.
5413 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5414 CK_UserDefinedConversion, Result.get(),
5415 nullptr, Result.get()->getValueKind());
5416 return false;
5417 }
5418
finishContextualImplicitConversion(Sema & SemaRef,SourceLocation Loc,Expr * From,Sema::ContextualImplicitConverter & Converter)5419 static ExprResult finishContextualImplicitConversion(
5420 Sema &SemaRef, SourceLocation Loc, Expr *From,
5421 Sema::ContextualImplicitConverter &Converter) {
5422 if (!Converter.match(From->getType()) && !Converter.Suppress)
5423 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5424 << From->getSourceRange();
5425
5426 return SemaRef.DefaultLvalueConversion(From);
5427 }
5428
5429 static void
collectViableConversionCandidates(Sema & SemaRef,Expr * From,QualType ToType,UnresolvedSetImpl & ViableConversions,OverloadCandidateSet & CandidateSet)5430 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5431 UnresolvedSetImpl &ViableConversions,
5432 OverloadCandidateSet &CandidateSet) {
5433 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5434 DeclAccessPair FoundDecl = ViableConversions[I];
5435 NamedDecl *D = FoundDecl.getDecl();
5436 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5437 if (isa<UsingShadowDecl>(D))
5438 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5439
5440 CXXConversionDecl *Conv;
5441 FunctionTemplateDecl *ConvTemplate;
5442 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5443 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5444 else
5445 Conv = cast<CXXConversionDecl>(D);
5446
5447 if (ConvTemplate)
5448 SemaRef.AddTemplateConversionCandidate(
5449 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5450 /*AllowObjCConversionOnExplicit=*/false);
5451 else
5452 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5453 ToType, CandidateSet,
5454 /*AllowObjCConversionOnExplicit=*/false);
5455 }
5456 }
5457
5458 /// \brief Attempt to convert the given expression to a type which is accepted
5459 /// by the given converter.
5460 ///
5461 /// This routine will attempt to convert an expression of class type to a
5462 /// type accepted by the specified converter. In C++11 and before, the class
5463 /// must have a single non-explicit conversion function converting to a matching
5464 /// type. In C++1y, there can be multiple such conversion functions, but only
5465 /// one target type.
5466 ///
5467 /// \param Loc The source location of the construct that requires the
5468 /// conversion.
5469 ///
5470 /// \param From The expression we're converting from.
5471 ///
5472 /// \param Converter Used to control and diagnose the conversion process.
5473 ///
5474 /// \returns The expression, converted to an integral or enumeration type if
5475 /// successful.
PerformContextualImplicitConversion(SourceLocation Loc,Expr * From,ContextualImplicitConverter & Converter)5476 ExprResult Sema::PerformContextualImplicitConversion(
5477 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5478 // We can't perform any more checking for type-dependent expressions.
5479 if (From->isTypeDependent())
5480 return From;
5481
5482 // Process placeholders immediately.
5483 if (From->hasPlaceholderType()) {
5484 ExprResult result = CheckPlaceholderExpr(From);
5485 if (result.isInvalid())
5486 return result;
5487 From = result.get();
5488 }
5489
5490 // If the expression already has a matching type, we're golden.
5491 QualType T = From->getType();
5492 if (Converter.match(T))
5493 return DefaultLvalueConversion(From);
5494
5495 // FIXME: Check for missing '()' if T is a function type?
5496
5497 // We can only perform contextual implicit conversions on objects of class
5498 // type.
5499 const RecordType *RecordTy = T->getAs<RecordType>();
5500 if (!RecordTy || !getLangOpts().CPlusPlus) {
5501 if (!Converter.Suppress)
5502 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5503 return From;
5504 }
5505
5506 // We must have a complete class type.
5507 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5508 ContextualImplicitConverter &Converter;
5509 Expr *From;
5510
5511 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5512 : Converter(Converter), From(From) {}
5513
5514 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5515 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5516 }
5517 } IncompleteDiagnoser(Converter, From);
5518
5519 if (Converter.Suppress ? !isCompleteType(Loc, T)
5520 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5521 return From;
5522
5523 // Look for a conversion to an integral or enumeration type.
5524 UnresolvedSet<4>
5525 ViableConversions; // These are *potentially* viable in C++1y.
5526 UnresolvedSet<4> ExplicitConversions;
5527 const auto &Conversions =
5528 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5529
5530 bool HadMultipleCandidates =
5531 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5532
5533 // To check that there is only one target type, in C++1y:
5534 QualType ToType;
5535 bool HasUniqueTargetType = true;
5536
5537 // Collect explicit or viable (potentially in C++1y) conversions.
5538 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5539 NamedDecl *D = (*I)->getUnderlyingDecl();
5540 CXXConversionDecl *Conversion;
5541 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5542 if (ConvTemplate) {
5543 if (getLangOpts().CPlusPlus14)
5544 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5545 else
5546 continue; // C++11 does not consider conversion operator templates(?).
5547 } else
5548 Conversion = cast<CXXConversionDecl>(D);
5549
5550 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5551 "Conversion operator templates are considered potentially "
5552 "viable in C++1y");
5553
5554 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5555 if (Converter.match(CurToType) || ConvTemplate) {
5556
5557 if (Conversion->isExplicit()) {
5558 // FIXME: For C++1y, do we need this restriction?
5559 // cf. diagnoseNoViableConversion()
5560 if (!ConvTemplate)
5561 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5562 } else {
5563 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5564 if (ToType.isNull())
5565 ToType = CurToType.getUnqualifiedType();
5566 else if (HasUniqueTargetType &&
5567 (CurToType.getUnqualifiedType() != ToType))
5568 HasUniqueTargetType = false;
5569 }
5570 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5571 }
5572 }
5573 }
5574
5575 if (getLangOpts().CPlusPlus14) {
5576 // C++1y [conv]p6:
5577 // ... An expression e of class type E appearing in such a context
5578 // is said to be contextually implicitly converted to a specified
5579 // type T and is well-formed if and only if e can be implicitly
5580 // converted to a type T that is determined as follows: E is searched
5581 // for conversion functions whose return type is cv T or reference to
5582 // cv T such that T is allowed by the context. There shall be
5583 // exactly one such T.
5584
5585 // If no unique T is found:
5586 if (ToType.isNull()) {
5587 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5588 HadMultipleCandidates,
5589 ExplicitConversions))
5590 return ExprError();
5591 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5592 }
5593
5594 // If more than one unique Ts are found:
5595 if (!HasUniqueTargetType)
5596 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5597 ViableConversions);
5598
5599 // If one unique T is found:
5600 // First, build a candidate set from the previously recorded
5601 // potentially viable conversions.
5602 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5603 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5604 CandidateSet);
5605
5606 // Then, perform overload resolution over the candidate set.
5607 OverloadCandidateSet::iterator Best;
5608 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5609 case OR_Success: {
5610 // Apply this conversion.
5611 DeclAccessPair Found =
5612 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5613 if (recordConversion(*this, Loc, From, Converter, T,
5614 HadMultipleCandidates, Found))
5615 return ExprError();
5616 break;
5617 }
5618 case OR_Ambiguous:
5619 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5620 ViableConversions);
5621 case OR_No_Viable_Function:
5622 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5623 HadMultipleCandidates,
5624 ExplicitConversions))
5625 return ExprError();
5626 // fall through 'OR_Deleted' case.
5627 case OR_Deleted:
5628 // We'll complain below about a non-integral condition type.
5629 break;
5630 }
5631 } else {
5632 switch (ViableConversions.size()) {
5633 case 0: {
5634 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5635 HadMultipleCandidates,
5636 ExplicitConversions))
5637 return ExprError();
5638
5639 // We'll complain below about a non-integral condition type.
5640 break;
5641 }
5642 case 1: {
5643 // Apply this conversion.
5644 DeclAccessPair Found = ViableConversions[0];
5645 if (recordConversion(*this, Loc, From, Converter, T,
5646 HadMultipleCandidates, Found))
5647 return ExprError();
5648 break;
5649 }
5650 default:
5651 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5652 ViableConversions);
5653 }
5654 }
5655
5656 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5657 }
5658
5659 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5660 /// an acceptable non-member overloaded operator for a call whose
5661 /// arguments have types T1 (and, if non-empty, T2). This routine
5662 /// implements the check in C++ [over.match.oper]p3b2 concerning
5663 /// enumeration types.
IsAcceptableNonMemberOperatorCandidate(ASTContext & Context,FunctionDecl * Fn,ArrayRef<Expr * > Args)5664 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5665 FunctionDecl *Fn,
5666 ArrayRef<Expr *> Args) {
5667 QualType T1 = Args[0]->getType();
5668 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5669
5670 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5671 return true;
5672
5673 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5674 return true;
5675
5676 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5677 if (Proto->getNumParams() < 1)
5678 return false;
5679
5680 if (T1->isEnumeralType()) {
5681 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5682 if (Context.hasSameUnqualifiedType(T1, ArgType))
5683 return true;
5684 }
5685
5686 if (Proto->getNumParams() < 2)
5687 return false;
5688
5689 if (!T2.isNull() && T2->isEnumeralType()) {
5690 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5691 if (Context.hasSameUnqualifiedType(T2, ArgType))
5692 return true;
5693 }
5694
5695 return false;
5696 }
5697
5698 /// AddOverloadCandidate - Adds the given function to the set of
5699 /// candidate functions, using the given function call arguments. If
5700 /// @p SuppressUserConversions, then don't allow user-defined
5701 /// conversions via constructors or conversion operators.
5702 ///
5703 /// \param PartialOverloading true if we are performing "partial" overloading
5704 /// based on an incomplete set of function arguments. This feature is used by
5705 /// code completion.
5706 void
AddOverloadCandidate(FunctionDecl * Function,DeclAccessPair FoundDecl,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,bool AllowExplicit)5707 Sema::AddOverloadCandidate(FunctionDecl *Function,
5708 DeclAccessPair FoundDecl,
5709 ArrayRef<Expr *> Args,
5710 OverloadCandidateSet &CandidateSet,
5711 bool SuppressUserConversions,
5712 bool PartialOverloading,
5713 bool AllowExplicit) {
5714 const FunctionProtoType *Proto
5715 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5716 assert(Proto && "Functions without a prototype cannot be overloaded");
5717 assert(!Function->getDescribedFunctionTemplate() &&
5718 "Use AddTemplateOverloadCandidate for function templates");
5719
5720 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5721 if (!isa<CXXConstructorDecl>(Method)) {
5722 // If we get here, it's because we're calling a member function
5723 // that is named without a member access expression (e.g.,
5724 // "this->f") that was either written explicitly or created
5725 // implicitly. This can happen with a qualified call to a member
5726 // function, e.g., X::f(). We use an empty type for the implied
5727 // object argument (C++ [over.call.func]p3), and the acting context
5728 // is irrelevant.
5729 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5730 QualType(), Expr::Classification::makeSimpleLValue(),
5731 Args, CandidateSet, SuppressUserConversions,
5732 PartialOverloading);
5733 return;
5734 }
5735 // We treat a constructor like a non-member function, since its object
5736 // argument doesn't participate in overload resolution.
5737 }
5738
5739 if (!CandidateSet.isNewCandidate(Function))
5740 return;
5741
5742 // C++ [over.match.oper]p3:
5743 // if no operand has a class type, only those non-member functions in the
5744 // lookup set that have a first parameter of type T1 or "reference to
5745 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5746 // is a right operand) a second parameter of type T2 or "reference to
5747 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5748 // candidate functions.
5749 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5750 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5751 return;
5752
5753 // C++11 [class.copy]p11: [DR1402]
5754 // A defaulted move constructor that is defined as deleted is ignored by
5755 // overload resolution.
5756 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5757 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5758 Constructor->isMoveConstructor())
5759 return;
5760
5761 // Overload resolution is always an unevaluated context.
5762 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5763
5764 // Add this candidate
5765 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5766 Candidate.FoundDecl = FoundDecl;
5767 Candidate.Function = Function;
5768 Candidate.Viable = true;
5769 Candidate.IsSurrogate = false;
5770 Candidate.IgnoreObjectArgument = false;
5771 Candidate.ExplicitCallArguments = Args.size();
5772
5773 if (Constructor) {
5774 // C++ [class.copy]p3:
5775 // A member function template is never instantiated to perform the copy
5776 // of a class object to an object of its class type.
5777 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5778 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5779 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5780 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5781 ClassType))) {
5782 Candidate.Viable = false;
5783 Candidate.FailureKind = ovl_fail_illegal_constructor;
5784 return;
5785 }
5786 }
5787
5788 unsigned NumParams = Proto->getNumParams();
5789
5790 // (C++ 13.3.2p2): A candidate function having fewer than m
5791 // parameters is viable only if it has an ellipsis in its parameter
5792 // list (8.3.5).
5793 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5794 !Proto->isVariadic()) {
5795 Candidate.Viable = false;
5796 Candidate.FailureKind = ovl_fail_too_many_arguments;
5797 return;
5798 }
5799
5800 // (C++ 13.3.2p2): A candidate function having more than m parameters
5801 // is viable only if the (m+1)st parameter has a default argument
5802 // (8.3.6). For the purposes of overload resolution, the
5803 // parameter list is truncated on the right, so that there are
5804 // exactly m parameters.
5805 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5806 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5807 // Not enough arguments.
5808 Candidate.Viable = false;
5809 Candidate.FailureKind = ovl_fail_too_few_arguments;
5810 return;
5811 }
5812
5813 // (CUDA B.1): Check for invalid calls between targets.
5814 if (getLangOpts().CUDA)
5815 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5816 // Skip the check for callers that are implicit members, because in this
5817 // case we may not yet know what the member's target is; the target is
5818 // inferred for the member automatically, based on the bases and fields of
5819 // the class.
5820 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5821 Candidate.Viable = false;
5822 Candidate.FailureKind = ovl_fail_bad_target;
5823 return;
5824 }
5825
5826 // Determine the implicit conversion sequences for each of the
5827 // arguments.
5828 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5829 if (ArgIdx < NumParams) {
5830 // (C++ 13.3.2p3): for F to be a viable function, there shall
5831 // exist for each argument an implicit conversion sequence
5832 // (13.3.3.1) that converts that argument to the corresponding
5833 // parameter of F.
5834 QualType ParamType = Proto->getParamType(ArgIdx);
5835 Candidate.Conversions[ArgIdx]
5836 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5837 SuppressUserConversions,
5838 /*InOverloadResolution=*/true,
5839 /*AllowObjCWritebackConversion=*/
5840 getLangOpts().ObjCAutoRefCount,
5841 AllowExplicit);
5842 if (Candidate.Conversions[ArgIdx].isBad()) {
5843 Candidate.Viable = false;
5844 Candidate.FailureKind = ovl_fail_bad_conversion;
5845 return;
5846 }
5847 } else {
5848 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5849 // argument for which there is no corresponding parameter is
5850 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5851 Candidate.Conversions[ArgIdx].setEllipsis();
5852 }
5853 }
5854
5855 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5856 Candidate.Viable = false;
5857 Candidate.FailureKind = ovl_fail_enable_if;
5858 Candidate.DeductionFailure.Data = FailedAttr;
5859 return;
5860 }
5861 }
5862
5863 ObjCMethodDecl *
SelectBestMethod(Selector Sel,MultiExprArg Args,bool IsInstance,SmallVectorImpl<ObjCMethodDecl * > & Methods)5864 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5865 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5866 if (Methods.size() <= 1)
5867 return nullptr;
5868
5869 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5870 bool Match = true;
5871 ObjCMethodDecl *Method = Methods[b];
5872 unsigned NumNamedArgs = Sel.getNumArgs();
5873 // Method might have more arguments than selector indicates. This is due
5874 // to addition of c-style arguments in method.
5875 if (Method->param_size() > NumNamedArgs)
5876 NumNamedArgs = Method->param_size();
5877 if (Args.size() < NumNamedArgs)
5878 continue;
5879
5880 for (unsigned i = 0; i < NumNamedArgs; i++) {
5881 // We can't do any type-checking on a type-dependent argument.
5882 if (Args[i]->isTypeDependent()) {
5883 Match = false;
5884 break;
5885 }
5886
5887 ParmVarDecl *param = Method->parameters()[i];
5888 Expr *argExpr = Args[i];
5889 assert(argExpr && "SelectBestMethod(): missing expression");
5890
5891 // Strip the unbridged-cast placeholder expression off unless it's
5892 // a consumed argument.
5893 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5894 !param->hasAttr<CFConsumedAttr>())
5895 argExpr = stripARCUnbridgedCast(argExpr);
5896
5897 // If the parameter is __unknown_anytype, move on to the next method.
5898 if (param->getType() == Context.UnknownAnyTy) {
5899 Match = false;
5900 break;
5901 }
5902
5903 ImplicitConversionSequence ConversionState
5904 = TryCopyInitialization(*this, argExpr, param->getType(),
5905 /*SuppressUserConversions*/false,
5906 /*InOverloadResolution=*/true,
5907 /*AllowObjCWritebackConversion=*/
5908 getLangOpts().ObjCAutoRefCount,
5909 /*AllowExplicit*/false);
5910 if (ConversionState.isBad()) {
5911 Match = false;
5912 break;
5913 }
5914 }
5915 // Promote additional arguments to variadic methods.
5916 if (Match && Method->isVariadic()) {
5917 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5918 if (Args[i]->isTypeDependent()) {
5919 Match = false;
5920 break;
5921 }
5922 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5923 nullptr);
5924 if (Arg.isInvalid()) {
5925 Match = false;
5926 break;
5927 }
5928 }
5929 } else {
5930 // Check for extra arguments to non-variadic methods.
5931 if (Args.size() != NumNamedArgs)
5932 Match = false;
5933 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5934 // Special case when selectors have no argument. In this case, select
5935 // one with the most general result type of 'id'.
5936 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5937 QualType ReturnT = Methods[b]->getReturnType();
5938 if (ReturnT->isObjCIdType())
5939 return Methods[b];
5940 }
5941 }
5942 }
5943
5944 if (Match)
5945 return Method;
5946 }
5947 return nullptr;
5948 }
5949
5950 // specific_attr_iterator iterates over enable_if attributes in reverse, and
5951 // enable_if is order-sensitive. As a result, we need to reverse things
5952 // sometimes. Size of 4 elements is arbitrary.
5953 static SmallVector<EnableIfAttr *, 4>
getOrderedEnableIfAttrs(const FunctionDecl * Function)5954 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5955 SmallVector<EnableIfAttr *, 4> Result;
5956 if (!Function->hasAttrs())
5957 return Result;
5958
5959 const auto &FuncAttrs = Function->getAttrs();
5960 for (Attr *Attr : FuncAttrs)
5961 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5962 Result.push_back(EnableIf);
5963
5964 std::reverse(Result.begin(), Result.end());
5965 return Result;
5966 }
5967
CheckEnableIf(FunctionDecl * Function,ArrayRef<Expr * > Args,bool MissingImplicitThis)5968 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5969 bool MissingImplicitThis) {
5970 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5971 if (EnableIfAttrs.empty())
5972 return nullptr;
5973
5974 SFINAETrap Trap(*this);
5975 SmallVector<Expr *, 16> ConvertedArgs;
5976 bool InitializationFailed = false;
5977
5978 // Convert the arguments.
5979 for (unsigned I = 0, E = Args.size(); I != E; ++I) {
5980 ExprResult R;
5981 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5982 !cast<CXXMethodDecl>(Function)->isStatic() &&
5983 !isa<CXXConstructorDecl>(Function)) {
5984 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5985 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5986 Method, Method);
5987 } else {
5988 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5989 Context, Function->getParamDecl(I)),
5990 SourceLocation(), Args[I]);
5991 }
5992
5993 if (R.isInvalid()) {
5994 InitializationFailed = true;
5995 break;
5996 }
5997
5998 ConvertedArgs.push_back(R.get());
5999 }
6000
6001 if (InitializationFailed || Trap.hasErrorOccurred())
6002 return EnableIfAttrs[0];
6003
6004 // Push default arguments if needed.
6005 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6006 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6007 ParmVarDecl *P = Function->getParamDecl(i);
6008 ExprResult R = PerformCopyInitialization(
6009 InitializedEntity::InitializeParameter(Context,
6010 Function->getParamDecl(i)),
6011 SourceLocation(),
6012 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6013 : P->getDefaultArg());
6014 if (R.isInvalid()) {
6015 InitializationFailed = true;
6016 break;
6017 }
6018 ConvertedArgs.push_back(R.get());
6019 }
6020
6021 if (InitializationFailed || Trap.hasErrorOccurred())
6022 return EnableIfAttrs[0];
6023 }
6024
6025 for (auto *EIA : EnableIfAttrs) {
6026 APValue Result;
6027 // FIXME: This doesn't consider value-dependent cases, because doing so is
6028 // very difficult. Ideally, we should handle them more gracefully.
6029 if (!EIA->getCond()->EvaluateWithSubstitution(
6030 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6031 return EIA;
6032
6033 if (!Result.isInt() || !Result.getInt().getBoolValue())
6034 return EIA;
6035 }
6036 return nullptr;
6037 }
6038
6039 /// \brief Add all of the function declarations in the given function set to
6040 /// the overload candidate set.
AddFunctionCandidates(const UnresolvedSetImpl & Fns,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,TemplateArgumentListInfo * ExplicitTemplateArgs,bool SuppressUserConversions,bool PartialOverloading)6041 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6042 ArrayRef<Expr *> Args,
6043 OverloadCandidateSet& CandidateSet,
6044 TemplateArgumentListInfo *ExplicitTemplateArgs,
6045 bool SuppressUserConversions,
6046 bool PartialOverloading) {
6047 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6048 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6049 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6050 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6051 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6052 cast<CXXMethodDecl>(FD)->getParent(),
6053 Args[0]->getType(), Args[0]->Classify(Context),
6054 Args.slice(1), CandidateSet,
6055 SuppressUserConversions, PartialOverloading);
6056 else
6057 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6058 SuppressUserConversions, PartialOverloading);
6059 } else {
6060 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6061 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6062 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6063 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6064 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6065 ExplicitTemplateArgs,
6066 Args[0]->getType(),
6067 Args[0]->Classify(Context), Args.slice(1),
6068 CandidateSet, SuppressUserConversions,
6069 PartialOverloading);
6070 else
6071 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6072 ExplicitTemplateArgs, Args,
6073 CandidateSet, SuppressUserConversions,
6074 PartialOverloading);
6075 }
6076 }
6077 }
6078
6079 /// AddMethodCandidate - Adds a named decl (which is some kind of
6080 /// method) as a method candidate to the given overload set.
AddMethodCandidate(DeclAccessPair FoundDecl,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)6081 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6082 QualType ObjectType,
6083 Expr::Classification ObjectClassification,
6084 ArrayRef<Expr *> Args,
6085 OverloadCandidateSet& CandidateSet,
6086 bool SuppressUserConversions) {
6087 NamedDecl *Decl = FoundDecl.getDecl();
6088 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6089
6090 if (isa<UsingShadowDecl>(Decl))
6091 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6092
6093 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6094 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6095 "Expected a member function template");
6096 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6097 /*ExplicitArgs*/ nullptr,
6098 ObjectType, ObjectClassification,
6099 Args, CandidateSet,
6100 SuppressUserConversions);
6101 } else {
6102 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6103 ObjectType, ObjectClassification,
6104 Args,
6105 CandidateSet, SuppressUserConversions);
6106 }
6107 }
6108
6109 /// AddMethodCandidate - Adds the given C++ member function to the set
6110 /// of candidate functions, using the given function call arguments
6111 /// and the object argument (@c Object). For example, in a call
6112 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6113 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6114 /// allow user-defined conversions via constructors or conversion
6115 /// operators.
6116 void
AddMethodCandidate(CXXMethodDecl * Method,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading)6117 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6118 CXXRecordDecl *ActingContext, QualType ObjectType,
6119 Expr::Classification ObjectClassification,
6120 ArrayRef<Expr *> Args,
6121 OverloadCandidateSet &CandidateSet,
6122 bool SuppressUserConversions,
6123 bool PartialOverloading) {
6124 const FunctionProtoType *Proto
6125 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6126 assert(Proto && "Methods without a prototype cannot be overloaded");
6127 assert(!isa<CXXConstructorDecl>(Method) &&
6128 "Use AddOverloadCandidate for constructors");
6129
6130 if (!CandidateSet.isNewCandidate(Method))
6131 return;
6132
6133 // C++11 [class.copy]p23: [DR1402]
6134 // A defaulted move assignment operator that is defined as deleted is
6135 // ignored by overload resolution.
6136 if (Method->isDefaulted() && Method->isDeleted() &&
6137 Method->isMoveAssignmentOperator())
6138 return;
6139
6140 // Overload resolution is always an unevaluated context.
6141 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6142
6143 // Add this candidate
6144 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6145 Candidate.FoundDecl = FoundDecl;
6146 Candidate.Function = Method;
6147 Candidate.IsSurrogate = false;
6148 Candidate.IgnoreObjectArgument = false;
6149 Candidate.ExplicitCallArguments = Args.size();
6150
6151 unsigned NumParams = Proto->getNumParams();
6152
6153 // (C++ 13.3.2p2): A candidate function having fewer than m
6154 // parameters is viable only if it has an ellipsis in its parameter
6155 // list (8.3.5).
6156 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6157 !Proto->isVariadic()) {
6158 Candidate.Viable = false;
6159 Candidate.FailureKind = ovl_fail_too_many_arguments;
6160 return;
6161 }
6162
6163 // (C++ 13.3.2p2): A candidate function having more than m parameters
6164 // is viable only if the (m+1)st parameter has a default argument
6165 // (8.3.6). For the purposes of overload resolution, the
6166 // parameter list is truncated on the right, so that there are
6167 // exactly m parameters.
6168 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6169 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6170 // Not enough arguments.
6171 Candidate.Viable = false;
6172 Candidate.FailureKind = ovl_fail_too_few_arguments;
6173 return;
6174 }
6175
6176 Candidate.Viable = true;
6177
6178 if (Method->isStatic() || ObjectType.isNull())
6179 // The implicit object argument is ignored.
6180 Candidate.IgnoreObjectArgument = true;
6181 else {
6182 // Determine the implicit conversion sequence for the object
6183 // parameter.
6184 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6185 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6186 Method, ActingContext);
6187 if (Candidate.Conversions[0].isBad()) {
6188 Candidate.Viable = false;
6189 Candidate.FailureKind = ovl_fail_bad_conversion;
6190 return;
6191 }
6192 }
6193
6194 // (CUDA B.1): Check for invalid calls between targets.
6195 if (getLangOpts().CUDA)
6196 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6197 if (CheckCUDATarget(Caller, Method)) {
6198 Candidate.Viable = false;
6199 Candidate.FailureKind = ovl_fail_bad_target;
6200 return;
6201 }
6202
6203 // Determine the implicit conversion sequences for each of the
6204 // arguments.
6205 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6206 if (ArgIdx < NumParams) {
6207 // (C++ 13.3.2p3): for F to be a viable function, there shall
6208 // exist for each argument an implicit conversion sequence
6209 // (13.3.3.1) that converts that argument to the corresponding
6210 // parameter of F.
6211 QualType ParamType = Proto->getParamType(ArgIdx);
6212 Candidate.Conversions[ArgIdx + 1]
6213 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6214 SuppressUserConversions,
6215 /*InOverloadResolution=*/true,
6216 /*AllowObjCWritebackConversion=*/
6217 getLangOpts().ObjCAutoRefCount);
6218 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6219 Candidate.Viable = false;
6220 Candidate.FailureKind = ovl_fail_bad_conversion;
6221 return;
6222 }
6223 } else {
6224 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6225 // argument for which there is no corresponding parameter is
6226 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6227 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6228 }
6229 }
6230
6231 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6232 Candidate.Viable = false;
6233 Candidate.FailureKind = ovl_fail_enable_if;
6234 Candidate.DeductionFailure.Data = FailedAttr;
6235 return;
6236 }
6237 }
6238
6239 /// \brief Add a C++ member function template as a candidate to the candidate
6240 /// set, using template argument deduction to produce an appropriate member
6241 /// function template specialization.
6242 void
AddMethodTemplateCandidate(FunctionTemplateDecl * MethodTmpl,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,TemplateArgumentListInfo * ExplicitTemplateArgs,QualType ObjectType,Expr::Classification ObjectClassification,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading)6243 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6244 DeclAccessPair FoundDecl,
6245 CXXRecordDecl *ActingContext,
6246 TemplateArgumentListInfo *ExplicitTemplateArgs,
6247 QualType ObjectType,
6248 Expr::Classification ObjectClassification,
6249 ArrayRef<Expr *> Args,
6250 OverloadCandidateSet& CandidateSet,
6251 bool SuppressUserConversions,
6252 bool PartialOverloading) {
6253 if (!CandidateSet.isNewCandidate(MethodTmpl))
6254 return;
6255
6256 // C++ [over.match.funcs]p7:
6257 // In each case where a candidate is a function template, candidate
6258 // function template specializations are generated using template argument
6259 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6260 // candidate functions in the usual way.113) A given name can refer to one
6261 // or more function templates and also to a set of overloaded non-template
6262 // functions. In such a case, the candidate functions generated from each
6263 // function template are combined with the set of non-template candidate
6264 // functions.
6265 TemplateDeductionInfo Info(CandidateSet.getLocation());
6266 FunctionDecl *Specialization = nullptr;
6267 if (TemplateDeductionResult Result
6268 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6269 Specialization, Info, PartialOverloading)) {
6270 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6271 Candidate.FoundDecl = FoundDecl;
6272 Candidate.Function = MethodTmpl->getTemplatedDecl();
6273 Candidate.Viable = false;
6274 Candidate.FailureKind = ovl_fail_bad_deduction;
6275 Candidate.IsSurrogate = false;
6276 Candidate.IgnoreObjectArgument = false;
6277 Candidate.ExplicitCallArguments = Args.size();
6278 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6279 Info);
6280 return;
6281 }
6282
6283 // Add the function template specialization produced by template argument
6284 // deduction as a candidate.
6285 assert(Specialization && "Missing member function template specialization?");
6286 assert(isa<CXXMethodDecl>(Specialization) &&
6287 "Specialization is not a member function?");
6288 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6289 ActingContext, ObjectType, ObjectClassification, Args,
6290 CandidateSet, SuppressUserConversions, PartialOverloading);
6291 }
6292
6293 /// \brief Add a C++ function template specialization as a candidate
6294 /// in the candidate set, using template argument deduction to produce
6295 /// an appropriate function template specialization.
6296 void
AddTemplateOverloadCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading)6297 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6298 DeclAccessPair FoundDecl,
6299 TemplateArgumentListInfo *ExplicitTemplateArgs,
6300 ArrayRef<Expr *> Args,
6301 OverloadCandidateSet& CandidateSet,
6302 bool SuppressUserConversions,
6303 bool PartialOverloading) {
6304 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6305 return;
6306
6307 // C++ [over.match.funcs]p7:
6308 // In each case where a candidate is a function template, candidate
6309 // function template specializations are generated using template argument
6310 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6311 // candidate functions in the usual way.113) A given name can refer to one
6312 // or more function templates and also to a set of overloaded non-template
6313 // functions. In such a case, the candidate functions generated from each
6314 // function template are combined with the set of non-template candidate
6315 // functions.
6316 TemplateDeductionInfo Info(CandidateSet.getLocation());
6317 FunctionDecl *Specialization = nullptr;
6318 if (TemplateDeductionResult Result
6319 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6320 Specialization, Info, PartialOverloading)) {
6321 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6322 Candidate.FoundDecl = FoundDecl;
6323 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6324 Candidate.Viable = false;
6325 Candidate.FailureKind = ovl_fail_bad_deduction;
6326 Candidate.IsSurrogate = false;
6327 Candidate.IgnoreObjectArgument = false;
6328 Candidate.ExplicitCallArguments = Args.size();
6329 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6330 Info);
6331 return;
6332 }
6333
6334 // Add the function template specialization produced by template argument
6335 // deduction as a candidate.
6336 assert(Specialization && "Missing function template specialization?");
6337 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6338 SuppressUserConversions, PartialOverloading);
6339 }
6340
6341 /// Determine whether this is an allowable conversion from the result
6342 /// of an explicit conversion operator to the expected type, per C++
6343 /// [over.match.conv]p1 and [over.match.ref]p1.
6344 ///
6345 /// \param ConvType The return type of the conversion function.
6346 ///
6347 /// \param ToType The type we are converting to.
6348 ///
6349 /// \param AllowObjCPointerConversion Allow a conversion from one
6350 /// Objective-C pointer to another.
6351 ///
6352 /// \returns true if the conversion is allowable, false otherwise.
isAllowableExplicitConversion(Sema & S,QualType ConvType,QualType ToType,bool AllowObjCPointerConversion)6353 static bool isAllowableExplicitConversion(Sema &S,
6354 QualType ConvType, QualType ToType,
6355 bool AllowObjCPointerConversion) {
6356 QualType ToNonRefType = ToType.getNonReferenceType();
6357
6358 // Easy case: the types are the same.
6359 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6360 return true;
6361
6362 // Allow qualification conversions.
6363 bool ObjCLifetimeConversion;
6364 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6365 ObjCLifetimeConversion))
6366 return true;
6367
6368 // If we're not allowed to consider Objective-C pointer conversions,
6369 // we're done.
6370 if (!AllowObjCPointerConversion)
6371 return false;
6372
6373 // Is this an Objective-C pointer conversion?
6374 bool IncompatibleObjC = false;
6375 QualType ConvertedType;
6376 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6377 IncompatibleObjC);
6378 }
6379
6380 /// AddConversionCandidate - Add a C++ conversion function as a
6381 /// candidate in the candidate set (C++ [over.match.conv],
6382 /// C++ [over.match.copy]). From is the expression we're converting from,
6383 /// and ToType is the type that we're eventually trying to convert to
6384 /// (which may or may not be the same type as the type that the
6385 /// conversion function produces).
6386 void
AddConversionCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit)6387 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6388 DeclAccessPair FoundDecl,
6389 CXXRecordDecl *ActingContext,
6390 Expr *From, QualType ToType,
6391 OverloadCandidateSet& CandidateSet,
6392 bool AllowObjCConversionOnExplicit) {
6393 assert(!Conversion->getDescribedFunctionTemplate() &&
6394 "Conversion function templates use AddTemplateConversionCandidate");
6395 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6396 if (!CandidateSet.isNewCandidate(Conversion))
6397 return;
6398
6399 // If the conversion function has an undeduced return type, trigger its
6400 // deduction now.
6401 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6402 if (DeduceReturnType(Conversion, From->getExprLoc()))
6403 return;
6404 ConvType = Conversion->getConversionType().getNonReferenceType();
6405 }
6406
6407 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6408 // operator is only a candidate if its return type is the target type or
6409 // can be converted to the target type with a qualification conversion.
6410 if (Conversion->isExplicit() &&
6411 !isAllowableExplicitConversion(*this, ConvType, ToType,
6412 AllowObjCConversionOnExplicit))
6413 return;
6414
6415 // Overload resolution is always an unevaluated context.
6416 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6417
6418 // Add this candidate
6419 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6420 Candidate.FoundDecl = FoundDecl;
6421 Candidate.Function = Conversion;
6422 Candidate.IsSurrogate = false;
6423 Candidate.IgnoreObjectArgument = false;
6424 Candidate.FinalConversion.setAsIdentityConversion();
6425 Candidate.FinalConversion.setFromType(ConvType);
6426 Candidate.FinalConversion.setAllToTypes(ToType);
6427 Candidate.Viable = true;
6428 Candidate.ExplicitCallArguments = 1;
6429
6430 // C++ [over.match.funcs]p4:
6431 // For conversion functions, the function is considered to be a member of
6432 // the class of the implicit implied object argument for the purpose of
6433 // defining the type of the implicit object parameter.
6434 //
6435 // Determine the implicit conversion sequence for the implicit
6436 // object parameter.
6437 QualType ImplicitParamType = From->getType();
6438 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6439 ImplicitParamType = FromPtrType->getPointeeType();
6440 CXXRecordDecl *ConversionContext
6441 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6442
6443 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6444 *this, CandidateSet.getLocation(), From->getType(),
6445 From->Classify(Context), Conversion, ConversionContext);
6446
6447 if (Candidate.Conversions[0].isBad()) {
6448 Candidate.Viable = false;
6449 Candidate.FailureKind = ovl_fail_bad_conversion;
6450 return;
6451 }
6452
6453 // We won't go through a user-defined type conversion function to convert a
6454 // derived to base as such conversions are given Conversion Rank. They only
6455 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6456 QualType FromCanon
6457 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6458 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6459 if (FromCanon == ToCanon ||
6460 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6461 Candidate.Viable = false;
6462 Candidate.FailureKind = ovl_fail_trivial_conversion;
6463 return;
6464 }
6465
6466 // To determine what the conversion from the result of calling the
6467 // conversion function to the type we're eventually trying to
6468 // convert to (ToType), we need to synthesize a call to the
6469 // conversion function and attempt copy initialization from it. This
6470 // makes sure that we get the right semantics with respect to
6471 // lvalues/rvalues and the type. Fortunately, we can allocate this
6472 // call on the stack and we don't need its arguments to be
6473 // well-formed.
6474 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6475 VK_LValue, From->getLocStart());
6476 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6477 Context.getPointerType(Conversion->getType()),
6478 CK_FunctionToPointerDecay,
6479 &ConversionRef, VK_RValue);
6480
6481 QualType ConversionType = Conversion->getConversionType();
6482 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6483 Candidate.Viable = false;
6484 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6485 return;
6486 }
6487
6488 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6489
6490 // Note that it is safe to allocate CallExpr on the stack here because
6491 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6492 // allocator).
6493 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6494 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6495 From->getLocStart());
6496 ImplicitConversionSequence ICS =
6497 TryCopyInitialization(*this, &Call, ToType,
6498 /*SuppressUserConversions=*/true,
6499 /*InOverloadResolution=*/false,
6500 /*AllowObjCWritebackConversion=*/false);
6501
6502 switch (ICS.getKind()) {
6503 case ImplicitConversionSequence::StandardConversion:
6504 Candidate.FinalConversion = ICS.Standard;
6505
6506 // C++ [over.ics.user]p3:
6507 // If the user-defined conversion is specified by a specialization of a
6508 // conversion function template, the second standard conversion sequence
6509 // shall have exact match rank.
6510 if (Conversion->getPrimaryTemplate() &&
6511 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6512 Candidate.Viable = false;
6513 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6514 return;
6515 }
6516
6517 // C++0x [dcl.init.ref]p5:
6518 // In the second case, if the reference is an rvalue reference and
6519 // the second standard conversion sequence of the user-defined
6520 // conversion sequence includes an lvalue-to-rvalue conversion, the
6521 // program is ill-formed.
6522 if (ToType->isRValueReferenceType() &&
6523 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6524 Candidate.Viable = false;
6525 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6526 return;
6527 }
6528 break;
6529
6530 case ImplicitConversionSequence::BadConversion:
6531 Candidate.Viable = false;
6532 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6533 return;
6534
6535 default:
6536 llvm_unreachable(
6537 "Can only end up with a standard conversion sequence or failure");
6538 }
6539
6540 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6541 Candidate.Viable = false;
6542 Candidate.FailureKind = ovl_fail_enable_if;
6543 Candidate.DeductionFailure.Data = FailedAttr;
6544 return;
6545 }
6546 }
6547
6548 /// \brief Adds a conversion function template specialization
6549 /// candidate to the overload set, using template argument deduction
6550 /// to deduce the template arguments of the conversion function
6551 /// template from the type that we are converting to (C++
6552 /// [temp.deduct.conv]).
6553 void
AddTemplateConversionCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,CXXRecordDecl * ActingDC,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet,bool AllowObjCConversionOnExplicit)6554 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6555 DeclAccessPair FoundDecl,
6556 CXXRecordDecl *ActingDC,
6557 Expr *From, QualType ToType,
6558 OverloadCandidateSet &CandidateSet,
6559 bool AllowObjCConversionOnExplicit) {
6560 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6561 "Only conversion function templates permitted here");
6562
6563 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6564 return;
6565
6566 TemplateDeductionInfo Info(CandidateSet.getLocation());
6567 CXXConversionDecl *Specialization = nullptr;
6568 if (TemplateDeductionResult Result
6569 = DeduceTemplateArguments(FunctionTemplate, ToType,
6570 Specialization, Info)) {
6571 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6572 Candidate.FoundDecl = FoundDecl;
6573 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6574 Candidate.Viable = false;
6575 Candidate.FailureKind = ovl_fail_bad_deduction;
6576 Candidate.IsSurrogate = false;
6577 Candidate.IgnoreObjectArgument = false;
6578 Candidate.ExplicitCallArguments = 1;
6579 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6580 Info);
6581 return;
6582 }
6583
6584 // Add the conversion function template specialization produced by
6585 // template argument deduction as a candidate.
6586 assert(Specialization && "Missing function template specialization?");
6587 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6588 CandidateSet, AllowObjCConversionOnExplicit);
6589 }
6590
6591 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6592 /// converts the given @c Object to a function pointer via the
6593 /// conversion function @c Conversion, and then attempts to call it
6594 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6595 /// the type of function that we'll eventually be calling.
AddSurrogateCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,const FunctionProtoType * Proto,Expr * Object,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)6596 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6597 DeclAccessPair FoundDecl,
6598 CXXRecordDecl *ActingContext,
6599 const FunctionProtoType *Proto,
6600 Expr *Object,
6601 ArrayRef<Expr *> Args,
6602 OverloadCandidateSet& CandidateSet) {
6603 if (!CandidateSet.isNewCandidate(Conversion))
6604 return;
6605
6606 // Overload resolution is always an unevaluated context.
6607 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6608
6609 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6610 Candidate.FoundDecl = FoundDecl;
6611 Candidate.Function = nullptr;
6612 Candidate.Surrogate = Conversion;
6613 Candidate.Viable = true;
6614 Candidate.IsSurrogate = true;
6615 Candidate.IgnoreObjectArgument = false;
6616 Candidate.ExplicitCallArguments = Args.size();
6617
6618 // Determine the implicit conversion sequence for the implicit
6619 // object parameter.
6620 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6621 *this, CandidateSet.getLocation(), Object->getType(),
6622 Object->Classify(Context), Conversion, ActingContext);
6623 if (ObjectInit.isBad()) {
6624 Candidate.Viable = false;
6625 Candidate.FailureKind = ovl_fail_bad_conversion;
6626 Candidate.Conversions[0] = ObjectInit;
6627 return;
6628 }
6629
6630 // The first conversion is actually a user-defined conversion whose
6631 // first conversion is ObjectInit's standard conversion (which is
6632 // effectively a reference binding). Record it as such.
6633 Candidate.Conversions[0].setUserDefined();
6634 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6635 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6636 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6637 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6638 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6639 Candidate.Conversions[0].UserDefined.After
6640 = Candidate.Conversions[0].UserDefined.Before;
6641 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6642
6643 // Find the
6644 unsigned NumParams = Proto->getNumParams();
6645
6646 // (C++ 13.3.2p2): A candidate function having fewer than m
6647 // parameters is viable only if it has an ellipsis in its parameter
6648 // list (8.3.5).
6649 if (Args.size() > NumParams && !Proto->isVariadic()) {
6650 Candidate.Viable = false;
6651 Candidate.FailureKind = ovl_fail_too_many_arguments;
6652 return;
6653 }
6654
6655 // Function types don't have any default arguments, so just check if
6656 // we have enough arguments.
6657 if (Args.size() < NumParams) {
6658 // Not enough arguments.
6659 Candidate.Viable = false;
6660 Candidate.FailureKind = ovl_fail_too_few_arguments;
6661 return;
6662 }
6663
6664 // Determine the implicit conversion sequences for each of the
6665 // arguments.
6666 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6667 if (ArgIdx < NumParams) {
6668 // (C++ 13.3.2p3): for F to be a viable function, there shall
6669 // exist for each argument an implicit conversion sequence
6670 // (13.3.3.1) that converts that argument to the corresponding
6671 // parameter of F.
6672 QualType ParamType = Proto->getParamType(ArgIdx);
6673 Candidate.Conversions[ArgIdx + 1]
6674 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6675 /*SuppressUserConversions=*/false,
6676 /*InOverloadResolution=*/false,
6677 /*AllowObjCWritebackConversion=*/
6678 getLangOpts().ObjCAutoRefCount);
6679 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6680 Candidate.Viable = false;
6681 Candidate.FailureKind = ovl_fail_bad_conversion;
6682 return;
6683 }
6684 } else {
6685 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6686 // argument for which there is no corresponding parameter is
6687 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6688 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6689 }
6690 }
6691
6692 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6693 Candidate.Viable = false;
6694 Candidate.FailureKind = ovl_fail_enable_if;
6695 Candidate.DeductionFailure.Data = FailedAttr;
6696 return;
6697 }
6698 }
6699
6700 /// \brief Add overload candidates for overloaded operators that are
6701 /// member functions.
6702 ///
6703 /// Add the overloaded operator candidates that are member functions
6704 /// for the operator Op that was used in an operator expression such
6705 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6706 /// CandidateSet will store the added overload candidates. (C++
6707 /// [over.match.oper]).
AddMemberOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,SourceRange OpRange)6708 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6709 SourceLocation OpLoc,
6710 ArrayRef<Expr *> Args,
6711 OverloadCandidateSet& CandidateSet,
6712 SourceRange OpRange) {
6713 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6714
6715 // C++ [over.match.oper]p3:
6716 // For a unary operator @ with an operand of a type whose
6717 // cv-unqualified version is T1, and for a binary operator @ with
6718 // a left operand of a type whose cv-unqualified version is T1 and
6719 // a right operand of a type whose cv-unqualified version is T2,
6720 // three sets of candidate functions, designated member
6721 // candidates, non-member candidates and built-in candidates, are
6722 // constructed as follows:
6723 QualType T1 = Args[0]->getType();
6724
6725 // -- If T1 is a complete class type or a class currently being
6726 // defined, the set of member candidates is the result of the
6727 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6728 // the set of member candidates is empty.
6729 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6730 // Complete the type if it can be completed.
6731 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6732 return;
6733 // If the type is neither complete nor being defined, bail out now.
6734 if (!T1Rec->getDecl()->getDefinition())
6735 return;
6736
6737 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6738 LookupQualifiedName(Operators, T1Rec->getDecl());
6739 Operators.suppressDiagnostics();
6740
6741 for (LookupResult::iterator Oper = Operators.begin(),
6742 OperEnd = Operators.end();
6743 Oper != OperEnd;
6744 ++Oper)
6745 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6746 Args[0]->Classify(Context),
6747 Args.slice(1),
6748 CandidateSet,
6749 /* SuppressUserConversions = */ false);
6750 }
6751 }
6752
6753 /// AddBuiltinCandidate - Add a candidate for a built-in
6754 /// operator. ResultTy and ParamTys are the result and parameter types
6755 /// of the built-in candidate, respectively. Args and NumArgs are the
6756 /// arguments being passed to the candidate. IsAssignmentOperator
6757 /// should be true when this built-in candidate is an assignment
6758 /// operator. NumContextualBoolArguments is the number of arguments
6759 /// (at the beginning of the argument list) that will be contextually
6760 /// converted to bool.
AddBuiltinCandidate(QualType ResultTy,QualType * ParamTys,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool IsAssignmentOperator,unsigned NumContextualBoolArguments)6761 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6762 ArrayRef<Expr *> Args,
6763 OverloadCandidateSet& CandidateSet,
6764 bool IsAssignmentOperator,
6765 unsigned NumContextualBoolArguments) {
6766 // Overload resolution is always an unevaluated context.
6767 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6768
6769 // Add this candidate
6770 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6771 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6772 Candidate.Function = nullptr;
6773 Candidate.IsSurrogate = false;
6774 Candidate.IgnoreObjectArgument = false;
6775 Candidate.BuiltinTypes.ResultTy = ResultTy;
6776 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6777 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6778
6779 // Determine the implicit conversion sequences for each of the
6780 // arguments.
6781 Candidate.Viable = true;
6782 Candidate.ExplicitCallArguments = Args.size();
6783 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6784 // C++ [over.match.oper]p4:
6785 // For the built-in assignment operators, conversions of the
6786 // left operand are restricted as follows:
6787 // -- no temporaries are introduced to hold the left operand, and
6788 // -- no user-defined conversions are applied to the left
6789 // operand to achieve a type match with the left-most
6790 // parameter of a built-in candidate.
6791 //
6792 // We block these conversions by turning off user-defined
6793 // conversions, since that is the only way that initialization of
6794 // a reference to a non-class type can occur from something that
6795 // is not of the same type.
6796 if (ArgIdx < NumContextualBoolArguments) {
6797 assert(ParamTys[ArgIdx] == Context.BoolTy &&
6798 "Contextual conversion to bool requires bool type");
6799 Candidate.Conversions[ArgIdx]
6800 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6801 } else {
6802 Candidate.Conversions[ArgIdx]
6803 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6804 ArgIdx == 0 && IsAssignmentOperator,
6805 /*InOverloadResolution=*/false,
6806 /*AllowObjCWritebackConversion=*/
6807 getLangOpts().ObjCAutoRefCount);
6808 }
6809 if (Candidate.Conversions[ArgIdx].isBad()) {
6810 Candidate.Viable = false;
6811 Candidate.FailureKind = ovl_fail_bad_conversion;
6812 break;
6813 }
6814 }
6815 }
6816
6817 namespace {
6818
6819 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6820 /// candidate operator functions for built-in operators (C++
6821 /// [over.built]). The types are separated into pointer types and
6822 /// enumeration types.
6823 class BuiltinCandidateTypeSet {
6824 /// TypeSet - A set of types.
6825 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6826 llvm::SmallPtrSet<QualType, 8>> TypeSet;
6827
6828 /// PointerTypes - The set of pointer types that will be used in the
6829 /// built-in candidates.
6830 TypeSet PointerTypes;
6831
6832 /// MemberPointerTypes - The set of member pointer types that will be
6833 /// used in the built-in candidates.
6834 TypeSet MemberPointerTypes;
6835
6836 /// EnumerationTypes - The set of enumeration types that will be
6837 /// used in the built-in candidates.
6838 TypeSet EnumerationTypes;
6839
6840 /// \brief The set of vector types that will be used in the built-in
6841 /// candidates.
6842 TypeSet VectorTypes;
6843
6844 /// \brief A flag indicating non-record types are viable candidates
6845 bool HasNonRecordTypes;
6846
6847 /// \brief A flag indicating whether either arithmetic or enumeration types
6848 /// were present in the candidate set.
6849 bool HasArithmeticOrEnumeralTypes;
6850
6851 /// \brief A flag indicating whether the nullptr type was present in the
6852 /// candidate set.
6853 bool HasNullPtrType;
6854
6855 /// Sema - The semantic analysis instance where we are building the
6856 /// candidate type set.
6857 Sema &SemaRef;
6858
6859 /// Context - The AST context in which we will build the type sets.
6860 ASTContext &Context;
6861
6862 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6863 const Qualifiers &VisibleQuals);
6864 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6865
6866 public:
6867 /// iterator - Iterates through the types that are part of the set.
6868 typedef TypeSet::iterator iterator;
6869
BuiltinCandidateTypeSet(Sema & SemaRef)6870 BuiltinCandidateTypeSet(Sema &SemaRef)
6871 : HasNonRecordTypes(false),
6872 HasArithmeticOrEnumeralTypes(false),
6873 HasNullPtrType(false),
6874 SemaRef(SemaRef),
6875 Context(SemaRef.Context) { }
6876
6877 void AddTypesConvertedFrom(QualType Ty,
6878 SourceLocation Loc,
6879 bool AllowUserConversions,
6880 bool AllowExplicitConversions,
6881 const Qualifiers &VisibleTypeConversionsQuals);
6882
6883 /// pointer_begin - First pointer type found;
pointer_begin()6884 iterator pointer_begin() { return PointerTypes.begin(); }
6885
6886 /// pointer_end - Past the last pointer type found;
pointer_end()6887 iterator pointer_end() { return PointerTypes.end(); }
6888
6889 /// member_pointer_begin - First member pointer type found;
member_pointer_begin()6890 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6891
6892 /// member_pointer_end - Past the last member pointer type found;
member_pointer_end()6893 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6894
6895 /// enumeration_begin - First enumeration type found;
enumeration_begin()6896 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6897
6898 /// enumeration_end - Past the last enumeration type found;
enumeration_end()6899 iterator enumeration_end() { return EnumerationTypes.end(); }
6900
vector_begin()6901 iterator vector_begin() { return VectorTypes.begin(); }
vector_end()6902 iterator vector_end() { return VectorTypes.end(); }
6903
hasNonRecordTypes()6904 bool hasNonRecordTypes() { return HasNonRecordTypes; }
hasArithmeticOrEnumeralTypes()6905 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
hasNullPtrType() const6906 bool hasNullPtrType() const { return HasNullPtrType; }
6907 };
6908
6909 } // end anonymous namespace
6910
6911 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6912 /// the set of pointer types along with any more-qualified variants of
6913 /// that type. For example, if @p Ty is "int const *", this routine
6914 /// will add "int const *", "int const volatile *", "int const
6915 /// restrict *", and "int const volatile restrict *" to the set of
6916 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6917 /// false otherwise.
6918 ///
6919 /// FIXME: what to do about extended qualifiers?
6920 bool
AddPointerWithMoreQualifiedTypeVariants(QualType Ty,const Qualifiers & VisibleQuals)6921 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6922 const Qualifiers &VisibleQuals) {
6923
6924 // Insert this type.
6925 if (!PointerTypes.insert(Ty))
6926 return false;
6927
6928 QualType PointeeTy;
6929 const PointerType *PointerTy = Ty->getAs<PointerType>();
6930 bool buildObjCPtr = false;
6931 if (!PointerTy) {
6932 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6933 PointeeTy = PTy->getPointeeType();
6934 buildObjCPtr = true;
6935 } else {
6936 PointeeTy = PointerTy->getPointeeType();
6937 }
6938
6939 // Don't add qualified variants of arrays. For one, they're not allowed
6940 // (the qualifier would sink to the element type), and for another, the
6941 // only overload situation where it matters is subscript or pointer +- int,
6942 // and those shouldn't have qualifier variants anyway.
6943 if (PointeeTy->isArrayType())
6944 return true;
6945
6946 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6947 bool hasVolatile = VisibleQuals.hasVolatile();
6948 bool hasRestrict = VisibleQuals.hasRestrict();
6949
6950 // Iterate through all strict supersets of BaseCVR.
6951 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6952 if ((CVR | BaseCVR) != CVR) continue;
6953 // Skip over volatile if no volatile found anywhere in the types.
6954 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6955
6956 // Skip over restrict if no restrict found anywhere in the types, or if
6957 // the type cannot be restrict-qualified.
6958 if ((CVR & Qualifiers::Restrict) &&
6959 (!hasRestrict ||
6960 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6961 continue;
6962
6963 // Build qualified pointee type.
6964 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6965
6966 // Build qualified pointer type.
6967 QualType QPointerTy;
6968 if (!buildObjCPtr)
6969 QPointerTy = Context.getPointerType(QPointeeTy);
6970 else
6971 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6972
6973 // Insert qualified pointer type.
6974 PointerTypes.insert(QPointerTy);
6975 }
6976
6977 return true;
6978 }
6979
6980 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6981 /// to the set of pointer types along with any more-qualified variants of
6982 /// that type. For example, if @p Ty is "int const *", this routine
6983 /// will add "int const *", "int const volatile *", "int const
6984 /// restrict *", and "int const volatile restrict *" to the set of
6985 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6986 /// false otherwise.
6987 ///
6988 /// FIXME: what to do about extended qualifiers?
6989 bool
AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty)6990 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6991 QualType Ty) {
6992 // Insert this type.
6993 if (!MemberPointerTypes.insert(Ty))
6994 return false;
6995
6996 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6997 assert(PointerTy && "type was not a member pointer type!");
6998
6999 QualType PointeeTy = PointerTy->getPointeeType();
7000 // Don't add qualified variants of arrays. For one, they're not allowed
7001 // (the qualifier would sink to the element type), and for another, the
7002 // only overload situation where it matters is subscript or pointer +- int,
7003 // and those shouldn't have qualifier variants anyway.
7004 if (PointeeTy->isArrayType())
7005 return true;
7006 const Type *ClassTy = PointerTy->getClass();
7007
7008 // Iterate through all strict supersets of the pointee type's CVR
7009 // qualifiers.
7010 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7011 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7012 if ((CVR | BaseCVR) != CVR) continue;
7013
7014 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7015 MemberPointerTypes.insert(
7016 Context.getMemberPointerType(QPointeeTy, ClassTy));
7017 }
7018
7019 return true;
7020 }
7021
7022 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7023 /// Ty can be implicit converted to the given set of @p Types. We're
7024 /// primarily interested in pointer types and enumeration types. We also
7025 /// take member pointer types, for the conditional operator.
7026 /// AllowUserConversions is true if we should look at the conversion
7027 /// functions of a class type, and AllowExplicitConversions if we
7028 /// should also include the explicit conversion functions of a class
7029 /// type.
7030 void
AddTypesConvertedFrom(QualType Ty,SourceLocation Loc,bool AllowUserConversions,bool AllowExplicitConversions,const Qualifiers & VisibleQuals)7031 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7032 SourceLocation Loc,
7033 bool AllowUserConversions,
7034 bool AllowExplicitConversions,
7035 const Qualifiers &VisibleQuals) {
7036 // Only deal with canonical types.
7037 Ty = Context.getCanonicalType(Ty);
7038
7039 // Look through reference types; they aren't part of the type of an
7040 // expression for the purposes of conversions.
7041 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7042 Ty = RefTy->getPointeeType();
7043
7044 // If we're dealing with an array type, decay to the pointer.
7045 if (Ty->isArrayType())
7046 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7047
7048 // Otherwise, we don't care about qualifiers on the type.
7049 Ty = Ty.getLocalUnqualifiedType();
7050
7051 // Flag if we ever add a non-record type.
7052 const RecordType *TyRec = Ty->getAs<RecordType>();
7053 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7054
7055 // Flag if we encounter an arithmetic type.
7056 HasArithmeticOrEnumeralTypes =
7057 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7058
7059 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7060 PointerTypes.insert(Ty);
7061 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7062 // Insert our type, and its more-qualified variants, into the set
7063 // of types.
7064 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7065 return;
7066 } else if (Ty->isMemberPointerType()) {
7067 // Member pointers are far easier, since the pointee can't be converted.
7068 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7069 return;
7070 } else if (Ty->isEnumeralType()) {
7071 HasArithmeticOrEnumeralTypes = true;
7072 EnumerationTypes.insert(Ty);
7073 } else if (Ty->isVectorType()) {
7074 // We treat vector types as arithmetic types in many contexts as an
7075 // extension.
7076 HasArithmeticOrEnumeralTypes = true;
7077 VectorTypes.insert(Ty);
7078 } else if (Ty->isNullPtrType()) {
7079 HasNullPtrType = true;
7080 } else if (AllowUserConversions && TyRec) {
7081 // No conversion functions in incomplete types.
7082 if (!SemaRef.isCompleteType(Loc, Ty))
7083 return;
7084
7085 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7086 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7087 if (isa<UsingShadowDecl>(D))
7088 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7089
7090 // Skip conversion function templates; they don't tell us anything
7091 // about which builtin types we can convert to.
7092 if (isa<FunctionTemplateDecl>(D))
7093 continue;
7094
7095 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7096 if (AllowExplicitConversions || !Conv->isExplicit()) {
7097 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7098 VisibleQuals);
7099 }
7100 }
7101 }
7102 }
7103
7104 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7105 /// the volatile- and non-volatile-qualified assignment operators for the
7106 /// given type to the candidate set.
AddBuiltinAssignmentOperatorCandidates(Sema & S,QualType T,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)7107 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7108 QualType T,
7109 ArrayRef<Expr *> Args,
7110 OverloadCandidateSet &CandidateSet) {
7111 QualType ParamTypes[2];
7112
7113 // T& operator=(T&, T)
7114 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7115 ParamTypes[1] = T;
7116 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7117 /*IsAssignmentOperator=*/true);
7118
7119 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7120 // volatile T& operator=(volatile T&, T)
7121 ParamTypes[0]
7122 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7123 ParamTypes[1] = T;
7124 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7125 /*IsAssignmentOperator=*/true);
7126 }
7127 }
7128
7129 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7130 /// if any, found in visible type conversion functions found in ArgExpr's type.
CollectVRQualifiers(ASTContext & Context,Expr * ArgExpr)7131 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7132 Qualifiers VRQuals;
7133 const RecordType *TyRec;
7134 if (const MemberPointerType *RHSMPType =
7135 ArgExpr->getType()->getAs<MemberPointerType>())
7136 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7137 else
7138 TyRec = ArgExpr->getType()->getAs<RecordType>();
7139 if (!TyRec) {
7140 // Just to be safe, assume the worst case.
7141 VRQuals.addVolatile();
7142 VRQuals.addRestrict();
7143 return VRQuals;
7144 }
7145
7146 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7147 if (!ClassDecl->hasDefinition())
7148 return VRQuals;
7149
7150 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7151 if (isa<UsingShadowDecl>(D))
7152 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7153 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7154 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7155 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7156 CanTy = ResTypeRef->getPointeeType();
7157 // Need to go down the pointer/mempointer chain and add qualifiers
7158 // as see them.
7159 bool done = false;
7160 while (!done) {
7161 if (CanTy.isRestrictQualified())
7162 VRQuals.addRestrict();
7163 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7164 CanTy = ResTypePtr->getPointeeType();
7165 else if (const MemberPointerType *ResTypeMPtr =
7166 CanTy->getAs<MemberPointerType>())
7167 CanTy = ResTypeMPtr->getPointeeType();
7168 else
7169 done = true;
7170 if (CanTy.isVolatileQualified())
7171 VRQuals.addVolatile();
7172 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7173 return VRQuals;
7174 }
7175 }
7176 }
7177 return VRQuals;
7178 }
7179
7180 namespace {
7181
7182 /// \brief Helper class to manage the addition of builtin operator overload
7183 /// candidates. It provides shared state and utility methods used throughout
7184 /// the process, as well as a helper method to add each group of builtin
7185 /// operator overloads from the standard to a candidate set.
7186 class BuiltinOperatorOverloadBuilder {
7187 // Common instance state available to all overload candidate addition methods.
7188 Sema &S;
7189 ArrayRef<Expr *> Args;
7190 Qualifiers VisibleTypeConversionsQuals;
7191 bool HasArithmeticOrEnumeralCandidateType;
7192 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7193 OverloadCandidateSet &CandidateSet;
7194
7195 // Define some constants used to index and iterate over the arithemetic types
7196 // provided via the getArithmeticType() method below.
7197 // The "promoted arithmetic types" are the arithmetic
7198 // types are that preserved by promotion (C++ [over.built]p2).
7199 static const unsigned FirstIntegralType = 4;
7200 static const unsigned LastIntegralType = 21;
7201 static const unsigned FirstPromotedIntegralType = 4,
7202 LastPromotedIntegralType = 12;
7203 static const unsigned FirstPromotedArithmeticType = 0,
7204 LastPromotedArithmeticType = 12;
7205 static const unsigned NumArithmeticTypes = 21;
7206
7207 /// \brief Get the canonical type for a given arithmetic type index.
getArithmeticType(unsigned index)7208 CanQualType getArithmeticType(unsigned index) {
7209 assert(index < NumArithmeticTypes);
7210 static CanQualType ASTContext::* const
7211 ArithmeticTypes[NumArithmeticTypes] = {
7212 // Start of promoted types.
7213 &ASTContext::FloatTy,
7214 &ASTContext::DoubleTy,
7215 &ASTContext::LongDoubleTy,
7216 &ASTContext::Float128Ty,
7217
7218 // Start of integral types.
7219 &ASTContext::IntTy,
7220 &ASTContext::LongTy,
7221 &ASTContext::LongLongTy,
7222 &ASTContext::Int128Ty,
7223 &ASTContext::UnsignedIntTy,
7224 &ASTContext::UnsignedLongTy,
7225 &ASTContext::UnsignedLongLongTy,
7226 &ASTContext::UnsignedInt128Ty,
7227 // End of promoted types.
7228
7229 &ASTContext::BoolTy,
7230 &ASTContext::CharTy,
7231 &ASTContext::WCharTy,
7232 &ASTContext::Char16Ty,
7233 &ASTContext::Char32Ty,
7234 &ASTContext::SignedCharTy,
7235 &ASTContext::ShortTy,
7236 &ASTContext::UnsignedCharTy,
7237 &ASTContext::UnsignedShortTy,
7238 // End of integral types.
7239 // FIXME: What about complex? What about half?
7240 };
7241 return S.Context.*ArithmeticTypes[index];
7242 }
7243
7244 /// \brief Gets the canonical type resulting from the usual arithemetic
7245 /// converions for the given arithmetic types.
getUsualArithmeticConversions(unsigned L,unsigned R)7246 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7247 // Accelerator table for performing the usual arithmetic conversions.
7248 // The rules are basically:
7249 // - if either is floating-point, use the wider floating-point
7250 // - if same signedness, use the higher rank
7251 // - if same size, use unsigned of the higher rank
7252 // - use the larger type
7253 // These rules, together with the axiom that higher ranks are
7254 // never smaller, are sufficient to precompute all of these results
7255 // *except* when dealing with signed types of higher rank.
7256 // (we could precompute SLL x UI for all known platforms, but it's
7257 // better not to make any assumptions).
7258 // We assume that int128 has a higher rank than long long on all platforms.
7259 enum PromotedType : int8_t {
7260 Dep=-1,
7261 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
7262 };
7263 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7264 [LastPromotedArithmeticType] = {
7265 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7266 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7267 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7268 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7269 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7270 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7271 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7272 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7273 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7274 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7275 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7276 };
7277
7278 assert(L < LastPromotedArithmeticType);
7279 assert(R < LastPromotedArithmeticType);
7280 int Idx = ConversionsTable[L][R];
7281
7282 // Fast path: the table gives us a concrete answer.
7283 if (Idx != Dep) return getArithmeticType(Idx);
7284
7285 // Slow path: we need to compare widths.
7286 // An invariant is that the signed type has higher rank.
7287 CanQualType LT = getArithmeticType(L),
7288 RT = getArithmeticType(R);
7289 unsigned LW = S.Context.getIntWidth(LT),
7290 RW = S.Context.getIntWidth(RT);
7291
7292 // If they're different widths, use the signed type.
7293 if (LW > RW) return LT;
7294 else if (LW < RW) return RT;
7295
7296 // Otherwise, use the unsigned type of the signed type's rank.
7297 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7298 assert(L == SLL || R == SLL);
7299 return S.Context.UnsignedLongLongTy;
7300 }
7301
7302 /// \brief Helper method to factor out the common pattern of adding overloads
7303 /// for '++' and '--' builtin operators.
addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,bool HasVolatile,bool HasRestrict)7304 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7305 bool HasVolatile,
7306 bool HasRestrict) {
7307 QualType ParamTypes[2] = {
7308 S.Context.getLValueReferenceType(CandidateTy),
7309 S.Context.IntTy
7310 };
7311
7312 // Non-volatile version.
7313 if (Args.size() == 1)
7314 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7315 else
7316 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7317
7318 // Use a heuristic to reduce number of builtin candidates in the set:
7319 // add volatile version only if there are conversions to a volatile type.
7320 if (HasVolatile) {
7321 ParamTypes[0] =
7322 S.Context.getLValueReferenceType(
7323 S.Context.getVolatileType(CandidateTy));
7324 if (Args.size() == 1)
7325 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7326 else
7327 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7328 }
7329
7330 // Add restrict version only if there are conversions to a restrict type
7331 // and our candidate type is a non-restrict-qualified pointer.
7332 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7333 !CandidateTy.isRestrictQualified()) {
7334 ParamTypes[0]
7335 = S.Context.getLValueReferenceType(
7336 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7337 if (Args.size() == 1)
7338 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7339 else
7340 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7341
7342 if (HasVolatile) {
7343 ParamTypes[0]
7344 = S.Context.getLValueReferenceType(
7345 S.Context.getCVRQualifiedType(CandidateTy,
7346 (Qualifiers::Volatile |
7347 Qualifiers::Restrict)));
7348 if (Args.size() == 1)
7349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7350 else
7351 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7352 }
7353 }
7354
7355 }
7356
7357 public:
BuiltinOperatorOverloadBuilder(Sema & S,ArrayRef<Expr * > Args,Qualifiers VisibleTypeConversionsQuals,bool HasArithmeticOrEnumeralCandidateType,SmallVectorImpl<BuiltinCandidateTypeSet> & CandidateTypes,OverloadCandidateSet & CandidateSet)7358 BuiltinOperatorOverloadBuilder(
7359 Sema &S, ArrayRef<Expr *> Args,
7360 Qualifiers VisibleTypeConversionsQuals,
7361 bool HasArithmeticOrEnumeralCandidateType,
7362 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7363 OverloadCandidateSet &CandidateSet)
7364 : S(S), Args(Args),
7365 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7366 HasArithmeticOrEnumeralCandidateType(
7367 HasArithmeticOrEnumeralCandidateType),
7368 CandidateTypes(CandidateTypes),
7369 CandidateSet(CandidateSet) {
7370 // Validate some of our static helper constants in debug builds.
7371 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7372 "Invalid first promoted integral type");
7373 assert(getArithmeticType(LastPromotedIntegralType - 1)
7374 == S.Context.UnsignedInt128Ty &&
7375 "Invalid last promoted integral type");
7376 assert(getArithmeticType(FirstPromotedArithmeticType)
7377 == S.Context.FloatTy &&
7378 "Invalid first promoted arithmetic type");
7379 assert(getArithmeticType(LastPromotedArithmeticType - 1)
7380 == S.Context.UnsignedInt128Ty &&
7381 "Invalid last promoted arithmetic type");
7382 }
7383
7384 // C++ [over.built]p3:
7385 //
7386 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7387 // is either volatile or empty, there exist candidate operator
7388 // functions of the form
7389 //
7390 // VQ T& operator++(VQ T&);
7391 // T operator++(VQ T&, int);
7392 //
7393 // C++ [over.built]p4:
7394 //
7395 // For every pair (T, VQ), where T is an arithmetic type other
7396 // than bool, and VQ is either volatile or empty, there exist
7397 // candidate operator functions of the form
7398 //
7399 // VQ T& operator--(VQ T&);
7400 // T operator--(VQ T&, int);
addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op)7401 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7402 if (!HasArithmeticOrEnumeralCandidateType)
7403 return;
7404
7405 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7406 Arith < NumArithmeticTypes; ++Arith) {
7407 addPlusPlusMinusMinusStyleOverloads(
7408 getArithmeticType(Arith),
7409 VisibleTypeConversionsQuals.hasVolatile(),
7410 VisibleTypeConversionsQuals.hasRestrict());
7411 }
7412 }
7413
7414 // C++ [over.built]p5:
7415 //
7416 // For every pair (T, VQ), where T is a cv-qualified or
7417 // cv-unqualified object type, and VQ is either volatile or
7418 // empty, there exist candidate operator functions of the form
7419 //
7420 // T*VQ& operator++(T*VQ&);
7421 // T*VQ& operator--(T*VQ&);
7422 // T* operator++(T*VQ&, int);
7423 // T* operator--(T*VQ&, int);
addPlusPlusMinusMinusPointerOverloads()7424 void addPlusPlusMinusMinusPointerOverloads() {
7425 for (BuiltinCandidateTypeSet::iterator
7426 Ptr = CandidateTypes[0].pointer_begin(),
7427 PtrEnd = CandidateTypes[0].pointer_end();
7428 Ptr != PtrEnd; ++Ptr) {
7429 // Skip pointer types that aren't pointers to object types.
7430 if (!(*Ptr)->getPointeeType()->isObjectType())
7431 continue;
7432
7433 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7434 (!(*Ptr).isVolatileQualified() &&
7435 VisibleTypeConversionsQuals.hasVolatile()),
7436 (!(*Ptr).isRestrictQualified() &&
7437 VisibleTypeConversionsQuals.hasRestrict()));
7438 }
7439 }
7440
7441 // C++ [over.built]p6:
7442 // For every cv-qualified or cv-unqualified object type T, there
7443 // exist candidate operator functions of the form
7444 //
7445 // T& operator*(T*);
7446 //
7447 // C++ [over.built]p7:
7448 // For every function type T that does not have cv-qualifiers or a
7449 // ref-qualifier, there exist candidate operator functions of the form
7450 // T& operator*(T*);
addUnaryStarPointerOverloads()7451 void addUnaryStarPointerOverloads() {
7452 for (BuiltinCandidateTypeSet::iterator
7453 Ptr = CandidateTypes[0].pointer_begin(),
7454 PtrEnd = CandidateTypes[0].pointer_end();
7455 Ptr != PtrEnd; ++Ptr) {
7456 QualType ParamTy = *Ptr;
7457 QualType PointeeTy = ParamTy->getPointeeType();
7458 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7459 continue;
7460
7461 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7462 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7463 continue;
7464
7465 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7466 &ParamTy, Args, CandidateSet);
7467 }
7468 }
7469
7470 // C++ [over.built]p9:
7471 // For every promoted arithmetic type T, there exist candidate
7472 // operator functions of the form
7473 //
7474 // T operator+(T);
7475 // T operator-(T);
addUnaryPlusOrMinusArithmeticOverloads()7476 void addUnaryPlusOrMinusArithmeticOverloads() {
7477 if (!HasArithmeticOrEnumeralCandidateType)
7478 return;
7479
7480 for (unsigned Arith = FirstPromotedArithmeticType;
7481 Arith < LastPromotedArithmeticType; ++Arith) {
7482 QualType ArithTy = getArithmeticType(Arith);
7483 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7484 }
7485
7486 // Extension: We also add these operators for vector types.
7487 for (BuiltinCandidateTypeSet::iterator
7488 Vec = CandidateTypes[0].vector_begin(),
7489 VecEnd = CandidateTypes[0].vector_end();
7490 Vec != VecEnd; ++Vec) {
7491 QualType VecTy = *Vec;
7492 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7493 }
7494 }
7495
7496 // C++ [over.built]p8:
7497 // For every type T, there exist candidate operator functions of
7498 // the form
7499 //
7500 // T* operator+(T*);
addUnaryPlusPointerOverloads()7501 void addUnaryPlusPointerOverloads() {
7502 for (BuiltinCandidateTypeSet::iterator
7503 Ptr = CandidateTypes[0].pointer_begin(),
7504 PtrEnd = CandidateTypes[0].pointer_end();
7505 Ptr != PtrEnd; ++Ptr) {
7506 QualType ParamTy = *Ptr;
7507 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7508 }
7509 }
7510
7511 // C++ [over.built]p10:
7512 // For every promoted integral type T, there exist candidate
7513 // operator functions of the form
7514 //
7515 // T operator~(T);
addUnaryTildePromotedIntegralOverloads()7516 void addUnaryTildePromotedIntegralOverloads() {
7517 if (!HasArithmeticOrEnumeralCandidateType)
7518 return;
7519
7520 for (unsigned Int = FirstPromotedIntegralType;
7521 Int < LastPromotedIntegralType; ++Int) {
7522 QualType IntTy = getArithmeticType(Int);
7523 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7524 }
7525
7526 // Extension: We also add this operator for vector types.
7527 for (BuiltinCandidateTypeSet::iterator
7528 Vec = CandidateTypes[0].vector_begin(),
7529 VecEnd = CandidateTypes[0].vector_end();
7530 Vec != VecEnd; ++Vec) {
7531 QualType VecTy = *Vec;
7532 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7533 }
7534 }
7535
7536 // C++ [over.match.oper]p16:
7537 // For every pointer to member type T, there exist candidate operator
7538 // functions of the form
7539 //
7540 // bool operator==(T,T);
7541 // bool operator!=(T,T);
addEqualEqualOrNotEqualMemberPointerOverloads()7542 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7543 /// Set of (canonical) types that we've already handled.
7544 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7545
7546 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7547 for (BuiltinCandidateTypeSet::iterator
7548 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7549 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7550 MemPtr != MemPtrEnd;
7551 ++MemPtr) {
7552 // Don't add the same builtin candidate twice.
7553 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7554 continue;
7555
7556 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7557 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7558 }
7559 }
7560 }
7561
7562 // C++ [over.built]p15:
7563 //
7564 // For every T, where T is an enumeration type, a pointer type, or
7565 // std::nullptr_t, there exist candidate operator functions of the form
7566 //
7567 // bool operator<(T, T);
7568 // bool operator>(T, T);
7569 // bool operator<=(T, T);
7570 // bool operator>=(T, T);
7571 // bool operator==(T, T);
7572 // bool operator!=(T, T);
addRelationalPointerOrEnumeralOverloads()7573 void addRelationalPointerOrEnumeralOverloads() {
7574 // C++ [over.match.oper]p3:
7575 // [...]the built-in candidates include all of the candidate operator
7576 // functions defined in 13.6 that, compared to the given operator, [...]
7577 // do not have the same parameter-type-list as any non-template non-member
7578 // candidate.
7579 //
7580 // Note that in practice, this only affects enumeration types because there
7581 // aren't any built-in candidates of record type, and a user-defined operator
7582 // must have an operand of record or enumeration type. Also, the only other
7583 // overloaded operator with enumeration arguments, operator=,
7584 // cannot be overloaded for enumeration types, so this is the only place
7585 // where we must suppress candidates like this.
7586 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7587 UserDefinedBinaryOperators;
7588
7589 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7590 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7591 CandidateTypes[ArgIdx].enumeration_end()) {
7592 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7593 CEnd = CandidateSet.end();
7594 C != CEnd; ++C) {
7595 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7596 continue;
7597
7598 if (C->Function->isFunctionTemplateSpecialization())
7599 continue;
7600
7601 QualType FirstParamType =
7602 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7603 QualType SecondParamType =
7604 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7605
7606 // Skip if either parameter isn't of enumeral type.
7607 if (!FirstParamType->isEnumeralType() ||
7608 !SecondParamType->isEnumeralType())
7609 continue;
7610
7611 // Add this operator to the set of known user-defined operators.
7612 UserDefinedBinaryOperators.insert(
7613 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7614 S.Context.getCanonicalType(SecondParamType)));
7615 }
7616 }
7617 }
7618
7619 /// Set of (canonical) types that we've already handled.
7620 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7621
7622 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7623 for (BuiltinCandidateTypeSet::iterator
7624 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7625 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7626 Ptr != PtrEnd; ++Ptr) {
7627 // Don't add the same builtin candidate twice.
7628 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7629 continue;
7630
7631 QualType ParamTypes[2] = { *Ptr, *Ptr };
7632 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7633 }
7634 for (BuiltinCandidateTypeSet::iterator
7635 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7636 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7637 Enum != EnumEnd; ++Enum) {
7638 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7639
7640 // Don't add the same builtin candidate twice, or if a user defined
7641 // candidate exists.
7642 if (!AddedTypes.insert(CanonType).second ||
7643 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7644 CanonType)))
7645 continue;
7646
7647 QualType ParamTypes[2] = { *Enum, *Enum };
7648 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7649 }
7650
7651 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7652 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7653 if (AddedTypes.insert(NullPtrTy).second &&
7654 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7655 NullPtrTy))) {
7656 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7657 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7658 CandidateSet);
7659 }
7660 }
7661 }
7662 }
7663
7664 // C++ [over.built]p13:
7665 //
7666 // For every cv-qualified or cv-unqualified object type T
7667 // there exist candidate operator functions of the form
7668 //
7669 // T* operator+(T*, ptrdiff_t);
7670 // T& operator[](T*, ptrdiff_t); [BELOW]
7671 // T* operator-(T*, ptrdiff_t);
7672 // T* operator+(ptrdiff_t, T*);
7673 // T& operator[](ptrdiff_t, T*); [BELOW]
7674 //
7675 // C++ [over.built]p14:
7676 //
7677 // For every T, where T is a pointer to object type, there
7678 // exist candidate operator functions of the form
7679 //
7680 // ptrdiff_t operator-(T, T);
addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op)7681 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7682 /// Set of (canonical) types that we've already handled.
7683 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7684
7685 for (int Arg = 0; Arg < 2; ++Arg) {
7686 QualType AsymmetricParamTypes[2] = {
7687 S.Context.getPointerDiffType(),
7688 S.Context.getPointerDiffType(),
7689 };
7690 for (BuiltinCandidateTypeSet::iterator
7691 Ptr = CandidateTypes[Arg].pointer_begin(),
7692 PtrEnd = CandidateTypes[Arg].pointer_end();
7693 Ptr != PtrEnd; ++Ptr) {
7694 QualType PointeeTy = (*Ptr)->getPointeeType();
7695 if (!PointeeTy->isObjectType())
7696 continue;
7697
7698 AsymmetricParamTypes[Arg] = *Ptr;
7699 if (Arg == 0 || Op == OO_Plus) {
7700 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7701 // T* operator+(ptrdiff_t, T*);
7702 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7703 }
7704 if (Op == OO_Minus) {
7705 // ptrdiff_t operator-(T, T);
7706 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7707 continue;
7708
7709 QualType ParamTypes[2] = { *Ptr, *Ptr };
7710 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7711 Args, CandidateSet);
7712 }
7713 }
7714 }
7715 }
7716
7717 // C++ [over.built]p12:
7718 //
7719 // For every pair of promoted arithmetic types L and R, there
7720 // exist candidate operator functions of the form
7721 //
7722 // LR operator*(L, R);
7723 // LR operator/(L, R);
7724 // LR operator+(L, R);
7725 // LR operator-(L, R);
7726 // bool operator<(L, R);
7727 // bool operator>(L, R);
7728 // bool operator<=(L, R);
7729 // bool operator>=(L, R);
7730 // bool operator==(L, R);
7731 // bool operator!=(L, R);
7732 //
7733 // where LR is the result of the usual arithmetic conversions
7734 // between types L and R.
7735 //
7736 // C++ [over.built]p24:
7737 //
7738 // For every pair of promoted arithmetic types L and R, there exist
7739 // candidate operator functions of the form
7740 //
7741 // LR operator?(bool, L, R);
7742 //
7743 // where LR is the result of the usual arithmetic conversions
7744 // between types L and R.
7745 // Our candidates ignore the first parameter.
addGenericBinaryArithmeticOverloads(bool isComparison)7746 void addGenericBinaryArithmeticOverloads(bool isComparison) {
7747 if (!HasArithmeticOrEnumeralCandidateType)
7748 return;
7749
7750 for (unsigned Left = FirstPromotedArithmeticType;
7751 Left < LastPromotedArithmeticType; ++Left) {
7752 for (unsigned Right = FirstPromotedArithmeticType;
7753 Right < LastPromotedArithmeticType; ++Right) {
7754 QualType LandR[2] = { getArithmeticType(Left),
7755 getArithmeticType(Right) };
7756 QualType Result =
7757 isComparison ? S.Context.BoolTy
7758 : getUsualArithmeticConversions(Left, Right);
7759 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7760 }
7761 }
7762
7763 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7764 // conditional operator for vector types.
7765 for (BuiltinCandidateTypeSet::iterator
7766 Vec1 = CandidateTypes[0].vector_begin(),
7767 Vec1End = CandidateTypes[0].vector_end();
7768 Vec1 != Vec1End; ++Vec1) {
7769 for (BuiltinCandidateTypeSet::iterator
7770 Vec2 = CandidateTypes[1].vector_begin(),
7771 Vec2End = CandidateTypes[1].vector_end();
7772 Vec2 != Vec2End; ++Vec2) {
7773 QualType LandR[2] = { *Vec1, *Vec2 };
7774 QualType Result = S.Context.BoolTy;
7775 if (!isComparison) {
7776 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7777 Result = *Vec1;
7778 else
7779 Result = *Vec2;
7780 }
7781
7782 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7783 }
7784 }
7785 }
7786
7787 // C++ [over.built]p17:
7788 //
7789 // For every pair of promoted integral types L and R, there
7790 // exist candidate operator functions of the form
7791 //
7792 // LR operator%(L, R);
7793 // LR operator&(L, R);
7794 // LR operator^(L, R);
7795 // LR operator|(L, R);
7796 // L operator<<(L, R);
7797 // L operator>>(L, R);
7798 //
7799 // where LR is the result of the usual arithmetic conversions
7800 // between types L and R.
addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op)7801 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7802 if (!HasArithmeticOrEnumeralCandidateType)
7803 return;
7804
7805 for (unsigned Left = FirstPromotedIntegralType;
7806 Left < LastPromotedIntegralType; ++Left) {
7807 for (unsigned Right = FirstPromotedIntegralType;
7808 Right < LastPromotedIntegralType; ++Right) {
7809 QualType LandR[2] = { getArithmeticType(Left),
7810 getArithmeticType(Right) };
7811 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7812 ? LandR[0]
7813 : getUsualArithmeticConversions(Left, Right);
7814 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7815 }
7816 }
7817 }
7818
7819 // C++ [over.built]p20:
7820 //
7821 // For every pair (T, VQ), where T is an enumeration or
7822 // pointer to member type and VQ is either volatile or
7823 // empty, there exist candidate operator functions of the form
7824 //
7825 // VQ T& operator=(VQ T&, T);
addAssignmentMemberPointerOrEnumeralOverloads()7826 void addAssignmentMemberPointerOrEnumeralOverloads() {
7827 /// Set of (canonical) types that we've already handled.
7828 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7829
7830 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7831 for (BuiltinCandidateTypeSet::iterator
7832 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7833 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7834 Enum != EnumEnd; ++Enum) {
7835 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7836 continue;
7837
7838 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7839 }
7840
7841 for (BuiltinCandidateTypeSet::iterator
7842 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7843 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7844 MemPtr != MemPtrEnd; ++MemPtr) {
7845 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7846 continue;
7847
7848 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7849 }
7850 }
7851 }
7852
7853 // C++ [over.built]p19:
7854 //
7855 // For every pair (T, VQ), where T is any type and VQ is either
7856 // volatile or empty, there exist candidate operator functions
7857 // of the form
7858 //
7859 // T*VQ& operator=(T*VQ&, T*);
7860 //
7861 // C++ [over.built]p21:
7862 //
7863 // For every pair (T, VQ), where T is a cv-qualified or
7864 // cv-unqualified object type and VQ is either volatile or
7865 // empty, there exist candidate operator functions of the form
7866 //
7867 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7868 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
addAssignmentPointerOverloads(bool isEqualOp)7869 void addAssignmentPointerOverloads(bool isEqualOp) {
7870 /// Set of (canonical) types that we've already handled.
7871 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7872
7873 for (BuiltinCandidateTypeSet::iterator
7874 Ptr = CandidateTypes[0].pointer_begin(),
7875 PtrEnd = CandidateTypes[0].pointer_end();
7876 Ptr != PtrEnd; ++Ptr) {
7877 // If this is operator=, keep track of the builtin candidates we added.
7878 if (isEqualOp)
7879 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7880 else if (!(*Ptr)->getPointeeType()->isObjectType())
7881 continue;
7882
7883 // non-volatile version
7884 QualType ParamTypes[2] = {
7885 S.Context.getLValueReferenceType(*Ptr),
7886 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7887 };
7888 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7889 /*IsAssigmentOperator=*/ isEqualOp);
7890
7891 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7892 VisibleTypeConversionsQuals.hasVolatile();
7893 if (NeedVolatile) {
7894 // volatile version
7895 ParamTypes[0] =
7896 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7897 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7898 /*IsAssigmentOperator=*/isEqualOp);
7899 }
7900
7901 if (!(*Ptr).isRestrictQualified() &&
7902 VisibleTypeConversionsQuals.hasRestrict()) {
7903 // restrict version
7904 ParamTypes[0]
7905 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7906 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7907 /*IsAssigmentOperator=*/isEqualOp);
7908
7909 if (NeedVolatile) {
7910 // volatile restrict version
7911 ParamTypes[0]
7912 = S.Context.getLValueReferenceType(
7913 S.Context.getCVRQualifiedType(*Ptr,
7914 (Qualifiers::Volatile |
7915 Qualifiers::Restrict)));
7916 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7917 /*IsAssigmentOperator=*/isEqualOp);
7918 }
7919 }
7920 }
7921
7922 if (isEqualOp) {
7923 for (BuiltinCandidateTypeSet::iterator
7924 Ptr = CandidateTypes[1].pointer_begin(),
7925 PtrEnd = CandidateTypes[1].pointer_end();
7926 Ptr != PtrEnd; ++Ptr) {
7927 // Make sure we don't add the same candidate twice.
7928 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7929 continue;
7930
7931 QualType ParamTypes[2] = {
7932 S.Context.getLValueReferenceType(*Ptr),
7933 *Ptr,
7934 };
7935
7936 // non-volatile version
7937 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7938 /*IsAssigmentOperator=*/true);
7939
7940 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7941 VisibleTypeConversionsQuals.hasVolatile();
7942 if (NeedVolatile) {
7943 // volatile version
7944 ParamTypes[0] =
7945 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7946 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7947 /*IsAssigmentOperator=*/true);
7948 }
7949
7950 if (!(*Ptr).isRestrictQualified() &&
7951 VisibleTypeConversionsQuals.hasRestrict()) {
7952 // restrict version
7953 ParamTypes[0]
7954 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7955 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7956 /*IsAssigmentOperator=*/true);
7957
7958 if (NeedVolatile) {
7959 // volatile restrict version
7960 ParamTypes[0]
7961 = S.Context.getLValueReferenceType(
7962 S.Context.getCVRQualifiedType(*Ptr,
7963 (Qualifiers::Volatile |
7964 Qualifiers::Restrict)));
7965 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7966 /*IsAssigmentOperator=*/true);
7967 }
7968 }
7969 }
7970 }
7971 }
7972
7973 // C++ [over.built]p18:
7974 //
7975 // For every triple (L, VQ, R), where L is an arithmetic type,
7976 // VQ is either volatile or empty, and R is a promoted
7977 // arithmetic type, there exist candidate operator functions of
7978 // the form
7979 //
7980 // VQ L& operator=(VQ L&, R);
7981 // VQ L& operator*=(VQ L&, R);
7982 // VQ L& operator/=(VQ L&, R);
7983 // VQ L& operator+=(VQ L&, R);
7984 // VQ L& operator-=(VQ L&, R);
addAssignmentArithmeticOverloads(bool isEqualOp)7985 void addAssignmentArithmeticOverloads(bool isEqualOp) {
7986 if (!HasArithmeticOrEnumeralCandidateType)
7987 return;
7988
7989 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7990 for (unsigned Right = FirstPromotedArithmeticType;
7991 Right < LastPromotedArithmeticType; ++Right) {
7992 QualType ParamTypes[2];
7993 ParamTypes[1] = getArithmeticType(Right);
7994
7995 // Add this built-in operator as a candidate (VQ is empty).
7996 ParamTypes[0] =
7997 S.Context.getLValueReferenceType(getArithmeticType(Left));
7998 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7999 /*IsAssigmentOperator=*/isEqualOp);
8000
8001 // Add this built-in operator as a candidate (VQ is 'volatile').
8002 if (VisibleTypeConversionsQuals.hasVolatile()) {
8003 ParamTypes[0] =
8004 S.Context.getVolatileType(getArithmeticType(Left));
8005 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8006 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8007 /*IsAssigmentOperator=*/isEqualOp);
8008 }
8009 }
8010 }
8011
8012 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8013 for (BuiltinCandidateTypeSet::iterator
8014 Vec1 = CandidateTypes[0].vector_begin(),
8015 Vec1End = CandidateTypes[0].vector_end();
8016 Vec1 != Vec1End; ++Vec1) {
8017 for (BuiltinCandidateTypeSet::iterator
8018 Vec2 = CandidateTypes[1].vector_begin(),
8019 Vec2End = CandidateTypes[1].vector_end();
8020 Vec2 != Vec2End; ++Vec2) {
8021 QualType ParamTypes[2];
8022 ParamTypes[1] = *Vec2;
8023 // Add this built-in operator as a candidate (VQ is empty).
8024 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8025 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8026 /*IsAssigmentOperator=*/isEqualOp);
8027
8028 // Add this built-in operator as a candidate (VQ is 'volatile').
8029 if (VisibleTypeConversionsQuals.hasVolatile()) {
8030 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8031 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8032 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8033 /*IsAssigmentOperator=*/isEqualOp);
8034 }
8035 }
8036 }
8037 }
8038
8039 // C++ [over.built]p22:
8040 //
8041 // For every triple (L, VQ, R), where L is an integral type, VQ
8042 // is either volatile or empty, and R is a promoted integral
8043 // type, there exist candidate operator functions of the form
8044 //
8045 // VQ L& operator%=(VQ L&, R);
8046 // VQ L& operator<<=(VQ L&, R);
8047 // VQ L& operator>>=(VQ L&, R);
8048 // VQ L& operator&=(VQ L&, R);
8049 // VQ L& operator^=(VQ L&, R);
8050 // VQ L& operator|=(VQ L&, R);
addAssignmentIntegralOverloads()8051 void addAssignmentIntegralOverloads() {
8052 if (!HasArithmeticOrEnumeralCandidateType)
8053 return;
8054
8055 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8056 for (unsigned Right = FirstPromotedIntegralType;
8057 Right < LastPromotedIntegralType; ++Right) {
8058 QualType ParamTypes[2];
8059 ParamTypes[1] = getArithmeticType(Right);
8060
8061 // Add this built-in operator as a candidate (VQ is empty).
8062 ParamTypes[0] =
8063 S.Context.getLValueReferenceType(getArithmeticType(Left));
8064 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8065 if (VisibleTypeConversionsQuals.hasVolatile()) {
8066 // Add this built-in operator as a candidate (VQ is 'volatile').
8067 ParamTypes[0] = getArithmeticType(Left);
8068 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8069 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8070 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8071 }
8072 }
8073 }
8074 }
8075
8076 // C++ [over.operator]p23:
8077 //
8078 // There also exist candidate operator functions of the form
8079 //
8080 // bool operator!(bool);
8081 // bool operator&&(bool, bool);
8082 // bool operator||(bool, bool);
addExclaimOverload()8083 void addExclaimOverload() {
8084 QualType ParamTy = S.Context.BoolTy;
8085 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8086 /*IsAssignmentOperator=*/false,
8087 /*NumContextualBoolArguments=*/1);
8088 }
addAmpAmpOrPipePipeOverload()8089 void addAmpAmpOrPipePipeOverload() {
8090 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8091 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8092 /*IsAssignmentOperator=*/false,
8093 /*NumContextualBoolArguments=*/2);
8094 }
8095
8096 // C++ [over.built]p13:
8097 //
8098 // For every cv-qualified or cv-unqualified object type T there
8099 // exist candidate operator functions of the form
8100 //
8101 // T* operator+(T*, ptrdiff_t); [ABOVE]
8102 // T& operator[](T*, ptrdiff_t);
8103 // T* operator-(T*, ptrdiff_t); [ABOVE]
8104 // T* operator+(ptrdiff_t, T*); [ABOVE]
8105 // T& operator[](ptrdiff_t, T*);
addSubscriptOverloads()8106 void addSubscriptOverloads() {
8107 for (BuiltinCandidateTypeSet::iterator
8108 Ptr = CandidateTypes[0].pointer_begin(),
8109 PtrEnd = CandidateTypes[0].pointer_end();
8110 Ptr != PtrEnd; ++Ptr) {
8111 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8112 QualType PointeeType = (*Ptr)->getPointeeType();
8113 if (!PointeeType->isObjectType())
8114 continue;
8115
8116 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8117
8118 // T& operator[](T*, ptrdiff_t)
8119 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8120 }
8121
8122 for (BuiltinCandidateTypeSet::iterator
8123 Ptr = CandidateTypes[1].pointer_begin(),
8124 PtrEnd = CandidateTypes[1].pointer_end();
8125 Ptr != PtrEnd; ++Ptr) {
8126 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8127 QualType PointeeType = (*Ptr)->getPointeeType();
8128 if (!PointeeType->isObjectType())
8129 continue;
8130
8131 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8132
8133 // T& operator[](ptrdiff_t, T*)
8134 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8135 }
8136 }
8137
8138 // C++ [over.built]p11:
8139 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8140 // C1 is the same type as C2 or is a derived class of C2, T is an object
8141 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8142 // there exist candidate operator functions of the form
8143 //
8144 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8145 //
8146 // where CV12 is the union of CV1 and CV2.
addArrowStarOverloads()8147 void addArrowStarOverloads() {
8148 for (BuiltinCandidateTypeSet::iterator
8149 Ptr = CandidateTypes[0].pointer_begin(),
8150 PtrEnd = CandidateTypes[0].pointer_end();
8151 Ptr != PtrEnd; ++Ptr) {
8152 QualType C1Ty = (*Ptr);
8153 QualType C1;
8154 QualifierCollector Q1;
8155 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8156 if (!isa<RecordType>(C1))
8157 continue;
8158 // heuristic to reduce number of builtin candidates in the set.
8159 // Add volatile/restrict version only if there are conversions to a
8160 // volatile/restrict type.
8161 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8162 continue;
8163 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8164 continue;
8165 for (BuiltinCandidateTypeSet::iterator
8166 MemPtr = CandidateTypes[1].member_pointer_begin(),
8167 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8168 MemPtr != MemPtrEnd; ++MemPtr) {
8169 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8170 QualType C2 = QualType(mptr->getClass(), 0);
8171 C2 = C2.getUnqualifiedType();
8172 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8173 break;
8174 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8175 // build CV12 T&
8176 QualType T = mptr->getPointeeType();
8177 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8178 T.isVolatileQualified())
8179 continue;
8180 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8181 T.isRestrictQualified())
8182 continue;
8183 T = Q1.apply(S.Context, T);
8184 QualType ResultTy = S.Context.getLValueReferenceType(T);
8185 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8186 }
8187 }
8188 }
8189
8190 // Note that we don't consider the first argument, since it has been
8191 // contextually converted to bool long ago. The candidates below are
8192 // therefore added as binary.
8193 //
8194 // C++ [over.built]p25:
8195 // For every type T, where T is a pointer, pointer-to-member, or scoped
8196 // enumeration type, there exist candidate operator functions of the form
8197 //
8198 // T operator?(bool, T, T);
8199 //
addConditionalOperatorOverloads()8200 void addConditionalOperatorOverloads() {
8201 /// Set of (canonical) types that we've already handled.
8202 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8203
8204 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8205 for (BuiltinCandidateTypeSet::iterator
8206 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8207 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8208 Ptr != PtrEnd; ++Ptr) {
8209 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8210 continue;
8211
8212 QualType ParamTypes[2] = { *Ptr, *Ptr };
8213 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8214 }
8215
8216 for (BuiltinCandidateTypeSet::iterator
8217 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8218 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8219 MemPtr != MemPtrEnd; ++MemPtr) {
8220 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8221 continue;
8222
8223 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8224 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8225 }
8226
8227 if (S.getLangOpts().CPlusPlus11) {
8228 for (BuiltinCandidateTypeSet::iterator
8229 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8230 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8231 Enum != EnumEnd; ++Enum) {
8232 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8233 continue;
8234
8235 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8236 continue;
8237
8238 QualType ParamTypes[2] = { *Enum, *Enum };
8239 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8240 }
8241 }
8242 }
8243 }
8244 };
8245
8246 } // end anonymous namespace
8247
8248 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8249 /// operator overloads to the candidate set (C++ [over.built]), based
8250 /// on the operator @p Op and the arguments given. For example, if the
8251 /// operator is a binary '+', this routine might add "int
8252 /// operator+(int, int)" to cover integer addition.
AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)8253 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8254 SourceLocation OpLoc,
8255 ArrayRef<Expr *> Args,
8256 OverloadCandidateSet &CandidateSet) {
8257 // Find all of the types that the arguments can convert to, but only
8258 // if the operator we're looking at has built-in operator candidates
8259 // that make use of these types. Also record whether we encounter non-record
8260 // candidate types or either arithmetic or enumeral candidate types.
8261 Qualifiers VisibleTypeConversionsQuals;
8262 VisibleTypeConversionsQuals.addConst();
8263 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8264 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8265
8266 bool HasNonRecordCandidateType = false;
8267 bool HasArithmeticOrEnumeralCandidateType = false;
8268 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8269 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8270 CandidateTypes.emplace_back(*this);
8271 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8272 OpLoc,
8273 true,
8274 (Op == OO_Exclaim ||
8275 Op == OO_AmpAmp ||
8276 Op == OO_PipePipe),
8277 VisibleTypeConversionsQuals);
8278 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8279 CandidateTypes[ArgIdx].hasNonRecordTypes();
8280 HasArithmeticOrEnumeralCandidateType =
8281 HasArithmeticOrEnumeralCandidateType ||
8282 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8283 }
8284
8285 // Exit early when no non-record types have been added to the candidate set
8286 // for any of the arguments to the operator.
8287 //
8288 // We can't exit early for !, ||, or &&, since there we have always have
8289 // 'bool' overloads.
8290 if (!HasNonRecordCandidateType &&
8291 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8292 return;
8293
8294 // Setup an object to manage the common state for building overloads.
8295 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8296 VisibleTypeConversionsQuals,
8297 HasArithmeticOrEnumeralCandidateType,
8298 CandidateTypes, CandidateSet);
8299
8300 // Dispatch over the operation to add in only those overloads which apply.
8301 switch (Op) {
8302 case OO_None:
8303 case NUM_OVERLOADED_OPERATORS:
8304 llvm_unreachable("Expected an overloaded operator");
8305
8306 case OO_New:
8307 case OO_Delete:
8308 case OO_Array_New:
8309 case OO_Array_Delete:
8310 case OO_Call:
8311 llvm_unreachable(
8312 "Special operators don't use AddBuiltinOperatorCandidates");
8313
8314 case OO_Comma:
8315 case OO_Arrow:
8316 case OO_Coawait:
8317 // C++ [over.match.oper]p3:
8318 // -- For the operator ',', the unary operator '&', the
8319 // operator '->', or the operator 'co_await', the
8320 // built-in candidates set is empty.
8321 break;
8322
8323 case OO_Plus: // '+' is either unary or binary
8324 if (Args.size() == 1)
8325 OpBuilder.addUnaryPlusPointerOverloads();
8326 // Fall through.
8327
8328 case OO_Minus: // '-' is either unary or binary
8329 if (Args.size() == 1) {
8330 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8331 } else {
8332 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8333 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8334 }
8335 break;
8336
8337 case OO_Star: // '*' is either unary or binary
8338 if (Args.size() == 1)
8339 OpBuilder.addUnaryStarPointerOverloads();
8340 else
8341 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8342 break;
8343
8344 case OO_Slash:
8345 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8346 break;
8347
8348 case OO_PlusPlus:
8349 case OO_MinusMinus:
8350 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8351 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8352 break;
8353
8354 case OO_EqualEqual:
8355 case OO_ExclaimEqual:
8356 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8357 // Fall through.
8358
8359 case OO_Less:
8360 case OO_Greater:
8361 case OO_LessEqual:
8362 case OO_GreaterEqual:
8363 OpBuilder.addRelationalPointerOrEnumeralOverloads();
8364 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8365 break;
8366
8367 case OO_Percent:
8368 case OO_Caret:
8369 case OO_Pipe:
8370 case OO_LessLess:
8371 case OO_GreaterGreater:
8372 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8373 break;
8374
8375 case OO_Amp: // '&' is either unary or binary
8376 if (Args.size() == 1)
8377 // C++ [over.match.oper]p3:
8378 // -- For the operator ',', the unary operator '&', or the
8379 // operator '->', the built-in candidates set is empty.
8380 break;
8381
8382 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8383 break;
8384
8385 case OO_Tilde:
8386 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8387 break;
8388
8389 case OO_Equal:
8390 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8391 // Fall through.
8392
8393 case OO_PlusEqual:
8394 case OO_MinusEqual:
8395 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8396 // Fall through.
8397
8398 case OO_StarEqual:
8399 case OO_SlashEqual:
8400 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8401 break;
8402
8403 case OO_PercentEqual:
8404 case OO_LessLessEqual:
8405 case OO_GreaterGreaterEqual:
8406 case OO_AmpEqual:
8407 case OO_CaretEqual:
8408 case OO_PipeEqual:
8409 OpBuilder.addAssignmentIntegralOverloads();
8410 break;
8411
8412 case OO_Exclaim:
8413 OpBuilder.addExclaimOverload();
8414 break;
8415
8416 case OO_AmpAmp:
8417 case OO_PipePipe:
8418 OpBuilder.addAmpAmpOrPipePipeOverload();
8419 break;
8420
8421 case OO_Subscript:
8422 OpBuilder.addSubscriptOverloads();
8423 break;
8424
8425 case OO_ArrowStar:
8426 OpBuilder.addArrowStarOverloads();
8427 break;
8428
8429 case OO_Conditional:
8430 OpBuilder.addConditionalOperatorOverloads();
8431 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8432 break;
8433 }
8434 }
8435
8436 /// \brief Add function candidates found via argument-dependent lookup
8437 /// to the set of overloading candidates.
8438 ///
8439 /// This routine performs argument-dependent name lookup based on the
8440 /// given function name (which may also be an operator name) and adds
8441 /// all of the overload candidates found by ADL to the overload
8442 /// candidate set (C++ [basic.lookup.argdep]).
8443 void
AddArgumentDependentLookupCandidates(DeclarationName Name,SourceLocation Loc,ArrayRef<Expr * > Args,TemplateArgumentListInfo * ExplicitTemplateArgs,OverloadCandidateSet & CandidateSet,bool PartialOverloading)8444 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8445 SourceLocation Loc,
8446 ArrayRef<Expr *> Args,
8447 TemplateArgumentListInfo *ExplicitTemplateArgs,
8448 OverloadCandidateSet& CandidateSet,
8449 bool PartialOverloading) {
8450 ADLResult Fns;
8451
8452 // FIXME: This approach for uniquing ADL results (and removing
8453 // redundant candidates from the set) relies on pointer-equality,
8454 // which means we need to key off the canonical decl. However,
8455 // always going back to the canonical decl might not get us the
8456 // right set of default arguments. What default arguments are
8457 // we supposed to consider on ADL candidates, anyway?
8458
8459 // FIXME: Pass in the explicit template arguments?
8460 ArgumentDependentLookup(Name, Loc, Args, Fns);
8461
8462 // Erase all of the candidates we already knew about.
8463 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8464 CandEnd = CandidateSet.end();
8465 Cand != CandEnd; ++Cand)
8466 if (Cand->Function) {
8467 Fns.erase(Cand->Function);
8468 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8469 Fns.erase(FunTmpl);
8470 }
8471
8472 // For each of the ADL candidates we found, add it to the overload
8473 // set.
8474 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8475 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8476 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8477 if (ExplicitTemplateArgs)
8478 continue;
8479
8480 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8481 PartialOverloading);
8482 } else
8483 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8484 FoundDecl, ExplicitTemplateArgs,
8485 Args, CandidateSet, PartialOverloading);
8486 }
8487 }
8488
8489 namespace {
8490 enum class Comparison { Equal, Better, Worse };
8491 }
8492
8493 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8494 /// overload resolution.
8495 ///
8496 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8497 /// Cand1's first N enable_if attributes have precisely the same conditions as
8498 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8499 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8500 ///
8501 /// Note that you can have a pair of candidates such that Cand1's enable_if
8502 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8503 /// worse than Cand1's.
compareEnableIfAttrs(const Sema & S,const FunctionDecl * Cand1,const FunctionDecl * Cand2)8504 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8505 const FunctionDecl *Cand2) {
8506 // Common case: One (or both) decls don't have enable_if attrs.
8507 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8508 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8509 if (!Cand1Attr || !Cand2Attr) {
8510 if (Cand1Attr == Cand2Attr)
8511 return Comparison::Equal;
8512 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8513 }
8514
8515 // FIXME: The next several lines are just
8516 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8517 // instead of reverse order which is how they're stored in the AST.
8518 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8519 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8520
8521 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8522 // has fewer enable_if attributes than Cand2.
8523 if (Cand1Attrs.size() < Cand2Attrs.size())
8524 return Comparison::Worse;
8525
8526 auto Cand1I = Cand1Attrs.begin();
8527 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8528 for (auto &Cand2A : Cand2Attrs) {
8529 Cand1ID.clear();
8530 Cand2ID.clear();
8531
8532 auto &Cand1A = *Cand1I++;
8533 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8534 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8535 if (Cand1ID != Cand2ID)
8536 return Comparison::Worse;
8537 }
8538
8539 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8540 }
8541
8542 /// isBetterOverloadCandidate - Determines whether the first overload
8543 /// candidate is a better candidate than the second (C++ 13.3.3p1).
isBetterOverloadCandidate(Sema & S,const OverloadCandidate & Cand1,const OverloadCandidate & Cand2,SourceLocation Loc,bool UserDefinedConversion)8544 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8545 const OverloadCandidate &Cand2,
8546 SourceLocation Loc,
8547 bool UserDefinedConversion) {
8548 // Define viable functions to be better candidates than non-viable
8549 // functions.
8550 if (!Cand2.Viable)
8551 return Cand1.Viable;
8552 else if (!Cand1.Viable)
8553 return false;
8554
8555 // C++ [over.match.best]p1:
8556 //
8557 // -- if F is a static member function, ICS1(F) is defined such
8558 // that ICS1(F) is neither better nor worse than ICS1(G) for
8559 // any function G, and, symmetrically, ICS1(G) is neither
8560 // better nor worse than ICS1(F).
8561 unsigned StartArg = 0;
8562 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8563 StartArg = 1;
8564
8565 // C++ [over.match.best]p1:
8566 // A viable function F1 is defined to be a better function than another
8567 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
8568 // conversion sequence than ICSi(F2), and then...
8569 unsigned NumArgs = Cand1.NumConversions;
8570 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8571 bool HasBetterConversion = false;
8572 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8573 switch (CompareImplicitConversionSequences(S, Loc,
8574 Cand1.Conversions[ArgIdx],
8575 Cand2.Conversions[ArgIdx])) {
8576 case ImplicitConversionSequence::Better:
8577 // Cand1 has a better conversion sequence.
8578 HasBetterConversion = true;
8579 break;
8580
8581 case ImplicitConversionSequence::Worse:
8582 // Cand1 can't be better than Cand2.
8583 return false;
8584
8585 case ImplicitConversionSequence::Indistinguishable:
8586 // Do nothing.
8587 break;
8588 }
8589 }
8590
8591 // -- for some argument j, ICSj(F1) is a better conversion sequence than
8592 // ICSj(F2), or, if not that,
8593 if (HasBetterConversion)
8594 return true;
8595
8596 // -- the context is an initialization by user-defined conversion
8597 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8598 // from the return type of F1 to the destination type (i.e.,
8599 // the type of the entity being initialized) is a better
8600 // conversion sequence than the standard conversion sequence
8601 // from the return type of F2 to the destination type.
8602 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8603 isa<CXXConversionDecl>(Cand1.Function) &&
8604 isa<CXXConversionDecl>(Cand2.Function)) {
8605 // First check whether we prefer one of the conversion functions over the
8606 // other. This only distinguishes the results in non-standard, extension
8607 // cases such as the conversion from a lambda closure type to a function
8608 // pointer or block.
8609 ImplicitConversionSequence::CompareKind Result =
8610 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8611 if (Result == ImplicitConversionSequence::Indistinguishable)
8612 Result = CompareStandardConversionSequences(S, Loc,
8613 Cand1.FinalConversion,
8614 Cand2.FinalConversion);
8615
8616 if (Result != ImplicitConversionSequence::Indistinguishable)
8617 return Result == ImplicitConversionSequence::Better;
8618
8619 // FIXME: Compare kind of reference binding if conversion functions
8620 // convert to a reference type used in direct reference binding, per
8621 // C++14 [over.match.best]p1 section 2 bullet 3.
8622 }
8623
8624 // -- F1 is a non-template function and F2 is a function template
8625 // specialization, or, if not that,
8626 bool Cand1IsSpecialization = Cand1.Function &&
8627 Cand1.Function->getPrimaryTemplate();
8628 bool Cand2IsSpecialization = Cand2.Function &&
8629 Cand2.Function->getPrimaryTemplate();
8630 if (Cand1IsSpecialization != Cand2IsSpecialization)
8631 return Cand2IsSpecialization;
8632
8633 // -- F1 and F2 are function template specializations, and the function
8634 // template for F1 is more specialized than the template for F2
8635 // according to the partial ordering rules described in 14.5.5.2, or,
8636 // if not that,
8637 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8638 if (FunctionTemplateDecl *BetterTemplate
8639 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8640 Cand2.Function->getPrimaryTemplate(),
8641 Loc,
8642 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8643 : TPOC_Call,
8644 Cand1.ExplicitCallArguments,
8645 Cand2.ExplicitCallArguments))
8646 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8647 }
8648
8649 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8650 // A derived-class constructor beats an (inherited) base class constructor.
8651 bool Cand1IsInherited =
8652 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8653 bool Cand2IsInherited =
8654 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8655 if (Cand1IsInherited != Cand2IsInherited)
8656 return Cand2IsInherited;
8657 else if (Cand1IsInherited) {
8658 assert(Cand2IsInherited);
8659 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8660 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8661 if (Cand1Class->isDerivedFrom(Cand2Class))
8662 return true;
8663 if (Cand2Class->isDerivedFrom(Cand1Class))
8664 return false;
8665 // Inherited from sibling base classes: still ambiguous.
8666 }
8667
8668 // Check for enable_if value-based overload resolution.
8669 if (Cand1.Function && Cand2.Function) {
8670 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8671 if (Cmp != Comparison::Equal)
8672 return Cmp == Comparison::Better;
8673 }
8674
8675 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8676 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8677 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8678 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8679 }
8680
8681 bool HasPS1 = Cand1.Function != nullptr &&
8682 functionHasPassObjectSizeParams(Cand1.Function);
8683 bool HasPS2 = Cand2.Function != nullptr &&
8684 functionHasPassObjectSizeParams(Cand2.Function);
8685 return HasPS1 != HasPS2 && HasPS1;
8686 }
8687
8688 /// Determine whether two declarations are "equivalent" for the purposes of
8689 /// name lookup and overload resolution. This applies when the same internal/no
8690 /// linkage entity is defined by two modules (probably by textually including
8691 /// the same header). In such a case, we don't consider the declarations to
8692 /// declare the same entity, but we also don't want lookups with both
8693 /// declarations visible to be ambiguous in some cases (this happens when using
8694 /// a modularized libstdc++).
isEquivalentInternalLinkageDeclaration(const NamedDecl * A,const NamedDecl * B)8695 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8696 const NamedDecl *B) {
8697 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8698 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8699 if (!VA || !VB)
8700 return false;
8701
8702 // The declarations must be declaring the same name as an internal linkage
8703 // entity in different modules.
8704 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8705 VB->getDeclContext()->getRedeclContext()) ||
8706 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8707 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8708 VA->isExternallyVisible() || VB->isExternallyVisible())
8709 return false;
8710
8711 // Check that the declarations appear to be equivalent.
8712 //
8713 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8714 // For constants and functions, we should check the initializer or body is
8715 // the same. For non-constant variables, we shouldn't allow it at all.
8716 if (Context.hasSameType(VA->getType(), VB->getType()))
8717 return true;
8718
8719 // Enum constants within unnamed enumerations will have different types, but
8720 // may still be similar enough to be interchangeable for our purposes.
8721 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8722 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8723 // Only handle anonymous enums. If the enumerations were named and
8724 // equivalent, they would have been merged to the same type.
8725 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8726 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8727 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8728 !Context.hasSameType(EnumA->getIntegerType(),
8729 EnumB->getIntegerType()))
8730 return false;
8731 // Allow this only if the value is the same for both enumerators.
8732 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8733 }
8734 }
8735
8736 // Nothing else is sufficiently similar.
8737 return false;
8738 }
8739
diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc,const NamedDecl * D,ArrayRef<const NamedDecl * > Equiv)8740 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8741 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8742 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8743
8744 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8745 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8746 << !M << (M ? M->getFullModuleName() : "");
8747
8748 for (auto *E : Equiv) {
8749 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8750 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8751 << !M << (M ? M->getFullModuleName() : "");
8752 }
8753 }
8754
8755 /// \brief Computes the best viable function (C++ 13.3.3)
8756 /// within an overload candidate set.
8757 ///
8758 /// \param Loc The location of the function name (or operator symbol) for
8759 /// which overload resolution occurs.
8760 ///
8761 /// \param Best If overload resolution was successful or found a deleted
8762 /// function, \p Best points to the candidate function found.
8763 ///
8764 /// \returns The result of overload resolution.
8765 OverloadingResult
BestViableFunction(Sema & S,SourceLocation Loc,iterator & Best,bool UserDefinedConversion)8766 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8767 iterator &Best,
8768 bool UserDefinedConversion) {
8769 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8770 std::transform(begin(), end(), std::back_inserter(Candidates),
8771 [](OverloadCandidate &Cand) { return &Cand; });
8772
8773 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA
8774 // but accepted by both clang and NVCC. However during a particular
8775 // compilation mode only one call variant is viable. We need to
8776 // exclude non-viable overload candidates from consideration based
8777 // only on their host/device attributes. Specifically, if one
8778 // candidate call is WrongSide and the other is SameSide, we ignore
8779 // the WrongSide candidate.
8780 if (S.getLangOpts().CUDA) {
8781 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8782 bool ContainsSameSideCandidate =
8783 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8784 return Cand->Function &&
8785 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8786 Sema::CFP_SameSide;
8787 });
8788 if (ContainsSameSideCandidate) {
8789 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8790 return Cand->Function &&
8791 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8792 Sema::CFP_WrongSide;
8793 };
8794 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8795 IsWrongSideCandidate),
8796 Candidates.end());
8797 }
8798 }
8799
8800 // Find the best viable function.
8801 Best = end();
8802 for (auto *Cand : Candidates)
8803 if (Cand->Viable)
8804 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8805 UserDefinedConversion))
8806 Best = Cand;
8807
8808 // If we didn't find any viable functions, abort.
8809 if (Best == end())
8810 return OR_No_Viable_Function;
8811
8812 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8813
8814 // Make sure that this function is better than every other viable
8815 // function. If not, we have an ambiguity.
8816 for (auto *Cand : Candidates) {
8817 if (Cand->Viable &&
8818 Cand != Best &&
8819 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8820 UserDefinedConversion)) {
8821 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8822 Cand->Function)) {
8823 EquivalentCands.push_back(Cand->Function);
8824 continue;
8825 }
8826
8827 Best = end();
8828 return OR_Ambiguous;
8829 }
8830 }
8831
8832 // Best is the best viable function.
8833 if (Best->Function &&
8834 (Best->Function->isDeleted() ||
8835 S.isFunctionConsideredUnavailable(Best->Function)))
8836 return OR_Deleted;
8837
8838 if (!EquivalentCands.empty())
8839 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8840 EquivalentCands);
8841
8842 return OR_Success;
8843 }
8844
8845 namespace {
8846
8847 enum OverloadCandidateKind {
8848 oc_function,
8849 oc_method,
8850 oc_constructor,
8851 oc_function_template,
8852 oc_method_template,
8853 oc_constructor_template,
8854 oc_implicit_default_constructor,
8855 oc_implicit_copy_constructor,
8856 oc_implicit_move_constructor,
8857 oc_implicit_copy_assignment,
8858 oc_implicit_move_assignment,
8859 oc_inherited_constructor,
8860 oc_inherited_constructor_template
8861 };
8862
ClassifyOverloadCandidate(Sema & S,NamedDecl * Found,FunctionDecl * Fn,std::string & Description)8863 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8864 NamedDecl *Found,
8865 FunctionDecl *Fn,
8866 std::string &Description) {
8867 bool isTemplate = false;
8868
8869 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8870 isTemplate = true;
8871 Description = S.getTemplateArgumentBindingsText(
8872 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8873 }
8874
8875 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8876 if (!Ctor->isImplicit()) {
8877 if (isa<ConstructorUsingShadowDecl>(Found))
8878 return isTemplate ? oc_inherited_constructor_template
8879 : oc_inherited_constructor;
8880 else
8881 return isTemplate ? oc_constructor_template : oc_constructor;
8882 }
8883
8884 if (Ctor->isDefaultConstructor())
8885 return oc_implicit_default_constructor;
8886
8887 if (Ctor->isMoveConstructor())
8888 return oc_implicit_move_constructor;
8889
8890 assert(Ctor->isCopyConstructor() &&
8891 "unexpected sort of implicit constructor");
8892 return oc_implicit_copy_constructor;
8893 }
8894
8895 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8896 // This actually gets spelled 'candidate function' for now, but
8897 // it doesn't hurt to split it out.
8898 if (!Meth->isImplicit())
8899 return isTemplate ? oc_method_template : oc_method;
8900
8901 if (Meth->isMoveAssignmentOperator())
8902 return oc_implicit_move_assignment;
8903
8904 if (Meth->isCopyAssignmentOperator())
8905 return oc_implicit_copy_assignment;
8906
8907 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8908 return oc_method;
8909 }
8910
8911 return isTemplate ? oc_function_template : oc_function;
8912 }
8913
MaybeEmitInheritedConstructorNote(Sema & S,Decl * FoundDecl)8914 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
8915 // FIXME: It'd be nice to only emit a note once per using-decl per overload
8916 // set.
8917 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
8918 S.Diag(FoundDecl->getLocation(),
8919 diag::note_ovl_candidate_inherited_constructor)
8920 << Shadow->getNominatedBaseClass();
8921 }
8922
8923 } // end anonymous namespace
8924
isFunctionAlwaysEnabled(const ASTContext & Ctx,const FunctionDecl * FD)8925 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8926 const FunctionDecl *FD) {
8927 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8928 bool AlwaysTrue;
8929 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8930 return false;
8931 if (!AlwaysTrue)
8932 return false;
8933 }
8934 return true;
8935 }
8936
8937 /// \brief Returns true if we can take the address of the function.
8938 ///
8939 /// \param Complain - If true, we'll emit a diagnostic
8940 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8941 /// we in overload resolution?
8942 /// \param Loc - The location of the statement we're complaining about. Ignored
8943 /// if we're not complaining, or if we're in overload resolution.
checkAddressOfFunctionIsAvailable(Sema & S,const FunctionDecl * FD,bool Complain,bool InOverloadResolution,SourceLocation Loc)8944 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8945 bool Complain,
8946 bool InOverloadResolution,
8947 SourceLocation Loc) {
8948 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8949 if (Complain) {
8950 if (InOverloadResolution)
8951 S.Diag(FD->getLocStart(),
8952 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8953 else
8954 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8955 }
8956 return false;
8957 }
8958
8959 auto I = llvm::find_if(
8960 FD->parameters(), std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8961 if (I == FD->param_end())
8962 return true;
8963
8964 if (Complain) {
8965 // Add one to ParamNo because it's user-facing
8966 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8967 if (InOverloadResolution)
8968 S.Diag(FD->getLocation(),
8969 diag::note_ovl_candidate_has_pass_object_size_params)
8970 << ParamNo;
8971 else
8972 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8973 << FD << ParamNo;
8974 }
8975 return false;
8976 }
8977
checkAddressOfCandidateIsAvailable(Sema & S,const FunctionDecl * FD)8978 static bool checkAddressOfCandidateIsAvailable(Sema &S,
8979 const FunctionDecl *FD) {
8980 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8981 /*InOverloadResolution=*/true,
8982 /*Loc=*/SourceLocation());
8983 }
8984
checkAddressOfFunctionIsAvailable(const FunctionDecl * Function,bool Complain,SourceLocation Loc)8985 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8986 bool Complain,
8987 SourceLocation Loc) {
8988 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8989 /*InOverloadResolution=*/false,
8990 Loc);
8991 }
8992
8993 // Notes the location of an overload candidate.
NoteOverloadCandidate(NamedDecl * Found,FunctionDecl * Fn,QualType DestType,bool TakingAddress)8994 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
8995 QualType DestType, bool TakingAddress) {
8996 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8997 return;
8998
8999 std::string FnDesc;
9000 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9001 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9002 << (unsigned) K << FnDesc;
9003
9004 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9005 Diag(Fn->getLocation(), PD);
9006 MaybeEmitInheritedConstructorNote(*this, Found);
9007 }
9008
9009 // Notes the location of all overload candidates designated through
9010 // OverloadedExpr
NoteAllOverloadCandidates(Expr * OverloadedExpr,QualType DestType,bool TakingAddress)9011 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9012 bool TakingAddress) {
9013 assert(OverloadedExpr->getType() == Context.OverloadTy);
9014
9015 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9016 OverloadExpr *OvlExpr = Ovl.Expression;
9017
9018 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9019 IEnd = OvlExpr->decls_end();
9020 I != IEnd; ++I) {
9021 if (FunctionTemplateDecl *FunTmpl =
9022 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9023 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9024 TakingAddress);
9025 } else if (FunctionDecl *Fun
9026 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9027 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9028 }
9029 }
9030 }
9031
9032 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
9033 /// "lead" diagnostic; it will be given two arguments, the source and
9034 /// target types of the conversion.
DiagnoseAmbiguousConversion(Sema & S,SourceLocation CaretLoc,const PartialDiagnostic & PDiag) const9035 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9036 Sema &S,
9037 SourceLocation CaretLoc,
9038 const PartialDiagnostic &PDiag) const {
9039 S.Diag(CaretLoc, PDiag)
9040 << Ambiguous.getFromType() << Ambiguous.getToType();
9041 // FIXME: The note limiting machinery is borrowed from
9042 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9043 // refactoring here.
9044 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9045 unsigned CandsShown = 0;
9046 AmbiguousConversionSequence::const_iterator I, E;
9047 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9048 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9049 break;
9050 ++CandsShown;
9051 S.NoteOverloadCandidate(I->first, I->second);
9052 }
9053 if (I != E)
9054 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9055 }
9056
DiagnoseBadConversion(Sema & S,OverloadCandidate * Cand,unsigned I,bool TakingCandidateAddress)9057 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9058 unsigned I, bool TakingCandidateAddress) {
9059 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9060 assert(Conv.isBad());
9061 assert(Cand->Function && "for now, candidate must be a function");
9062 FunctionDecl *Fn = Cand->Function;
9063
9064 // There's a conversion slot for the object argument if this is a
9065 // non-constructor method. Note that 'I' corresponds the
9066 // conversion-slot index.
9067 bool isObjectArgument = false;
9068 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9069 if (I == 0)
9070 isObjectArgument = true;
9071 else
9072 I--;
9073 }
9074
9075 std::string FnDesc;
9076 OverloadCandidateKind FnKind =
9077 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9078
9079 Expr *FromExpr = Conv.Bad.FromExpr;
9080 QualType FromTy = Conv.Bad.getFromType();
9081 QualType ToTy = Conv.Bad.getToType();
9082
9083 if (FromTy == S.Context.OverloadTy) {
9084 assert(FromExpr && "overload set argument came from implicit argument?");
9085 Expr *E = FromExpr->IgnoreParens();
9086 if (isa<UnaryOperator>(E))
9087 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9088 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9089
9090 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9091 << (unsigned) FnKind << FnDesc
9092 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9093 << ToTy << Name << I+1;
9094 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9095 return;
9096 }
9097
9098 // Do some hand-waving analysis to see if the non-viability is due
9099 // to a qualifier mismatch.
9100 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9101 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9102 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9103 CToTy = RT->getPointeeType();
9104 else {
9105 // TODO: detect and diagnose the full richness of const mismatches.
9106 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9107 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9108 CFromTy = FromPT->getPointeeType();
9109 CToTy = ToPT->getPointeeType();
9110 }
9111 }
9112
9113 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9114 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9115 Qualifiers FromQs = CFromTy.getQualifiers();
9116 Qualifiers ToQs = CToTy.getQualifiers();
9117
9118 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9119 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9120 << (unsigned) FnKind << FnDesc
9121 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9122 << FromTy
9123 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9124 << (unsigned) isObjectArgument << I+1;
9125 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9126 return;
9127 }
9128
9129 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9130 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9131 << (unsigned) FnKind << FnDesc
9132 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9133 << FromTy
9134 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9135 << (unsigned) isObjectArgument << I+1;
9136 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9137 return;
9138 }
9139
9140 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9141 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9142 << (unsigned) FnKind << FnDesc
9143 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9144 << FromTy
9145 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9146 << (unsigned) isObjectArgument << I+1;
9147 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9148 return;
9149 }
9150
9151 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9153 << (unsigned) FnKind << FnDesc
9154 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9155 << FromTy << FromQs.hasUnaligned() << I+1;
9156 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9157 return;
9158 }
9159
9160 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9161 assert(CVR && "unexpected qualifiers mismatch");
9162
9163 if (isObjectArgument) {
9164 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9165 << (unsigned) FnKind << FnDesc
9166 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9167 << FromTy << (CVR - 1);
9168 } else {
9169 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9170 << (unsigned) FnKind << FnDesc
9171 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9172 << FromTy << (CVR - 1) << I+1;
9173 }
9174 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9175 return;
9176 }
9177
9178 // Special diagnostic for failure to convert an initializer list, since
9179 // telling the user that it has type void is not useful.
9180 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9181 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9182 << (unsigned) FnKind << FnDesc
9183 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9184 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9185 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9186 return;
9187 }
9188
9189 // Diagnose references or pointers to incomplete types differently,
9190 // since it's far from impossible that the incompleteness triggered
9191 // the failure.
9192 QualType TempFromTy = FromTy.getNonReferenceType();
9193 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9194 TempFromTy = PTy->getPointeeType();
9195 if (TempFromTy->isIncompleteType()) {
9196 // Emit the generic diagnostic and, optionally, add the hints to it.
9197 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9198 << (unsigned) FnKind << FnDesc
9199 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9200 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9201 << (unsigned) (Cand->Fix.Kind);
9202
9203 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9204 return;
9205 }
9206
9207 // Diagnose base -> derived pointer conversions.
9208 unsigned BaseToDerivedConversion = 0;
9209 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9210 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9211 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9212 FromPtrTy->getPointeeType()) &&
9213 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9214 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9215 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9216 FromPtrTy->getPointeeType()))
9217 BaseToDerivedConversion = 1;
9218 }
9219 } else if (const ObjCObjectPointerType *FromPtrTy
9220 = FromTy->getAs<ObjCObjectPointerType>()) {
9221 if (const ObjCObjectPointerType *ToPtrTy
9222 = ToTy->getAs<ObjCObjectPointerType>())
9223 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9224 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9225 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9226 FromPtrTy->getPointeeType()) &&
9227 FromIface->isSuperClassOf(ToIface))
9228 BaseToDerivedConversion = 2;
9229 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9230 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9231 !FromTy->isIncompleteType() &&
9232 !ToRefTy->getPointeeType()->isIncompleteType() &&
9233 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9234 BaseToDerivedConversion = 3;
9235 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9236 ToTy.getNonReferenceType().getCanonicalType() ==
9237 FromTy.getNonReferenceType().getCanonicalType()) {
9238 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9239 << (unsigned) FnKind << FnDesc
9240 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9241 << (unsigned) isObjectArgument << I + 1;
9242 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9243 return;
9244 }
9245 }
9246
9247 if (BaseToDerivedConversion) {
9248 S.Diag(Fn->getLocation(),
9249 diag::note_ovl_candidate_bad_base_to_derived_conv)
9250 << (unsigned) FnKind << FnDesc
9251 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9252 << (BaseToDerivedConversion - 1)
9253 << FromTy << ToTy << I+1;
9254 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9255 return;
9256 }
9257
9258 if (isa<ObjCObjectPointerType>(CFromTy) &&
9259 isa<PointerType>(CToTy)) {
9260 Qualifiers FromQs = CFromTy.getQualifiers();
9261 Qualifiers ToQs = CToTy.getQualifiers();
9262 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9263 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9264 << (unsigned) FnKind << FnDesc
9265 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9266 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9267 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9268 return;
9269 }
9270 }
9271
9272 if (TakingCandidateAddress &&
9273 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9274 return;
9275
9276 // Emit the generic diagnostic and, optionally, add the hints to it.
9277 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9278 FDiag << (unsigned) FnKind << FnDesc
9279 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9280 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9281 << (unsigned) (Cand->Fix.Kind);
9282
9283 // If we can fix the conversion, suggest the FixIts.
9284 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9285 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9286 FDiag << *HI;
9287 S.Diag(Fn->getLocation(), FDiag);
9288
9289 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9290 }
9291
9292 /// Additional arity mismatch diagnosis specific to a function overload
9293 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9294 /// over a candidate in any candidate set.
CheckArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)9295 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9296 unsigned NumArgs) {
9297 FunctionDecl *Fn = Cand->Function;
9298 unsigned MinParams = Fn->getMinRequiredArguments();
9299
9300 // With invalid overloaded operators, it's possible that we think we
9301 // have an arity mismatch when in fact it looks like we have the
9302 // right number of arguments, because only overloaded operators have
9303 // the weird behavior of overloading member and non-member functions.
9304 // Just don't report anything.
9305 if (Fn->isInvalidDecl() &&
9306 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9307 return true;
9308
9309 if (NumArgs < MinParams) {
9310 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9311 (Cand->FailureKind == ovl_fail_bad_deduction &&
9312 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9313 } else {
9314 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9315 (Cand->FailureKind == ovl_fail_bad_deduction &&
9316 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9317 }
9318
9319 return false;
9320 }
9321
9322 /// General arity mismatch diagnosis over a candidate in a candidate set.
DiagnoseArityMismatch(Sema & S,NamedDecl * Found,Decl * D,unsigned NumFormalArgs)9323 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9324 unsigned NumFormalArgs) {
9325 assert(isa<FunctionDecl>(D) &&
9326 "The templated declaration should at least be a function"
9327 " when diagnosing bad template argument deduction due to too many"
9328 " or too few arguments");
9329
9330 FunctionDecl *Fn = cast<FunctionDecl>(D);
9331
9332 // TODO: treat calls to a missing default constructor as a special case
9333 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9334 unsigned MinParams = Fn->getMinRequiredArguments();
9335
9336 // at least / at most / exactly
9337 unsigned mode, modeCount;
9338 if (NumFormalArgs < MinParams) {
9339 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9340 FnTy->isTemplateVariadic())
9341 mode = 0; // "at least"
9342 else
9343 mode = 2; // "exactly"
9344 modeCount = MinParams;
9345 } else {
9346 if (MinParams != FnTy->getNumParams())
9347 mode = 1; // "at most"
9348 else
9349 mode = 2; // "exactly"
9350 modeCount = FnTy->getNumParams();
9351 }
9352
9353 std::string Description;
9354 OverloadCandidateKind FnKind =
9355 ClassifyOverloadCandidate(S, Found, Fn, Description);
9356
9357 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9358 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9359 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9360 << mode << Fn->getParamDecl(0) << NumFormalArgs;
9361 else
9362 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9363 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9364 << mode << modeCount << NumFormalArgs;
9365 MaybeEmitInheritedConstructorNote(S, Found);
9366 }
9367
9368 /// Arity mismatch diagnosis specific to a function overload candidate.
DiagnoseArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumFormalArgs)9369 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9370 unsigned NumFormalArgs) {
9371 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9372 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9373 }
9374
getDescribedTemplate(Decl * Templated)9375 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9376 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9377 return TD;
9378 llvm_unreachable("Unsupported: Getting the described template declaration"
9379 " for bad deduction diagnosis");
9380 }
9381
9382 /// Diagnose a failed template-argument deduction.
DiagnoseBadDeduction(Sema & S,NamedDecl * Found,Decl * Templated,DeductionFailureInfo & DeductionFailure,unsigned NumArgs,bool TakingCandidateAddress)9383 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9384 DeductionFailureInfo &DeductionFailure,
9385 unsigned NumArgs,
9386 bool TakingCandidateAddress) {
9387 TemplateParameter Param = DeductionFailure.getTemplateParameter();
9388 NamedDecl *ParamD;
9389 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9390 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9391 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9392 switch (DeductionFailure.Result) {
9393 case Sema::TDK_Success:
9394 llvm_unreachable("TDK_success while diagnosing bad deduction");
9395
9396 case Sema::TDK_Incomplete: {
9397 assert(ParamD && "no parameter found for incomplete deduction result");
9398 S.Diag(Templated->getLocation(),
9399 diag::note_ovl_candidate_incomplete_deduction)
9400 << ParamD->getDeclName();
9401 MaybeEmitInheritedConstructorNote(S, Found);
9402 return;
9403 }
9404
9405 case Sema::TDK_Underqualified: {
9406 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9407 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9408
9409 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9410
9411 // Param will have been canonicalized, but it should just be a
9412 // qualified version of ParamD, so move the qualifiers to that.
9413 QualifierCollector Qs;
9414 Qs.strip(Param);
9415 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9416 assert(S.Context.hasSameType(Param, NonCanonParam));
9417
9418 // Arg has also been canonicalized, but there's nothing we can do
9419 // about that. It also doesn't matter as much, because it won't
9420 // have any template parameters in it (because deduction isn't
9421 // done on dependent types).
9422 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9423
9424 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9425 << ParamD->getDeclName() << Arg << NonCanonParam;
9426 MaybeEmitInheritedConstructorNote(S, Found);
9427 return;
9428 }
9429
9430 case Sema::TDK_Inconsistent: {
9431 assert(ParamD && "no parameter found for inconsistent deduction result");
9432 int which = 0;
9433 if (isa<TemplateTypeParmDecl>(ParamD))
9434 which = 0;
9435 else if (isa<NonTypeTemplateParmDecl>(ParamD))
9436 which = 1;
9437 else {
9438 which = 2;
9439 }
9440
9441 S.Diag(Templated->getLocation(),
9442 diag::note_ovl_candidate_inconsistent_deduction)
9443 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9444 << *DeductionFailure.getSecondArg();
9445 MaybeEmitInheritedConstructorNote(S, Found);
9446 return;
9447 }
9448
9449 case Sema::TDK_InvalidExplicitArguments:
9450 assert(ParamD && "no parameter found for invalid explicit arguments");
9451 if (ParamD->getDeclName())
9452 S.Diag(Templated->getLocation(),
9453 diag::note_ovl_candidate_explicit_arg_mismatch_named)
9454 << ParamD->getDeclName();
9455 else {
9456 int index = 0;
9457 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9458 index = TTP->getIndex();
9459 else if (NonTypeTemplateParmDecl *NTTP
9460 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9461 index = NTTP->getIndex();
9462 else
9463 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9464 S.Diag(Templated->getLocation(),
9465 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9466 << (index + 1);
9467 }
9468 MaybeEmitInheritedConstructorNote(S, Found);
9469 return;
9470
9471 case Sema::TDK_TooManyArguments:
9472 case Sema::TDK_TooFewArguments:
9473 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9474 return;
9475
9476 case Sema::TDK_InstantiationDepth:
9477 S.Diag(Templated->getLocation(),
9478 diag::note_ovl_candidate_instantiation_depth);
9479 MaybeEmitInheritedConstructorNote(S, Found);
9480 return;
9481
9482 case Sema::TDK_SubstitutionFailure: {
9483 // Format the template argument list into the argument string.
9484 SmallString<128> TemplateArgString;
9485 if (TemplateArgumentList *Args =
9486 DeductionFailure.getTemplateArgumentList()) {
9487 TemplateArgString = " ";
9488 TemplateArgString += S.getTemplateArgumentBindingsText(
9489 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9490 }
9491
9492 // If this candidate was disabled by enable_if, say so.
9493 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9494 if (PDiag && PDiag->second.getDiagID() ==
9495 diag::err_typename_nested_not_found_enable_if) {
9496 // FIXME: Use the source range of the condition, and the fully-qualified
9497 // name of the enable_if template. These are both present in PDiag.
9498 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9499 << "'enable_if'" << TemplateArgString;
9500 return;
9501 }
9502
9503 // Format the SFINAE diagnostic into the argument string.
9504 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9505 // formatted message in another diagnostic.
9506 SmallString<128> SFINAEArgString;
9507 SourceRange R;
9508 if (PDiag) {
9509 SFINAEArgString = ": ";
9510 R = SourceRange(PDiag->first, PDiag->first);
9511 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9512 }
9513
9514 S.Diag(Templated->getLocation(),
9515 diag::note_ovl_candidate_substitution_failure)
9516 << TemplateArgString << SFINAEArgString << R;
9517 MaybeEmitInheritedConstructorNote(S, Found);
9518 return;
9519 }
9520
9521 case Sema::TDK_FailedOverloadResolution: {
9522 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9523 S.Diag(Templated->getLocation(),
9524 diag::note_ovl_candidate_failed_overload_resolution)
9525 << R.Expression->getName();
9526 return;
9527 }
9528
9529 case Sema::TDK_DeducedMismatch: {
9530 // Format the template argument list into the argument string.
9531 SmallString<128> TemplateArgString;
9532 if (TemplateArgumentList *Args =
9533 DeductionFailure.getTemplateArgumentList()) {
9534 TemplateArgString = " ";
9535 TemplateArgString += S.getTemplateArgumentBindingsText(
9536 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9537 }
9538
9539 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9540 << (*DeductionFailure.getCallArgIndex() + 1)
9541 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9542 << TemplateArgString;
9543 break;
9544 }
9545
9546 case Sema::TDK_NonDeducedMismatch: {
9547 // FIXME: Provide a source location to indicate what we couldn't match.
9548 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9549 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9550 if (FirstTA.getKind() == TemplateArgument::Template &&
9551 SecondTA.getKind() == TemplateArgument::Template) {
9552 TemplateName FirstTN = FirstTA.getAsTemplate();
9553 TemplateName SecondTN = SecondTA.getAsTemplate();
9554 if (FirstTN.getKind() == TemplateName::Template &&
9555 SecondTN.getKind() == TemplateName::Template) {
9556 if (FirstTN.getAsTemplateDecl()->getName() ==
9557 SecondTN.getAsTemplateDecl()->getName()) {
9558 // FIXME: This fixes a bad diagnostic where both templates are named
9559 // the same. This particular case is a bit difficult since:
9560 // 1) It is passed as a string to the diagnostic printer.
9561 // 2) The diagnostic printer only attempts to find a better
9562 // name for types, not decls.
9563 // Ideally, this should folded into the diagnostic printer.
9564 S.Diag(Templated->getLocation(),
9565 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9566 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9567 return;
9568 }
9569 }
9570 }
9571
9572 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9573 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9574 return;
9575
9576 // FIXME: For generic lambda parameters, check if the function is a lambda
9577 // call operator, and if so, emit a prettier and more informative
9578 // diagnostic that mentions 'auto' and lambda in addition to
9579 // (or instead of?) the canonical template type parameters.
9580 S.Diag(Templated->getLocation(),
9581 diag::note_ovl_candidate_non_deduced_mismatch)
9582 << FirstTA << SecondTA;
9583 return;
9584 }
9585 // TODO: diagnose these individually, then kill off
9586 // note_ovl_candidate_bad_deduction, which is uselessly vague.
9587 case Sema::TDK_MiscellaneousDeductionFailure:
9588 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9589 MaybeEmitInheritedConstructorNote(S, Found);
9590 return;
9591 }
9592 }
9593
9594 /// Diagnose a failed template-argument deduction, for function calls.
DiagnoseBadDeduction(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool TakingCandidateAddress)9595 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9596 unsigned NumArgs,
9597 bool TakingCandidateAddress) {
9598 unsigned TDK = Cand->DeductionFailure.Result;
9599 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9600 if (CheckArityMismatch(S, Cand, NumArgs))
9601 return;
9602 }
9603 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9604 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9605 }
9606
9607 /// CUDA: diagnose an invalid call across targets.
DiagnoseBadTarget(Sema & S,OverloadCandidate * Cand)9608 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9609 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9610 FunctionDecl *Callee = Cand->Function;
9611
9612 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9613 CalleeTarget = S.IdentifyCUDATarget(Callee);
9614
9615 std::string FnDesc;
9616 OverloadCandidateKind FnKind =
9617 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
9618
9619 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9620 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9621
9622 // This could be an implicit constructor for which we could not infer the
9623 // target due to a collsion. Diagnose that case.
9624 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9625 if (Meth != nullptr && Meth->isImplicit()) {
9626 CXXRecordDecl *ParentClass = Meth->getParent();
9627 Sema::CXXSpecialMember CSM;
9628
9629 switch (FnKind) {
9630 default:
9631 return;
9632 case oc_implicit_default_constructor:
9633 CSM = Sema::CXXDefaultConstructor;
9634 break;
9635 case oc_implicit_copy_constructor:
9636 CSM = Sema::CXXCopyConstructor;
9637 break;
9638 case oc_implicit_move_constructor:
9639 CSM = Sema::CXXMoveConstructor;
9640 break;
9641 case oc_implicit_copy_assignment:
9642 CSM = Sema::CXXCopyAssignment;
9643 break;
9644 case oc_implicit_move_assignment:
9645 CSM = Sema::CXXMoveAssignment;
9646 break;
9647 };
9648
9649 bool ConstRHS = false;
9650 if (Meth->getNumParams()) {
9651 if (const ReferenceType *RT =
9652 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9653 ConstRHS = RT->getPointeeType().isConstQualified();
9654 }
9655 }
9656
9657 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9658 /* ConstRHS */ ConstRHS,
9659 /* Diagnose */ true);
9660 }
9661 }
9662
DiagnoseFailedEnableIfAttr(Sema & S,OverloadCandidate * Cand)9663 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9664 FunctionDecl *Callee = Cand->Function;
9665 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9666
9667 S.Diag(Callee->getLocation(),
9668 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9669 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9670 }
9671
9672 /// Generates a 'note' diagnostic for an overload candidate. We've
9673 /// already generated a primary error at the call site.
9674 ///
9675 /// It really does need to be a single diagnostic with its caret
9676 /// pointed at the candidate declaration. Yes, this creates some
9677 /// major challenges of technical writing. Yes, this makes pointing
9678 /// out problems with specific arguments quite awkward. It's still
9679 /// better than generating twenty screens of text for every failed
9680 /// overload.
9681 ///
9682 /// It would be great to be able to express per-candidate problems
9683 /// more richly for those diagnostic clients that cared, but we'd
9684 /// still have to be just as careful with the default diagnostics.
NoteFunctionCandidate(Sema & S,OverloadCandidate * Cand,unsigned NumArgs,bool TakingCandidateAddress)9685 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9686 unsigned NumArgs,
9687 bool TakingCandidateAddress) {
9688 FunctionDecl *Fn = Cand->Function;
9689
9690 // Note deleted candidates, but only if they're viable.
9691 if (Cand->Viable && (Fn->isDeleted() ||
9692 S.isFunctionConsideredUnavailable(Fn))) {
9693 std::string FnDesc;
9694 OverloadCandidateKind FnKind =
9695 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9696
9697 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9698 << FnKind << FnDesc
9699 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9700 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9701 return;
9702 }
9703
9704 // We don't really have anything else to say about viable candidates.
9705 if (Cand->Viable) {
9706 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9707 return;
9708 }
9709
9710 switch (Cand->FailureKind) {
9711 case ovl_fail_too_many_arguments:
9712 case ovl_fail_too_few_arguments:
9713 return DiagnoseArityMismatch(S, Cand, NumArgs);
9714
9715 case ovl_fail_bad_deduction:
9716 return DiagnoseBadDeduction(S, Cand, NumArgs,
9717 TakingCandidateAddress);
9718
9719 case ovl_fail_illegal_constructor: {
9720 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9721 << (Fn->getPrimaryTemplate() ? 1 : 0);
9722 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9723 return;
9724 }
9725
9726 case ovl_fail_trivial_conversion:
9727 case ovl_fail_bad_final_conversion:
9728 case ovl_fail_final_conversion_not_exact:
9729 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9730
9731 case ovl_fail_bad_conversion: {
9732 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9733 for (unsigned N = Cand->NumConversions; I != N; ++I)
9734 if (Cand->Conversions[I].isBad())
9735 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9736
9737 // FIXME: this currently happens when we're called from SemaInit
9738 // when user-conversion overload fails. Figure out how to handle
9739 // those conditions and diagnose them well.
9740 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9741 }
9742
9743 case ovl_fail_bad_target:
9744 return DiagnoseBadTarget(S, Cand);
9745
9746 case ovl_fail_enable_if:
9747 return DiagnoseFailedEnableIfAttr(S, Cand);
9748
9749 case ovl_fail_addr_not_available: {
9750 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9751 (void)Available;
9752 assert(!Available);
9753 break;
9754 }
9755 }
9756 }
9757
NoteSurrogateCandidate(Sema & S,OverloadCandidate * Cand)9758 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9759 // Desugar the type of the surrogate down to a function type,
9760 // retaining as many typedefs as possible while still showing
9761 // the function type (and, therefore, its parameter types).
9762 QualType FnType = Cand->Surrogate->getConversionType();
9763 bool isLValueReference = false;
9764 bool isRValueReference = false;
9765 bool isPointer = false;
9766 if (const LValueReferenceType *FnTypeRef =
9767 FnType->getAs<LValueReferenceType>()) {
9768 FnType = FnTypeRef->getPointeeType();
9769 isLValueReference = true;
9770 } else if (const RValueReferenceType *FnTypeRef =
9771 FnType->getAs<RValueReferenceType>()) {
9772 FnType = FnTypeRef->getPointeeType();
9773 isRValueReference = true;
9774 }
9775 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9776 FnType = FnTypePtr->getPointeeType();
9777 isPointer = true;
9778 }
9779 // Desugar down to a function type.
9780 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9781 // Reconstruct the pointer/reference as appropriate.
9782 if (isPointer) FnType = S.Context.getPointerType(FnType);
9783 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9784 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9785
9786 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9787 << FnType;
9788 }
9789
NoteBuiltinOperatorCandidate(Sema & S,StringRef Opc,SourceLocation OpLoc,OverloadCandidate * Cand)9790 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9791 SourceLocation OpLoc,
9792 OverloadCandidate *Cand) {
9793 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9794 std::string TypeStr("operator");
9795 TypeStr += Opc;
9796 TypeStr += "(";
9797 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9798 if (Cand->NumConversions == 1) {
9799 TypeStr += ")";
9800 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9801 } else {
9802 TypeStr += ", ";
9803 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9804 TypeStr += ")";
9805 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9806 }
9807 }
9808
NoteAmbiguousUserConversions(Sema & S,SourceLocation OpLoc,OverloadCandidate * Cand)9809 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9810 OverloadCandidate *Cand) {
9811 unsigned NoOperands = Cand->NumConversions;
9812 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9813 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9814 if (ICS.isBad()) break; // all meaningless after first invalid
9815 if (!ICS.isAmbiguous()) continue;
9816
9817 ICS.DiagnoseAmbiguousConversion(
9818 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
9819 }
9820 }
9821
GetLocationForCandidate(const OverloadCandidate * Cand)9822 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9823 if (Cand->Function)
9824 return Cand->Function->getLocation();
9825 if (Cand->IsSurrogate)
9826 return Cand->Surrogate->getLocation();
9827 return SourceLocation();
9828 }
9829
RankDeductionFailure(const DeductionFailureInfo & DFI)9830 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9831 switch ((Sema::TemplateDeductionResult)DFI.Result) {
9832 case Sema::TDK_Success:
9833 llvm_unreachable("TDK_success while diagnosing bad deduction");
9834
9835 case Sema::TDK_Invalid:
9836 case Sema::TDK_Incomplete:
9837 return 1;
9838
9839 case Sema::TDK_Underqualified:
9840 case Sema::TDK_Inconsistent:
9841 return 2;
9842
9843 case Sema::TDK_SubstitutionFailure:
9844 case Sema::TDK_DeducedMismatch:
9845 case Sema::TDK_NonDeducedMismatch:
9846 case Sema::TDK_MiscellaneousDeductionFailure:
9847 return 3;
9848
9849 case Sema::TDK_InstantiationDepth:
9850 case Sema::TDK_FailedOverloadResolution:
9851 return 4;
9852
9853 case Sema::TDK_InvalidExplicitArguments:
9854 return 5;
9855
9856 case Sema::TDK_TooManyArguments:
9857 case Sema::TDK_TooFewArguments:
9858 return 6;
9859 }
9860 llvm_unreachable("Unhandled deduction result");
9861 }
9862
9863 namespace {
9864 struct CompareOverloadCandidatesForDisplay {
9865 Sema &S;
9866 SourceLocation Loc;
9867 size_t NumArgs;
9868
CompareOverloadCandidatesForDisplay__anond619a3da0b11::CompareOverloadCandidatesForDisplay9869 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
9870 : S(S), NumArgs(nArgs) {}
9871
operator ()__anond619a3da0b11::CompareOverloadCandidatesForDisplay9872 bool operator()(const OverloadCandidate *L,
9873 const OverloadCandidate *R) {
9874 // Fast-path this check.
9875 if (L == R) return false;
9876
9877 // Order first by viability.
9878 if (L->Viable) {
9879 if (!R->Viable) return true;
9880
9881 // TODO: introduce a tri-valued comparison for overload
9882 // candidates. Would be more worthwhile if we had a sort
9883 // that could exploit it.
9884 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9885 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9886 } else if (R->Viable)
9887 return false;
9888
9889 assert(L->Viable == R->Viable);
9890
9891 // Criteria by which we can sort non-viable candidates:
9892 if (!L->Viable) {
9893 // 1. Arity mismatches come after other candidates.
9894 if (L->FailureKind == ovl_fail_too_many_arguments ||
9895 L->FailureKind == ovl_fail_too_few_arguments) {
9896 if (R->FailureKind == ovl_fail_too_many_arguments ||
9897 R->FailureKind == ovl_fail_too_few_arguments) {
9898 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9899 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9900 if (LDist == RDist) {
9901 if (L->FailureKind == R->FailureKind)
9902 // Sort non-surrogates before surrogates.
9903 return !L->IsSurrogate && R->IsSurrogate;
9904 // Sort candidates requiring fewer parameters than there were
9905 // arguments given after candidates requiring more parameters
9906 // than there were arguments given.
9907 return L->FailureKind == ovl_fail_too_many_arguments;
9908 }
9909 return LDist < RDist;
9910 }
9911 return false;
9912 }
9913 if (R->FailureKind == ovl_fail_too_many_arguments ||
9914 R->FailureKind == ovl_fail_too_few_arguments)
9915 return true;
9916
9917 // 2. Bad conversions come first and are ordered by the number
9918 // of bad conversions and quality of good conversions.
9919 if (L->FailureKind == ovl_fail_bad_conversion) {
9920 if (R->FailureKind != ovl_fail_bad_conversion)
9921 return true;
9922
9923 // The conversion that can be fixed with a smaller number of changes,
9924 // comes first.
9925 unsigned numLFixes = L->Fix.NumConversionsFixed;
9926 unsigned numRFixes = R->Fix.NumConversionsFixed;
9927 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9928 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9929 if (numLFixes != numRFixes) {
9930 return numLFixes < numRFixes;
9931 }
9932
9933 // If there's any ordering between the defined conversions...
9934 // FIXME: this might not be transitive.
9935 assert(L->NumConversions == R->NumConversions);
9936
9937 int leftBetter = 0;
9938 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9939 for (unsigned E = L->NumConversions; I != E; ++I) {
9940 switch (CompareImplicitConversionSequences(S, Loc,
9941 L->Conversions[I],
9942 R->Conversions[I])) {
9943 case ImplicitConversionSequence::Better:
9944 leftBetter++;
9945 break;
9946
9947 case ImplicitConversionSequence::Worse:
9948 leftBetter--;
9949 break;
9950
9951 case ImplicitConversionSequence::Indistinguishable:
9952 break;
9953 }
9954 }
9955 if (leftBetter > 0) return true;
9956 if (leftBetter < 0) return false;
9957
9958 } else if (R->FailureKind == ovl_fail_bad_conversion)
9959 return false;
9960
9961 if (L->FailureKind == ovl_fail_bad_deduction) {
9962 if (R->FailureKind != ovl_fail_bad_deduction)
9963 return true;
9964
9965 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9966 return RankDeductionFailure(L->DeductionFailure)
9967 < RankDeductionFailure(R->DeductionFailure);
9968 } else if (R->FailureKind == ovl_fail_bad_deduction)
9969 return false;
9970
9971 // TODO: others?
9972 }
9973
9974 // Sort everything else by location.
9975 SourceLocation LLoc = GetLocationForCandidate(L);
9976 SourceLocation RLoc = GetLocationForCandidate(R);
9977
9978 // Put candidates without locations (e.g. builtins) at the end.
9979 if (LLoc.isInvalid()) return false;
9980 if (RLoc.isInvalid()) return true;
9981
9982 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9983 }
9984 };
9985 }
9986
9987 /// CompleteNonViableCandidate - Normally, overload resolution only
9988 /// computes up to the first. Produces the FixIt set if possible.
CompleteNonViableCandidate(Sema & S,OverloadCandidate * Cand,ArrayRef<Expr * > Args)9989 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9990 ArrayRef<Expr *> Args) {
9991 assert(!Cand->Viable);
9992
9993 // Don't do anything on failures other than bad conversion.
9994 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9995
9996 // We only want the FixIts if all the arguments can be corrected.
9997 bool Unfixable = false;
9998 // Use a implicit copy initialization to check conversion fixes.
9999 Cand->Fix.setConversionChecker(TryCopyInitialization);
10000
10001 // Skip forward to the first bad conversion.
10002 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10003 unsigned ConvCount = Cand->NumConversions;
10004 while (true) {
10005 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10006 ConvIdx++;
10007 if (Cand->Conversions[ConvIdx - 1].isBad()) {
10008 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
10009 break;
10010 }
10011 }
10012
10013 if (ConvIdx == ConvCount)
10014 return;
10015
10016 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10017 "remaining conversion is initialized?");
10018
10019 // FIXME: this should probably be preserved from the overload
10020 // operation somehow.
10021 bool SuppressUserConversions = false;
10022
10023 const FunctionProtoType* Proto;
10024 unsigned ArgIdx = ConvIdx;
10025
10026 if (Cand->IsSurrogate) {
10027 QualType ConvType
10028 = Cand->Surrogate->getConversionType().getNonReferenceType();
10029 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10030 ConvType = ConvPtrType->getPointeeType();
10031 Proto = ConvType->getAs<FunctionProtoType>();
10032 ArgIdx--;
10033 } else if (Cand->Function) {
10034 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10035 if (isa<CXXMethodDecl>(Cand->Function) &&
10036 !isa<CXXConstructorDecl>(Cand->Function))
10037 ArgIdx--;
10038 } else {
10039 // Builtin binary operator with a bad first conversion.
10040 assert(ConvCount <= 3);
10041 for (; ConvIdx != ConvCount; ++ConvIdx)
10042 Cand->Conversions[ConvIdx]
10043 = TryCopyInitialization(S, Args[ConvIdx],
10044 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10045 SuppressUserConversions,
10046 /*InOverloadResolution*/ true,
10047 /*AllowObjCWritebackConversion=*/
10048 S.getLangOpts().ObjCAutoRefCount);
10049 return;
10050 }
10051
10052 // Fill in the rest of the conversions.
10053 unsigned NumParams = Proto->getNumParams();
10054 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10055 if (ArgIdx < NumParams) {
10056 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10057 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10058 /*InOverloadResolution=*/true,
10059 /*AllowObjCWritebackConversion=*/
10060 S.getLangOpts().ObjCAutoRefCount);
10061 // Store the FixIt in the candidate if it exists.
10062 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10063 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10064 }
10065 else
10066 Cand->Conversions[ConvIdx].setEllipsis();
10067 }
10068 }
10069
10070 /// PrintOverloadCandidates - When overload resolution fails, prints
10071 /// diagnostic messages containing the candidates in the candidate
10072 /// set.
NoteCandidates(Sema & S,OverloadCandidateDisplayKind OCD,ArrayRef<Expr * > Args,StringRef Opc,SourceLocation OpLoc)10073 void OverloadCandidateSet::NoteCandidates(Sema &S,
10074 OverloadCandidateDisplayKind OCD,
10075 ArrayRef<Expr *> Args,
10076 StringRef Opc,
10077 SourceLocation OpLoc) {
10078 // Sort the candidates by viability and position. Sorting directly would
10079 // be prohibitive, so we make a set of pointers and sort those.
10080 SmallVector<OverloadCandidate*, 32> Cands;
10081 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10082 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10083 if (Cand->Viable)
10084 Cands.push_back(Cand);
10085 else if (OCD == OCD_AllCandidates) {
10086 CompleteNonViableCandidate(S, Cand, Args);
10087 if (Cand->Function || Cand->IsSurrogate)
10088 Cands.push_back(Cand);
10089 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10090 // want to list every possible builtin candidate.
10091 }
10092 }
10093
10094 std::sort(Cands.begin(), Cands.end(),
10095 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10096
10097 bool ReportedAmbiguousConversions = false;
10098
10099 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10100 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10101 unsigned CandsShown = 0;
10102 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10103 OverloadCandidate *Cand = *I;
10104
10105 // Set an arbitrary limit on the number of candidate functions we'll spam
10106 // the user with. FIXME: This limit should depend on details of the
10107 // candidate list.
10108 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10109 break;
10110 }
10111 ++CandsShown;
10112
10113 if (Cand->Function)
10114 NoteFunctionCandidate(S, Cand, Args.size(),
10115 /*TakingCandidateAddress=*/false);
10116 else if (Cand->IsSurrogate)
10117 NoteSurrogateCandidate(S, Cand);
10118 else {
10119 assert(Cand->Viable &&
10120 "Non-viable built-in candidates are not added to Cands.");
10121 // Generally we only see ambiguities including viable builtin
10122 // operators if overload resolution got screwed up by an
10123 // ambiguous user-defined conversion.
10124 //
10125 // FIXME: It's quite possible for different conversions to see
10126 // different ambiguities, though.
10127 if (!ReportedAmbiguousConversions) {
10128 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10129 ReportedAmbiguousConversions = true;
10130 }
10131
10132 // If this is a viable builtin, print it.
10133 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10134 }
10135 }
10136
10137 if (I != E)
10138 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10139 }
10140
10141 static SourceLocation
GetLocationForCandidate(const TemplateSpecCandidate * Cand)10142 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10143 return Cand->Specialization ? Cand->Specialization->getLocation()
10144 : SourceLocation();
10145 }
10146
10147 namespace {
10148 struct CompareTemplateSpecCandidatesForDisplay {
10149 Sema &S;
CompareTemplateSpecCandidatesForDisplay__anond619a3da0c11::CompareTemplateSpecCandidatesForDisplay10150 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10151
operator ()__anond619a3da0c11::CompareTemplateSpecCandidatesForDisplay10152 bool operator()(const TemplateSpecCandidate *L,
10153 const TemplateSpecCandidate *R) {
10154 // Fast-path this check.
10155 if (L == R)
10156 return false;
10157
10158 // Assuming that both candidates are not matches...
10159
10160 // Sort by the ranking of deduction failures.
10161 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10162 return RankDeductionFailure(L->DeductionFailure) <
10163 RankDeductionFailure(R->DeductionFailure);
10164
10165 // Sort everything else by location.
10166 SourceLocation LLoc = GetLocationForCandidate(L);
10167 SourceLocation RLoc = GetLocationForCandidate(R);
10168
10169 // Put candidates without locations (e.g. builtins) at the end.
10170 if (LLoc.isInvalid())
10171 return false;
10172 if (RLoc.isInvalid())
10173 return true;
10174
10175 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10176 }
10177 };
10178 }
10179
10180 /// Diagnose a template argument deduction failure.
10181 /// We are treating these failures as overload failures due to bad
10182 /// deductions.
NoteDeductionFailure(Sema & S,bool ForTakingAddress)10183 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10184 bool ForTakingAddress) {
10185 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10186 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10187 }
10188
destroyCandidates()10189 void TemplateSpecCandidateSet::destroyCandidates() {
10190 for (iterator i = begin(), e = end(); i != e; ++i) {
10191 i->DeductionFailure.Destroy();
10192 }
10193 }
10194
clear()10195 void TemplateSpecCandidateSet::clear() {
10196 destroyCandidates();
10197 Candidates.clear();
10198 }
10199
10200 /// NoteCandidates - When no template specialization match is found, prints
10201 /// diagnostic messages containing the non-matching specializations that form
10202 /// the candidate set.
10203 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10204 /// OCD == OCD_AllCandidates and Cand->Viable == false.
NoteCandidates(Sema & S,SourceLocation Loc)10205 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10206 // Sort the candidates by position (assuming no candidate is a match).
10207 // Sorting directly would be prohibitive, so we make a set of pointers
10208 // and sort those.
10209 SmallVector<TemplateSpecCandidate *, 32> Cands;
10210 Cands.reserve(size());
10211 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10212 if (Cand->Specialization)
10213 Cands.push_back(Cand);
10214 // Otherwise, this is a non-matching builtin candidate. We do not,
10215 // in general, want to list every possible builtin candidate.
10216 }
10217
10218 std::sort(Cands.begin(), Cands.end(),
10219 CompareTemplateSpecCandidatesForDisplay(S));
10220
10221 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10222 // for generalization purposes (?).
10223 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10224
10225 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10226 unsigned CandsShown = 0;
10227 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10228 TemplateSpecCandidate *Cand = *I;
10229
10230 // Set an arbitrary limit on the number of candidates we'll spam
10231 // the user with. FIXME: This limit should depend on details of the
10232 // candidate list.
10233 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10234 break;
10235 ++CandsShown;
10236
10237 assert(Cand->Specialization &&
10238 "Non-matching built-in candidates are not added to Cands.");
10239 Cand->NoteDeductionFailure(S, ForTakingAddress);
10240 }
10241
10242 if (I != E)
10243 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10244 }
10245
10246 // [PossiblyAFunctionType] --> [Return]
10247 // NonFunctionType --> NonFunctionType
10248 // R (A) --> R(A)
10249 // R (*)(A) --> R (A)
10250 // R (&)(A) --> R (A)
10251 // R (S::*)(A) --> R (A)
ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)10252 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10253 QualType Ret = PossiblyAFunctionType;
10254 if (const PointerType *ToTypePtr =
10255 PossiblyAFunctionType->getAs<PointerType>())
10256 Ret = ToTypePtr->getPointeeType();
10257 else if (const ReferenceType *ToTypeRef =
10258 PossiblyAFunctionType->getAs<ReferenceType>())
10259 Ret = ToTypeRef->getPointeeType();
10260 else if (const MemberPointerType *MemTypePtr =
10261 PossiblyAFunctionType->getAs<MemberPointerType>())
10262 Ret = MemTypePtr->getPointeeType();
10263 Ret =
10264 Context.getCanonicalType(Ret).getUnqualifiedType();
10265 return Ret;
10266 }
10267
10268 namespace {
10269 // A helper class to help with address of function resolution
10270 // - allows us to avoid passing around all those ugly parameters
10271 class AddressOfFunctionResolver {
10272 Sema& S;
10273 Expr* SourceExpr;
10274 const QualType& TargetType;
10275 QualType TargetFunctionType; // Extracted function type from target type
10276
10277 bool Complain;
10278 //DeclAccessPair& ResultFunctionAccessPair;
10279 ASTContext& Context;
10280
10281 bool TargetTypeIsNonStaticMemberFunction;
10282 bool FoundNonTemplateFunction;
10283 bool StaticMemberFunctionFromBoundPointer;
10284 bool HasComplained;
10285
10286 OverloadExpr::FindResult OvlExprInfo;
10287 OverloadExpr *OvlExpr;
10288 TemplateArgumentListInfo OvlExplicitTemplateArgs;
10289 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10290 TemplateSpecCandidateSet FailedCandidates;
10291
10292 public:
AddressOfFunctionResolver(Sema & S,Expr * SourceExpr,const QualType & TargetType,bool Complain)10293 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10294 const QualType &TargetType, bool Complain)
10295 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10296 Complain(Complain), Context(S.getASTContext()),
10297 TargetTypeIsNonStaticMemberFunction(
10298 !!TargetType->getAs<MemberPointerType>()),
10299 FoundNonTemplateFunction(false),
10300 StaticMemberFunctionFromBoundPointer(false),
10301 HasComplained(false),
10302 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10303 OvlExpr(OvlExprInfo.Expression),
10304 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10305 ExtractUnqualifiedFunctionTypeFromTargetType();
10306
10307 if (TargetFunctionType->isFunctionType()) {
10308 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10309 if (!UME->isImplicitAccess() &&
10310 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10311 StaticMemberFunctionFromBoundPointer = true;
10312 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10313 DeclAccessPair dap;
10314 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10315 OvlExpr, false, &dap)) {
10316 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10317 if (!Method->isStatic()) {
10318 // If the target type is a non-function type and the function found
10319 // is a non-static member function, pretend as if that was the
10320 // target, it's the only possible type to end up with.
10321 TargetTypeIsNonStaticMemberFunction = true;
10322
10323 // And skip adding the function if its not in the proper form.
10324 // We'll diagnose this due to an empty set of functions.
10325 if (!OvlExprInfo.HasFormOfMemberPointer)
10326 return;
10327 }
10328
10329 Matches.push_back(std::make_pair(dap, Fn));
10330 }
10331 return;
10332 }
10333
10334 if (OvlExpr->hasExplicitTemplateArgs())
10335 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10336
10337 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10338 // C++ [over.over]p4:
10339 // If more than one function is selected, [...]
10340 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10341 if (FoundNonTemplateFunction)
10342 EliminateAllTemplateMatches();
10343 else
10344 EliminateAllExceptMostSpecializedTemplate();
10345 }
10346 }
10347
10348 if (S.getLangOpts().CUDA && Matches.size() > 1)
10349 EliminateSuboptimalCudaMatches();
10350 }
10351
hasComplained() const10352 bool hasComplained() const { return HasComplained; }
10353
10354 private:
candidateHasExactlyCorrectType(const FunctionDecl * FD)10355 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10356 QualType Discard;
10357 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10358 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard);
10359 }
10360
10361 /// \return true if A is considered a better overload candidate for the
10362 /// desired type than B.
isBetterCandidate(const FunctionDecl * A,const FunctionDecl * B)10363 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10364 // If A doesn't have exactly the correct type, we don't want to classify it
10365 // as "better" than anything else. This way, the user is required to
10366 // disambiguate for us if there are multiple candidates and no exact match.
10367 return candidateHasExactlyCorrectType(A) &&
10368 (!candidateHasExactlyCorrectType(B) ||
10369 compareEnableIfAttrs(S, A, B) == Comparison::Better);
10370 }
10371
10372 /// \return true if we were able to eliminate all but one overload candidate,
10373 /// false otherwise.
eliminiateSuboptimalOverloadCandidates()10374 bool eliminiateSuboptimalOverloadCandidates() {
10375 // Same algorithm as overload resolution -- one pass to pick the "best",
10376 // another pass to be sure that nothing is better than the best.
10377 auto Best = Matches.begin();
10378 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10379 if (isBetterCandidate(I->second, Best->second))
10380 Best = I;
10381
10382 const FunctionDecl *BestFn = Best->second;
10383 auto IsBestOrInferiorToBest = [this, BestFn](
10384 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10385 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10386 };
10387
10388 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10389 // option, so we can potentially give the user a better error
10390 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10391 return false;
10392 Matches[0] = *Best;
10393 Matches.resize(1);
10394 return true;
10395 }
10396
isTargetTypeAFunction() const10397 bool isTargetTypeAFunction() const {
10398 return TargetFunctionType->isFunctionType();
10399 }
10400
10401 // [ToType] [Return]
10402
10403 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10404 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10405 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
ExtractUnqualifiedFunctionTypeFromTargetType()10406 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10407 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10408 }
10409
10410 // return true if any matching specializations were found
AddMatchingTemplateFunction(FunctionTemplateDecl * FunctionTemplate,const DeclAccessPair & CurAccessFunPair)10411 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10412 const DeclAccessPair& CurAccessFunPair) {
10413 if (CXXMethodDecl *Method
10414 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10415 // Skip non-static function templates when converting to pointer, and
10416 // static when converting to member pointer.
10417 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10418 return false;
10419 }
10420 else if (TargetTypeIsNonStaticMemberFunction)
10421 return false;
10422
10423 // C++ [over.over]p2:
10424 // If the name is a function template, template argument deduction is
10425 // done (14.8.2.2), and if the argument deduction succeeds, the
10426 // resulting template argument list is used to generate a single
10427 // function template specialization, which is added to the set of
10428 // overloaded functions considered.
10429 FunctionDecl *Specialization = nullptr;
10430 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10431 if (Sema::TemplateDeductionResult Result
10432 = S.DeduceTemplateArguments(FunctionTemplate,
10433 &OvlExplicitTemplateArgs,
10434 TargetFunctionType, Specialization,
10435 Info, /*InOverloadResolution=*/true)) {
10436 // Make a note of the failed deduction for diagnostics.
10437 FailedCandidates.addCandidate()
10438 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10439 MakeDeductionFailureInfo(Context, Result, Info));
10440 return false;
10441 }
10442
10443 // Template argument deduction ensures that we have an exact match or
10444 // compatible pointer-to-function arguments that would be adjusted by ICS.
10445 // This function template specicalization works.
10446 assert(S.isSameOrCompatibleFunctionType(
10447 Context.getCanonicalType(Specialization->getType()),
10448 Context.getCanonicalType(TargetFunctionType)));
10449
10450 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10451 return false;
10452
10453 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10454 return true;
10455 }
10456
AddMatchingNonTemplateFunction(NamedDecl * Fn,const DeclAccessPair & CurAccessFunPair)10457 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10458 const DeclAccessPair& CurAccessFunPair) {
10459 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10460 // Skip non-static functions when converting to pointer, and static
10461 // when converting to member pointer.
10462 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10463 return false;
10464 }
10465 else if (TargetTypeIsNonStaticMemberFunction)
10466 return false;
10467
10468 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10469 if (S.getLangOpts().CUDA)
10470 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10471 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
10472 return false;
10473
10474 // If any candidate has a placeholder return type, trigger its deduction
10475 // now.
10476 if (S.getLangOpts().CPlusPlus14 &&
10477 FunDecl->getReturnType()->isUndeducedType() &&
10478 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10479 HasComplained |= Complain;
10480 return false;
10481 }
10482
10483 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10484 return false;
10485
10486 // If we're in C, we need to support types that aren't exactly identical.
10487 if (!S.getLangOpts().CPlusPlus ||
10488 candidateHasExactlyCorrectType(FunDecl)) {
10489 Matches.push_back(std::make_pair(
10490 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10491 FoundNonTemplateFunction = true;
10492 return true;
10493 }
10494 }
10495
10496 return false;
10497 }
10498
FindAllFunctionsThatMatchTargetTypeExactly()10499 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10500 bool Ret = false;
10501
10502 // If the overload expression doesn't have the form of a pointer to
10503 // member, don't try to convert it to a pointer-to-member type.
10504 if (IsInvalidFormOfPointerToMemberFunction())
10505 return false;
10506
10507 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10508 E = OvlExpr->decls_end();
10509 I != E; ++I) {
10510 // Look through any using declarations to find the underlying function.
10511 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10512
10513 // C++ [over.over]p3:
10514 // Non-member functions and static member functions match
10515 // targets of type "pointer-to-function" or "reference-to-function."
10516 // Nonstatic member functions match targets of
10517 // type "pointer-to-member-function."
10518 // Note that according to DR 247, the containing class does not matter.
10519 if (FunctionTemplateDecl *FunctionTemplate
10520 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10521 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10522 Ret = true;
10523 }
10524 // If we have explicit template arguments supplied, skip non-templates.
10525 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10526 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10527 Ret = true;
10528 }
10529 assert(Ret || Matches.empty());
10530 return Ret;
10531 }
10532
EliminateAllExceptMostSpecializedTemplate()10533 void EliminateAllExceptMostSpecializedTemplate() {
10534 // [...] and any given function template specialization F1 is
10535 // eliminated if the set contains a second function template
10536 // specialization whose function template is more specialized
10537 // than the function template of F1 according to the partial
10538 // ordering rules of 14.5.5.2.
10539
10540 // The algorithm specified above is quadratic. We instead use a
10541 // two-pass algorithm (similar to the one used to identify the
10542 // best viable function in an overload set) that identifies the
10543 // best function template (if it exists).
10544
10545 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10546 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10547 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10548
10549 // TODO: It looks like FailedCandidates does not serve much purpose
10550 // here, since the no_viable diagnostic has index 0.
10551 UnresolvedSetIterator Result = S.getMostSpecialized(
10552 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10553 SourceExpr->getLocStart(), S.PDiag(),
10554 S.PDiag(diag::err_addr_ovl_ambiguous)
10555 << Matches[0].second->getDeclName(),
10556 S.PDiag(diag::note_ovl_candidate)
10557 << (unsigned)oc_function_template,
10558 Complain, TargetFunctionType);
10559
10560 if (Result != MatchesCopy.end()) {
10561 // Make it the first and only element
10562 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10563 Matches[0].second = cast<FunctionDecl>(*Result);
10564 Matches.resize(1);
10565 } else
10566 HasComplained |= Complain;
10567 }
10568
EliminateAllTemplateMatches()10569 void EliminateAllTemplateMatches() {
10570 // [...] any function template specializations in the set are
10571 // eliminated if the set also contains a non-template function, [...]
10572 for (unsigned I = 0, N = Matches.size(); I != N; ) {
10573 if (Matches[I].second->getPrimaryTemplate() == nullptr)
10574 ++I;
10575 else {
10576 Matches[I] = Matches[--N];
10577 Matches.resize(N);
10578 }
10579 }
10580 }
10581
EliminateSuboptimalCudaMatches()10582 void EliminateSuboptimalCudaMatches() {
10583 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10584 }
10585
10586 public:
ComplainNoMatchesFound() const10587 void ComplainNoMatchesFound() const {
10588 assert(Matches.empty());
10589 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10590 << OvlExpr->getName() << TargetFunctionType
10591 << OvlExpr->getSourceRange();
10592 if (FailedCandidates.empty())
10593 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10594 /*TakingAddress=*/true);
10595 else {
10596 // We have some deduction failure messages. Use them to diagnose
10597 // the function templates, and diagnose the non-template candidates
10598 // normally.
10599 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10600 IEnd = OvlExpr->decls_end();
10601 I != IEnd; ++I)
10602 if (FunctionDecl *Fun =
10603 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10604 if (!functionHasPassObjectSizeParams(Fun))
10605 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
10606 /*TakingAddress=*/true);
10607 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10608 }
10609 }
10610
IsInvalidFormOfPointerToMemberFunction() const10611 bool IsInvalidFormOfPointerToMemberFunction() const {
10612 return TargetTypeIsNonStaticMemberFunction &&
10613 !OvlExprInfo.HasFormOfMemberPointer;
10614 }
10615
ComplainIsInvalidFormOfPointerToMemberFunction() const10616 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10617 // TODO: Should we condition this on whether any functions might
10618 // have matched, or is it more appropriate to do that in callers?
10619 // TODO: a fixit wouldn't hurt.
10620 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10621 << TargetType << OvlExpr->getSourceRange();
10622 }
10623
IsStaticMemberFunctionFromBoundPointer() const10624 bool IsStaticMemberFunctionFromBoundPointer() const {
10625 return StaticMemberFunctionFromBoundPointer;
10626 }
10627
ComplainIsStaticMemberFunctionFromBoundPointer() const10628 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10629 S.Diag(OvlExpr->getLocStart(),
10630 diag::err_invalid_form_pointer_member_function)
10631 << OvlExpr->getSourceRange();
10632 }
10633
ComplainOfInvalidConversion() const10634 void ComplainOfInvalidConversion() const {
10635 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10636 << OvlExpr->getName() << TargetType;
10637 }
10638
ComplainMultipleMatchesFound() const10639 void ComplainMultipleMatchesFound() const {
10640 assert(Matches.size() > 1);
10641 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10642 << OvlExpr->getName()
10643 << OvlExpr->getSourceRange();
10644 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10645 /*TakingAddress=*/true);
10646 }
10647
hadMultipleCandidates() const10648 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10649
getNumMatches() const10650 int getNumMatches() const { return Matches.size(); }
10651
getMatchingFunctionDecl() const10652 FunctionDecl* getMatchingFunctionDecl() const {
10653 if (Matches.size() != 1) return nullptr;
10654 return Matches[0].second;
10655 }
10656
getMatchingFunctionAccessPair() const10657 const DeclAccessPair* getMatchingFunctionAccessPair() const {
10658 if (Matches.size() != 1) return nullptr;
10659 return &Matches[0].first;
10660 }
10661 };
10662 }
10663
10664 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10665 /// an overloaded function (C++ [over.over]), where @p From is an
10666 /// expression with overloaded function type and @p ToType is the type
10667 /// we're trying to resolve to. For example:
10668 ///
10669 /// @code
10670 /// int f(double);
10671 /// int f(int);
10672 ///
10673 /// int (*pfd)(double) = f; // selects f(double)
10674 /// @endcode
10675 ///
10676 /// This routine returns the resulting FunctionDecl if it could be
10677 /// resolved, and NULL otherwise. When @p Complain is true, this
10678 /// routine will emit diagnostics if there is an error.
10679 FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr * AddressOfExpr,QualType TargetType,bool Complain,DeclAccessPair & FoundResult,bool * pHadMultipleCandidates)10680 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10681 QualType TargetType,
10682 bool Complain,
10683 DeclAccessPair &FoundResult,
10684 bool *pHadMultipleCandidates) {
10685 assert(AddressOfExpr->getType() == Context.OverloadTy);
10686
10687 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10688 Complain);
10689 int NumMatches = Resolver.getNumMatches();
10690 FunctionDecl *Fn = nullptr;
10691 bool ShouldComplain = Complain && !Resolver.hasComplained();
10692 if (NumMatches == 0 && ShouldComplain) {
10693 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10694 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10695 else
10696 Resolver.ComplainNoMatchesFound();
10697 }
10698 else if (NumMatches > 1 && ShouldComplain)
10699 Resolver.ComplainMultipleMatchesFound();
10700 else if (NumMatches == 1) {
10701 Fn = Resolver.getMatchingFunctionDecl();
10702 assert(Fn);
10703 FoundResult = *Resolver.getMatchingFunctionAccessPair();
10704 if (Complain) {
10705 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10706 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10707 else
10708 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10709 }
10710 }
10711
10712 if (pHadMultipleCandidates)
10713 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10714 return Fn;
10715 }
10716
10717 /// \brief Given an expression that refers to an overloaded function, try to
10718 /// resolve that function to a single function that can have its address taken.
10719 /// This will modify `Pair` iff it returns non-null.
10720 ///
10721 /// This routine can only realistically succeed if all but one candidates in the
10722 /// overload set for SrcExpr cannot have their addresses taken.
10723 FunctionDecl *
resolveAddressOfOnlyViableOverloadCandidate(Expr * E,DeclAccessPair & Pair)10724 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10725 DeclAccessPair &Pair) {
10726 OverloadExpr::FindResult R = OverloadExpr::find(E);
10727 OverloadExpr *Ovl = R.Expression;
10728 FunctionDecl *Result = nullptr;
10729 DeclAccessPair DAP;
10730 // Don't use the AddressOfResolver because we're specifically looking for
10731 // cases where we have one overload candidate that lacks
10732 // enable_if/pass_object_size/...
10733 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10734 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10735 if (!FD)
10736 return nullptr;
10737
10738 if (!checkAddressOfFunctionIsAvailable(FD))
10739 continue;
10740
10741 // We have more than one result; quit.
10742 if (Result)
10743 return nullptr;
10744 DAP = I.getPair();
10745 Result = FD;
10746 }
10747
10748 if (Result)
10749 Pair = DAP;
10750 return Result;
10751 }
10752
10753 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
10754 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10755 /// will perform access checks, diagnose the use of the resultant decl, and, if
10756 /// necessary, perform a function-to-pointer decay.
10757 ///
10758 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10759 /// Otherwise, returns true. This may emit diagnostics and return true.
resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult & SrcExpr)10760 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10761 ExprResult &SrcExpr) {
10762 Expr *E = SrcExpr.get();
10763 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10764
10765 DeclAccessPair DAP;
10766 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10767 if (!Found)
10768 return false;
10769
10770 // Emitting multiple diagnostics for a function that is both inaccessible and
10771 // unavailable is consistent with our behavior elsewhere. So, always check
10772 // for both.
10773 DiagnoseUseOfDecl(Found, E->getExprLoc());
10774 CheckAddressOfMemberAccess(E, DAP);
10775 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10776 if (Fixed->getType()->isFunctionType())
10777 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10778 else
10779 SrcExpr = Fixed;
10780 return true;
10781 }
10782
10783 /// \brief Given an expression that refers to an overloaded function, try to
10784 /// resolve that overloaded function expression down to a single function.
10785 ///
10786 /// This routine can only resolve template-ids that refer to a single function
10787 /// template, where that template-id refers to a single template whose template
10788 /// arguments are either provided by the template-id or have defaults,
10789 /// as described in C++0x [temp.arg.explicit]p3.
10790 ///
10791 /// If no template-ids are found, no diagnostics are emitted and NULL is
10792 /// returned.
10793 FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr * ovl,bool Complain,DeclAccessPair * FoundResult)10794 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10795 bool Complain,
10796 DeclAccessPair *FoundResult) {
10797 // C++ [over.over]p1:
10798 // [...] [Note: any redundant set of parentheses surrounding the
10799 // overloaded function name is ignored (5.1). ]
10800 // C++ [over.over]p1:
10801 // [...] The overloaded function name can be preceded by the &
10802 // operator.
10803
10804 // If we didn't actually find any template-ids, we're done.
10805 if (!ovl->hasExplicitTemplateArgs())
10806 return nullptr;
10807
10808 TemplateArgumentListInfo ExplicitTemplateArgs;
10809 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10810 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10811
10812 // Look through all of the overloaded functions, searching for one
10813 // whose type matches exactly.
10814 FunctionDecl *Matched = nullptr;
10815 for (UnresolvedSetIterator I = ovl->decls_begin(),
10816 E = ovl->decls_end(); I != E; ++I) {
10817 // C++0x [temp.arg.explicit]p3:
10818 // [...] In contexts where deduction is done and fails, or in contexts
10819 // where deduction is not done, if a template argument list is
10820 // specified and it, along with any default template arguments,
10821 // identifies a single function template specialization, then the
10822 // template-id is an lvalue for the function template specialization.
10823 FunctionTemplateDecl *FunctionTemplate
10824 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10825
10826 // C++ [over.over]p2:
10827 // If the name is a function template, template argument deduction is
10828 // done (14.8.2.2), and if the argument deduction succeeds, the
10829 // resulting template argument list is used to generate a single
10830 // function template specialization, which is added to the set of
10831 // overloaded functions considered.
10832 FunctionDecl *Specialization = nullptr;
10833 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10834 if (TemplateDeductionResult Result
10835 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10836 Specialization, Info,
10837 /*InOverloadResolution=*/true)) {
10838 // Make a note of the failed deduction for diagnostics.
10839 // TODO: Actually use the failed-deduction info?
10840 FailedCandidates.addCandidate()
10841 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
10842 MakeDeductionFailureInfo(Context, Result, Info));
10843 continue;
10844 }
10845
10846 assert(Specialization && "no specialization and no error?");
10847
10848 // Multiple matches; we can't resolve to a single declaration.
10849 if (Matched) {
10850 if (Complain) {
10851 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10852 << ovl->getName();
10853 NoteAllOverloadCandidates(ovl);
10854 }
10855 return nullptr;
10856 }
10857
10858 Matched = Specialization;
10859 if (FoundResult) *FoundResult = I.getPair();
10860 }
10861
10862 if (Matched && getLangOpts().CPlusPlus14 &&
10863 Matched->getReturnType()->isUndeducedType() &&
10864 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10865 return nullptr;
10866
10867 return Matched;
10868 }
10869
10870
10871
10872
10873 // Resolve and fix an overloaded expression that can be resolved
10874 // because it identifies a single function template specialization.
10875 //
10876 // Last three arguments should only be supplied if Complain = true
10877 //
10878 // Return true if it was logically possible to so resolve the
10879 // expression, regardless of whether or not it succeeded. Always
10880 // returns true if 'complain' is set.
ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult & SrcExpr,bool doFunctionPointerConverion,bool complain,SourceRange OpRangeForComplaining,QualType DestTypeForComplaining,unsigned DiagIDForComplaining)10881 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10882 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10883 bool complain, SourceRange OpRangeForComplaining,
10884 QualType DestTypeForComplaining,
10885 unsigned DiagIDForComplaining) {
10886 assert(SrcExpr.get()->getType() == Context.OverloadTy);
10887
10888 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10889
10890 DeclAccessPair found;
10891 ExprResult SingleFunctionExpression;
10892 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10893 ovl.Expression, /*complain*/ false, &found)) {
10894 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10895 SrcExpr = ExprError();
10896 return true;
10897 }
10898
10899 // It is only correct to resolve to an instance method if we're
10900 // resolving a form that's permitted to be a pointer to member.
10901 // Otherwise we'll end up making a bound member expression, which
10902 // is illegal in all the contexts we resolve like this.
10903 if (!ovl.HasFormOfMemberPointer &&
10904 isa<CXXMethodDecl>(fn) &&
10905 cast<CXXMethodDecl>(fn)->isInstance()) {
10906 if (!complain) return false;
10907
10908 Diag(ovl.Expression->getExprLoc(),
10909 diag::err_bound_member_function)
10910 << 0 << ovl.Expression->getSourceRange();
10911
10912 // TODO: I believe we only end up here if there's a mix of
10913 // static and non-static candidates (otherwise the expression
10914 // would have 'bound member' type, not 'overload' type).
10915 // Ideally we would note which candidate was chosen and why
10916 // the static candidates were rejected.
10917 SrcExpr = ExprError();
10918 return true;
10919 }
10920
10921 // Fix the expression to refer to 'fn'.
10922 SingleFunctionExpression =
10923 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10924
10925 // If desired, do function-to-pointer decay.
10926 if (doFunctionPointerConverion) {
10927 SingleFunctionExpression =
10928 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10929 if (SingleFunctionExpression.isInvalid()) {
10930 SrcExpr = ExprError();
10931 return true;
10932 }
10933 }
10934 }
10935
10936 if (!SingleFunctionExpression.isUsable()) {
10937 if (complain) {
10938 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10939 << ovl.Expression->getName()
10940 << DestTypeForComplaining
10941 << OpRangeForComplaining
10942 << ovl.Expression->getQualifierLoc().getSourceRange();
10943 NoteAllOverloadCandidates(SrcExpr.get());
10944
10945 SrcExpr = ExprError();
10946 return true;
10947 }
10948
10949 return false;
10950 }
10951
10952 SrcExpr = SingleFunctionExpression;
10953 return true;
10954 }
10955
10956 /// \brief Add a single candidate to the overload set.
AddOverloadedCallCandidate(Sema & S,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading,bool KnownValid)10957 static void AddOverloadedCallCandidate(Sema &S,
10958 DeclAccessPair FoundDecl,
10959 TemplateArgumentListInfo *ExplicitTemplateArgs,
10960 ArrayRef<Expr *> Args,
10961 OverloadCandidateSet &CandidateSet,
10962 bool PartialOverloading,
10963 bool KnownValid) {
10964 NamedDecl *Callee = FoundDecl.getDecl();
10965 if (isa<UsingShadowDecl>(Callee))
10966 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10967
10968 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10969 if (ExplicitTemplateArgs) {
10970 assert(!KnownValid && "Explicit template arguments?");
10971 return;
10972 }
10973 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10974 /*SuppressUsedConversions=*/false,
10975 PartialOverloading);
10976 return;
10977 }
10978
10979 if (FunctionTemplateDecl *FuncTemplate
10980 = dyn_cast<FunctionTemplateDecl>(Callee)) {
10981 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10982 ExplicitTemplateArgs, Args, CandidateSet,
10983 /*SuppressUsedConversions=*/false,
10984 PartialOverloading);
10985 return;
10986 }
10987
10988 assert(!KnownValid && "unhandled case in overloaded call candidate");
10989 }
10990
10991 /// \brief Add the overload candidates named by callee and/or found by argument
10992 /// dependent lookup to the given overload set.
AddOverloadedCallCandidates(UnresolvedLookupExpr * ULE,ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading)10993 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10994 ArrayRef<Expr *> Args,
10995 OverloadCandidateSet &CandidateSet,
10996 bool PartialOverloading) {
10997
10998 #ifndef NDEBUG
10999 // Verify that ArgumentDependentLookup is consistent with the rules
11000 // in C++0x [basic.lookup.argdep]p3:
11001 //
11002 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11003 // and let Y be the lookup set produced by argument dependent
11004 // lookup (defined as follows). If X contains
11005 //
11006 // -- a declaration of a class member, or
11007 //
11008 // -- a block-scope function declaration that is not a
11009 // using-declaration, or
11010 //
11011 // -- a declaration that is neither a function or a function
11012 // template
11013 //
11014 // then Y is empty.
11015
11016 if (ULE->requiresADL()) {
11017 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11018 E = ULE->decls_end(); I != E; ++I) {
11019 assert(!(*I)->getDeclContext()->isRecord());
11020 assert(isa<UsingShadowDecl>(*I) ||
11021 !(*I)->getDeclContext()->isFunctionOrMethod());
11022 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11023 }
11024 }
11025 #endif
11026
11027 // It would be nice to avoid this copy.
11028 TemplateArgumentListInfo TABuffer;
11029 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11030 if (ULE->hasExplicitTemplateArgs()) {
11031 ULE->copyTemplateArgumentsInto(TABuffer);
11032 ExplicitTemplateArgs = &TABuffer;
11033 }
11034
11035 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11036 E = ULE->decls_end(); I != E; ++I)
11037 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11038 CandidateSet, PartialOverloading,
11039 /*KnownValid*/ true);
11040
11041 if (ULE->requiresADL())
11042 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11043 Args, ExplicitTemplateArgs,
11044 CandidateSet, PartialOverloading);
11045 }
11046
11047 /// Determine whether a declaration with the specified name could be moved into
11048 /// a different namespace.
canBeDeclaredInNamespace(const DeclarationName & Name)11049 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11050 switch (Name.getCXXOverloadedOperator()) {
11051 case OO_New: case OO_Array_New:
11052 case OO_Delete: case OO_Array_Delete:
11053 return false;
11054
11055 default:
11056 return true;
11057 }
11058 }
11059
11060 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11061 /// template, where the non-dependent name was declared after the template
11062 /// was defined. This is common in code written for a compilers which do not
11063 /// correctly implement two-stage name lookup.
11064 ///
11065 /// Returns true if a viable candidate was found and a diagnostic was issued.
11066 static bool
DiagnoseTwoPhaseLookup(Sema & SemaRef,SourceLocation FnLoc,const CXXScopeSpec & SS,LookupResult & R,OverloadCandidateSet::CandidateSetKind CSK,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,bool * DoDiagnoseEmptyLookup=nullptr)11067 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11068 const CXXScopeSpec &SS, LookupResult &R,
11069 OverloadCandidateSet::CandidateSetKind CSK,
11070 TemplateArgumentListInfo *ExplicitTemplateArgs,
11071 ArrayRef<Expr *> Args,
11072 bool *DoDiagnoseEmptyLookup = nullptr) {
11073 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11074 return false;
11075
11076 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11077 if (DC->isTransparentContext())
11078 continue;
11079
11080 SemaRef.LookupQualifiedName(R, DC);
11081
11082 if (!R.empty()) {
11083 R.suppressDiagnostics();
11084
11085 if (isa<CXXRecordDecl>(DC)) {
11086 // Don't diagnose names we find in classes; we get much better
11087 // diagnostics for these from DiagnoseEmptyLookup.
11088 R.clear();
11089 if (DoDiagnoseEmptyLookup)
11090 *DoDiagnoseEmptyLookup = true;
11091 return false;
11092 }
11093
11094 OverloadCandidateSet Candidates(FnLoc, CSK);
11095 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11096 AddOverloadedCallCandidate(SemaRef, I.getPair(),
11097 ExplicitTemplateArgs, Args,
11098 Candidates, false, /*KnownValid*/ false);
11099
11100 OverloadCandidateSet::iterator Best;
11101 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11102 // No viable functions. Don't bother the user with notes for functions
11103 // which don't work and shouldn't be found anyway.
11104 R.clear();
11105 return false;
11106 }
11107
11108 // Find the namespaces where ADL would have looked, and suggest
11109 // declaring the function there instead.
11110 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11111 Sema::AssociatedClassSet AssociatedClasses;
11112 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11113 AssociatedNamespaces,
11114 AssociatedClasses);
11115 Sema::AssociatedNamespaceSet SuggestedNamespaces;
11116 if (canBeDeclaredInNamespace(R.getLookupName())) {
11117 DeclContext *Std = SemaRef.getStdNamespace();
11118 for (Sema::AssociatedNamespaceSet::iterator
11119 it = AssociatedNamespaces.begin(),
11120 end = AssociatedNamespaces.end(); it != end; ++it) {
11121 // Never suggest declaring a function within namespace 'std'.
11122 if (Std && Std->Encloses(*it))
11123 continue;
11124
11125 // Never suggest declaring a function within a namespace with a
11126 // reserved name, like __gnu_cxx.
11127 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11128 if (NS &&
11129 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11130 continue;
11131
11132 SuggestedNamespaces.insert(*it);
11133 }
11134 }
11135
11136 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11137 << R.getLookupName();
11138 if (SuggestedNamespaces.empty()) {
11139 SemaRef.Diag(Best->Function->getLocation(),
11140 diag::note_not_found_by_two_phase_lookup)
11141 << R.getLookupName() << 0;
11142 } else if (SuggestedNamespaces.size() == 1) {
11143 SemaRef.Diag(Best->Function->getLocation(),
11144 diag::note_not_found_by_two_phase_lookup)
11145 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11146 } else {
11147 // FIXME: It would be useful to list the associated namespaces here,
11148 // but the diagnostics infrastructure doesn't provide a way to produce
11149 // a localized representation of a list of items.
11150 SemaRef.Diag(Best->Function->getLocation(),
11151 diag::note_not_found_by_two_phase_lookup)
11152 << R.getLookupName() << 2;
11153 }
11154
11155 // Try to recover by calling this function.
11156 return true;
11157 }
11158
11159 R.clear();
11160 }
11161
11162 return false;
11163 }
11164
11165 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11166 /// template, where the non-dependent operator was declared after the template
11167 /// was defined.
11168 ///
11169 /// Returns true if a viable candidate was found and a diagnostic was issued.
11170 static bool
DiagnoseTwoPhaseOperatorLookup(Sema & SemaRef,OverloadedOperatorKind Op,SourceLocation OpLoc,ArrayRef<Expr * > Args)11171 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11172 SourceLocation OpLoc,
11173 ArrayRef<Expr *> Args) {
11174 DeclarationName OpName =
11175 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11176 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11177 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11178 OverloadCandidateSet::CSK_Operator,
11179 /*ExplicitTemplateArgs=*/nullptr, Args);
11180 }
11181
11182 namespace {
11183 class BuildRecoveryCallExprRAII {
11184 Sema &SemaRef;
11185 public:
BuildRecoveryCallExprRAII(Sema & S)11186 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11187 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11188 SemaRef.IsBuildingRecoveryCallExpr = true;
11189 }
11190
~BuildRecoveryCallExprRAII()11191 ~BuildRecoveryCallExprRAII() {
11192 SemaRef.IsBuildingRecoveryCallExpr = false;
11193 }
11194 };
11195
11196 }
11197
11198 static std::unique_ptr<CorrectionCandidateCallback>
MakeValidator(Sema & SemaRef,MemberExpr * ME,size_t NumArgs,bool HasTemplateArgs,bool AllowTypoCorrection)11199 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11200 bool HasTemplateArgs, bool AllowTypoCorrection) {
11201 if (!AllowTypoCorrection)
11202 return llvm::make_unique<NoTypoCorrectionCCC>();
11203 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11204 HasTemplateArgs, ME);
11205 }
11206
11207 /// Attempts to recover from a call where no functions were found.
11208 ///
11209 /// Returns true if new candidates were found.
11210 static ExprResult
BuildRecoveryCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MutableArrayRef<Expr * > Args,SourceLocation RParenLoc,bool EmptyLookup,bool AllowTypoCorrection)11211 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11212 UnresolvedLookupExpr *ULE,
11213 SourceLocation LParenLoc,
11214 MutableArrayRef<Expr *> Args,
11215 SourceLocation RParenLoc,
11216 bool EmptyLookup, bool AllowTypoCorrection) {
11217 // Do not try to recover if it is already building a recovery call.
11218 // This stops infinite loops for template instantiations like
11219 //
11220 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11221 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11222 //
11223 if (SemaRef.IsBuildingRecoveryCallExpr)
11224 return ExprError();
11225 BuildRecoveryCallExprRAII RCE(SemaRef);
11226
11227 CXXScopeSpec SS;
11228 SS.Adopt(ULE->getQualifierLoc());
11229 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11230
11231 TemplateArgumentListInfo TABuffer;
11232 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11233 if (ULE->hasExplicitTemplateArgs()) {
11234 ULE->copyTemplateArgumentsInto(TABuffer);
11235 ExplicitTemplateArgs = &TABuffer;
11236 }
11237
11238 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11239 Sema::LookupOrdinaryName);
11240 bool DoDiagnoseEmptyLookup = EmptyLookup;
11241 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11242 OverloadCandidateSet::CSK_Normal,
11243 ExplicitTemplateArgs, Args,
11244 &DoDiagnoseEmptyLookup) &&
11245 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11246 S, SS, R,
11247 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11248 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11249 ExplicitTemplateArgs, Args)))
11250 return ExprError();
11251
11252 assert(!R.empty() && "lookup results empty despite recovery");
11253
11254 // Build an implicit member call if appropriate. Just drop the
11255 // casts and such from the call, we don't really care.
11256 ExprResult NewFn = ExprError();
11257 if ((*R.begin())->isCXXClassMember())
11258 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11259 ExplicitTemplateArgs, S);
11260 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11261 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11262 ExplicitTemplateArgs);
11263 else
11264 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11265
11266 if (NewFn.isInvalid())
11267 return ExprError();
11268
11269 // This shouldn't cause an infinite loop because we're giving it
11270 // an expression with viable lookup results, which should never
11271 // end up here.
11272 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11273 MultiExprArg(Args.data(), Args.size()),
11274 RParenLoc);
11275 }
11276
11277 /// \brief Constructs and populates an OverloadedCandidateSet from
11278 /// the given function.
11279 /// \returns true when an the ExprResult output parameter has been set.
buildOverloadedCallSet(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,MultiExprArg Args,SourceLocation RParenLoc,OverloadCandidateSet * CandidateSet,ExprResult * Result)11280 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11281 UnresolvedLookupExpr *ULE,
11282 MultiExprArg Args,
11283 SourceLocation RParenLoc,
11284 OverloadCandidateSet *CandidateSet,
11285 ExprResult *Result) {
11286 #ifndef NDEBUG
11287 if (ULE->requiresADL()) {
11288 // To do ADL, we must have found an unqualified name.
11289 assert(!ULE->getQualifier() && "qualified name with ADL");
11290
11291 // We don't perform ADL for implicit declarations of builtins.
11292 // Verify that this was correctly set up.
11293 FunctionDecl *F;
11294 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11295 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11296 F->getBuiltinID() && F->isImplicit())
11297 llvm_unreachable("performing ADL for builtin");
11298
11299 // We don't perform ADL in C.
11300 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11301 }
11302 #endif
11303
11304 UnbridgedCastsSet UnbridgedCasts;
11305 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11306 *Result = ExprError();
11307 return true;
11308 }
11309
11310 // Add the functions denoted by the callee to the set of candidate
11311 // functions, including those from argument-dependent lookup.
11312 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11313
11314 if (getLangOpts().MSVCCompat &&
11315 CurContext->isDependentContext() && !isSFINAEContext() &&
11316 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11317
11318 OverloadCandidateSet::iterator Best;
11319 if (CandidateSet->empty() ||
11320 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11321 OR_No_Viable_Function) {
11322 // In Microsoft mode, if we are inside a template class member function then
11323 // create a type dependent CallExpr. The goal is to postpone name lookup
11324 // to instantiation time to be able to search into type dependent base
11325 // classes.
11326 CallExpr *CE = new (Context) CallExpr(
11327 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11328 CE->setTypeDependent(true);
11329 CE->setValueDependent(true);
11330 CE->setInstantiationDependent(true);
11331 *Result = CE;
11332 return true;
11333 }
11334 }
11335
11336 if (CandidateSet->empty())
11337 return false;
11338
11339 UnbridgedCasts.restore();
11340 return false;
11341 }
11342
11343 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11344 /// the completed call expression. If overload resolution fails, emits
11345 /// diagnostics and returns ExprError()
FinishOverloadedCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,OverloadCandidateSet * CandidateSet,OverloadCandidateSet::iterator * Best,OverloadingResult OverloadResult,bool AllowTypoCorrection)11346 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11347 UnresolvedLookupExpr *ULE,
11348 SourceLocation LParenLoc,
11349 MultiExprArg Args,
11350 SourceLocation RParenLoc,
11351 Expr *ExecConfig,
11352 OverloadCandidateSet *CandidateSet,
11353 OverloadCandidateSet::iterator *Best,
11354 OverloadingResult OverloadResult,
11355 bool AllowTypoCorrection) {
11356 if (CandidateSet->empty())
11357 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11358 RParenLoc, /*EmptyLookup=*/true,
11359 AllowTypoCorrection);
11360
11361 switch (OverloadResult) {
11362 case OR_Success: {
11363 FunctionDecl *FDecl = (*Best)->Function;
11364 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11365 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11366 return ExprError();
11367 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11368 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11369 ExecConfig);
11370 }
11371
11372 case OR_No_Viable_Function: {
11373 // Try to recover by looking for viable functions which the user might
11374 // have meant to call.
11375 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11376 Args, RParenLoc,
11377 /*EmptyLookup=*/false,
11378 AllowTypoCorrection);
11379 if (!Recovery.isInvalid())
11380 return Recovery;
11381
11382 // If the user passes in a function that we can't take the address of, we
11383 // generally end up emitting really bad error messages. Here, we attempt to
11384 // emit better ones.
11385 for (const Expr *Arg : Args) {
11386 if (!Arg->getType()->isFunctionType())
11387 continue;
11388 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11389 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11390 if (FD &&
11391 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11392 Arg->getExprLoc()))
11393 return ExprError();
11394 }
11395 }
11396
11397 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11398 << ULE->getName() << Fn->getSourceRange();
11399 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11400 break;
11401 }
11402
11403 case OR_Ambiguous:
11404 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11405 << ULE->getName() << Fn->getSourceRange();
11406 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11407 break;
11408
11409 case OR_Deleted: {
11410 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11411 << (*Best)->Function->isDeleted()
11412 << ULE->getName()
11413 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11414 << Fn->getSourceRange();
11415 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11416
11417 // We emitted an error for the unvailable/deleted function call but keep
11418 // the call in the AST.
11419 FunctionDecl *FDecl = (*Best)->Function;
11420 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11421 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11422 ExecConfig);
11423 }
11424 }
11425
11426 // Overload resolution failed.
11427 return ExprError();
11428 }
11429
markUnaddressableCandidatesUnviable(Sema & S,OverloadCandidateSet & CS)11430 static void markUnaddressableCandidatesUnviable(Sema &S,
11431 OverloadCandidateSet &CS) {
11432 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11433 if (I->Viable &&
11434 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11435 I->Viable = false;
11436 I->FailureKind = ovl_fail_addr_not_available;
11437 }
11438 }
11439 }
11440
11441 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11442 /// (which eventually refers to the declaration Func) and the call
11443 /// arguments Args/NumArgs, attempt to resolve the function call down
11444 /// to a specific function. If overload resolution succeeds, returns
11445 /// the call expression produced by overload resolution.
11446 /// Otherwise, emits diagnostics and returns ExprError.
BuildOverloadedCallExpr(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig,bool AllowTypoCorrection,bool CalleesAddressIsTaken)11447 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11448 UnresolvedLookupExpr *ULE,
11449 SourceLocation LParenLoc,
11450 MultiExprArg Args,
11451 SourceLocation RParenLoc,
11452 Expr *ExecConfig,
11453 bool AllowTypoCorrection,
11454 bool CalleesAddressIsTaken) {
11455 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11456 OverloadCandidateSet::CSK_Normal);
11457 ExprResult result;
11458
11459 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11460 &result))
11461 return result;
11462
11463 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11464 // functions that aren't addressible are considered unviable.
11465 if (CalleesAddressIsTaken)
11466 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11467
11468 OverloadCandidateSet::iterator Best;
11469 OverloadingResult OverloadResult =
11470 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11471
11472 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11473 RParenLoc, ExecConfig, &CandidateSet,
11474 &Best, OverloadResult,
11475 AllowTypoCorrection);
11476 }
11477
IsOverloaded(const UnresolvedSetImpl & Functions)11478 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11479 return Functions.size() > 1 ||
11480 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11481 }
11482
11483 /// \brief Create a unary operation that may resolve to an overloaded
11484 /// operator.
11485 ///
11486 /// \param OpLoc The location of the operator itself (e.g., '*').
11487 ///
11488 /// \param Opc The UnaryOperatorKind that describes this operator.
11489 ///
11490 /// \param Fns The set of non-member functions that will be
11491 /// considered by overload resolution. The caller needs to build this
11492 /// set based on the context using, e.g.,
11493 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11494 /// set should not contain any member functions; those will be added
11495 /// by CreateOverloadedUnaryOp().
11496 ///
11497 /// \param Input The input argument.
11498 ExprResult
CreateOverloadedUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,const UnresolvedSetImpl & Fns,Expr * Input)11499 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11500 const UnresolvedSetImpl &Fns,
11501 Expr *Input) {
11502 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11503 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11504 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11505 // TODO: provide better source location info.
11506 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11507
11508 if (checkPlaceholderForOverload(*this, Input))
11509 return ExprError();
11510
11511 Expr *Args[2] = { Input, nullptr };
11512 unsigned NumArgs = 1;
11513
11514 // For post-increment and post-decrement, add the implicit '0' as
11515 // the second argument, so that we know this is a post-increment or
11516 // post-decrement.
11517 if (Opc == UO_PostInc || Opc == UO_PostDec) {
11518 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11519 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11520 SourceLocation());
11521 NumArgs = 2;
11522 }
11523
11524 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11525
11526 if (Input->isTypeDependent()) {
11527 if (Fns.empty())
11528 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11529 VK_RValue, OK_Ordinary, OpLoc);
11530
11531 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11532 UnresolvedLookupExpr *Fn
11533 = UnresolvedLookupExpr::Create(Context, NamingClass,
11534 NestedNameSpecifierLoc(), OpNameInfo,
11535 /*ADL*/ true, IsOverloaded(Fns),
11536 Fns.begin(), Fns.end());
11537 return new (Context)
11538 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11539 VK_RValue, OpLoc, false);
11540 }
11541
11542 // Build an empty overload set.
11543 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11544
11545 // Add the candidates from the given function set.
11546 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11547
11548 // Add operator candidates that are member functions.
11549 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11550
11551 // Add candidates from ADL.
11552 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11553 /*ExplicitTemplateArgs*/nullptr,
11554 CandidateSet);
11555
11556 // Add builtin operator candidates.
11557 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11558
11559 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11560
11561 // Perform overload resolution.
11562 OverloadCandidateSet::iterator Best;
11563 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11564 case OR_Success: {
11565 // We found a built-in operator or an overloaded operator.
11566 FunctionDecl *FnDecl = Best->Function;
11567
11568 if (FnDecl) {
11569 // We matched an overloaded operator. Build a call to that
11570 // operator.
11571
11572 // Convert the arguments.
11573 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11574 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11575
11576 ExprResult InputRes =
11577 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11578 Best->FoundDecl, Method);
11579 if (InputRes.isInvalid())
11580 return ExprError();
11581 Input = InputRes.get();
11582 } else {
11583 // Convert the arguments.
11584 ExprResult InputInit
11585 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11586 Context,
11587 FnDecl->getParamDecl(0)),
11588 SourceLocation(),
11589 Input);
11590 if (InputInit.isInvalid())
11591 return ExprError();
11592 Input = InputInit.get();
11593 }
11594
11595 // Build the actual expression node.
11596 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11597 HadMultipleCandidates, OpLoc);
11598 if (FnExpr.isInvalid())
11599 return ExprError();
11600
11601 // Determine the result type.
11602 QualType ResultTy = FnDecl->getReturnType();
11603 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11604 ResultTy = ResultTy.getNonLValueExprType(Context);
11605
11606 Args[0] = Input;
11607 CallExpr *TheCall =
11608 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11609 ResultTy, VK, OpLoc, false);
11610
11611 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11612 return ExprError();
11613
11614 return MaybeBindToTemporary(TheCall);
11615 } else {
11616 // We matched a built-in operator. Convert the arguments, then
11617 // break out so that we will build the appropriate built-in
11618 // operator node.
11619 ExprResult InputRes =
11620 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11621 Best->Conversions[0], AA_Passing);
11622 if (InputRes.isInvalid())
11623 return ExprError();
11624 Input = InputRes.get();
11625 break;
11626 }
11627 }
11628
11629 case OR_No_Viable_Function:
11630 // This is an erroneous use of an operator which can be overloaded by
11631 // a non-member function. Check for non-member operators which were
11632 // defined too late to be candidates.
11633 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11634 // FIXME: Recover by calling the found function.
11635 return ExprError();
11636
11637 // No viable function; fall through to handling this as a
11638 // built-in operator, which will produce an error message for us.
11639 break;
11640
11641 case OR_Ambiguous:
11642 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11643 << UnaryOperator::getOpcodeStr(Opc)
11644 << Input->getType()
11645 << Input->getSourceRange();
11646 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11647 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11648 return ExprError();
11649
11650 case OR_Deleted:
11651 Diag(OpLoc, diag::err_ovl_deleted_oper)
11652 << Best->Function->isDeleted()
11653 << UnaryOperator::getOpcodeStr(Opc)
11654 << getDeletedOrUnavailableSuffix(Best->Function)
11655 << Input->getSourceRange();
11656 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11657 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11658 return ExprError();
11659 }
11660
11661 // Either we found no viable overloaded operator or we matched a
11662 // built-in operator. In either case, fall through to trying to
11663 // build a built-in operation.
11664 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11665 }
11666
11667 /// \brief Create a binary operation that may resolve to an overloaded
11668 /// operator.
11669 ///
11670 /// \param OpLoc The location of the operator itself (e.g., '+').
11671 ///
11672 /// \param Opc The BinaryOperatorKind that describes this operator.
11673 ///
11674 /// \param Fns The set of non-member functions that will be
11675 /// considered by overload resolution. The caller needs to build this
11676 /// set based on the context using, e.g.,
11677 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11678 /// set should not contain any member functions; those will be added
11679 /// by CreateOverloadedBinOp().
11680 ///
11681 /// \param LHS Left-hand argument.
11682 /// \param RHS Right-hand argument.
11683 ExprResult
CreateOverloadedBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,const UnresolvedSetImpl & Fns,Expr * LHS,Expr * RHS)11684 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11685 BinaryOperatorKind Opc,
11686 const UnresolvedSetImpl &Fns,
11687 Expr *LHS, Expr *RHS) {
11688 Expr *Args[2] = { LHS, RHS };
11689 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11690
11691 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11692 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11693
11694 // If either side is type-dependent, create an appropriate dependent
11695 // expression.
11696 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11697 if (Fns.empty()) {
11698 // If there are no functions to store, just build a dependent
11699 // BinaryOperator or CompoundAssignment.
11700 if (Opc <= BO_Assign || Opc > BO_OrAssign)
11701 return new (Context) BinaryOperator(
11702 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11703 OpLoc, FPFeatures.fp_contract);
11704
11705 return new (Context) CompoundAssignOperator(
11706 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11707 Context.DependentTy, Context.DependentTy, OpLoc,
11708 FPFeatures.fp_contract);
11709 }
11710
11711 // FIXME: save results of ADL from here?
11712 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11713 // TODO: provide better source location info in DNLoc component.
11714 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11715 UnresolvedLookupExpr *Fn
11716 = UnresolvedLookupExpr::Create(Context, NamingClass,
11717 NestedNameSpecifierLoc(), OpNameInfo,
11718 /*ADL*/ true, IsOverloaded(Fns),
11719 Fns.begin(), Fns.end());
11720 return new (Context)
11721 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11722 VK_RValue, OpLoc, FPFeatures.fp_contract);
11723 }
11724
11725 // Always do placeholder-like conversions on the RHS.
11726 if (checkPlaceholderForOverload(*this, Args[1]))
11727 return ExprError();
11728
11729 // Do placeholder-like conversion on the LHS; note that we should
11730 // not get here with a PseudoObject LHS.
11731 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11732 if (checkPlaceholderForOverload(*this, Args[0]))
11733 return ExprError();
11734
11735 // If this is the assignment operator, we only perform overload resolution
11736 // if the left-hand side is a class or enumeration type. This is actually
11737 // a hack. The standard requires that we do overload resolution between the
11738 // various built-in candidates, but as DR507 points out, this can lead to
11739 // problems. So we do it this way, which pretty much follows what GCC does.
11740 // Note that we go the traditional code path for compound assignment forms.
11741 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11742 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11743
11744 // If this is the .* operator, which is not overloadable, just
11745 // create a built-in binary operator.
11746 if (Opc == BO_PtrMemD)
11747 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11748
11749 // Build an empty overload set.
11750 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11751
11752 // Add the candidates from the given function set.
11753 AddFunctionCandidates(Fns, Args, CandidateSet);
11754
11755 // Add operator candidates that are member functions.
11756 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11757
11758 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11759 // performed for an assignment operator (nor for operator[] nor operator->,
11760 // which don't get here).
11761 if (Opc != BO_Assign)
11762 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11763 /*ExplicitTemplateArgs*/ nullptr,
11764 CandidateSet);
11765
11766 // Add builtin operator candidates.
11767 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11768
11769 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11770
11771 // Perform overload resolution.
11772 OverloadCandidateSet::iterator Best;
11773 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11774 case OR_Success: {
11775 // We found a built-in operator or an overloaded operator.
11776 FunctionDecl *FnDecl = Best->Function;
11777
11778 if (FnDecl) {
11779 // We matched an overloaded operator. Build a call to that
11780 // operator.
11781
11782 // Convert the arguments.
11783 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11784 // Best->Access is only meaningful for class members.
11785 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11786
11787 ExprResult Arg1 =
11788 PerformCopyInitialization(
11789 InitializedEntity::InitializeParameter(Context,
11790 FnDecl->getParamDecl(0)),
11791 SourceLocation(), Args[1]);
11792 if (Arg1.isInvalid())
11793 return ExprError();
11794
11795 ExprResult Arg0 =
11796 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11797 Best->FoundDecl, Method);
11798 if (Arg0.isInvalid())
11799 return ExprError();
11800 Args[0] = Arg0.getAs<Expr>();
11801 Args[1] = RHS = Arg1.getAs<Expr>();
11802 } else {
11803 // Convert the arguments.
11804 ExprResult Arg0 = PerformCopyInitialization(
11805 InitializedEntity::InitializeParameter(Context,
11806 FnDecl->getParamDecl(0)),
11807 SourceLocation(), Args[0]);
11808 if (Arg0.isInvalid())
11809 return ExprError();
11810
11811 ExprResult Arg1 =
11812 PerformCopyInitialization(
11813 InitializedEntity::InitializeParameter(Context,
11814 FnDecl->getParamDecl(1)),
11815 SourceLocation(), Args[1]);
11816 if (Arg1.isInvalid())
11817 return ExprError();
11818 Args[0] = LHS = Arg0.getAs<Expr>();
11819 Args[1] = RHS = Arg1.getAs<Expr>();
11820 }
11821
11822 // Build the actual expression node.
11823 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11824 Best->FoundDecl,
11825 HadMultipleCandidates, OpLoc);
11826 if (FnExpr.isInvalid())
11827 return ExprError();
11828
11829 // Determine the result type.
11830 QualType ResultTy = FnDecl->getReturnType();
11831 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11832 ResultTy = ResultTy.getNonLValueExprType(Context);
11833
11834 CXXOperatorCallExpr *TheCall =
11835 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11836 Args, ResultTy, VK, OpLoc,
11837 FPFeatures.fp_contract);
11838
11839 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11840 FnDecl))
11841 return ExprError();
11842
11843 ArrayRef<const Expr *> ArgsArray(Args, 2);
11844 // Cut off the implicit 'this'.
11845 if (isa<CXXMethodDecl>(FnDecl))
11846 ArgsArray = ArgsArray.slice(1);
11847
11848 // Check for a self move.
11849 if (Op == OO_Equal)
11850 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11851
11852 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11853 TheCall->getSourceRange(), VariadicDoesNotApply);
11854
11855 return MaybeBindToTemporary(TheCall);
11856 } else {
11857 // We matched a built-in operator. Convert the arguments, then
11858 // break out so that we will build the appropriate built-in
11859 // operator node.
11860 ExprResult ArgsRes0 =
11861 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11862 Best->Conversions[0], AA_Passing);
11863 if (ArgsRes0.isInvalid())
11864 return ExprError();
11865 Args[0] = ArgsRes0.get();
11866
11867 ExprResult ArgsRes1 =
11868 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11869 Best->Conversions[1], AA_Passing);
11870 if (ArgsRes1.isInvalid())
11871 return ExprError();
11872 Args[1] = ArgsRes1.get();
11873 break;
11874 }
11875 }
11876
11877 case OR_No_Viable_Function: {
11878 // C++ [over.match.oper]p9:
11879 // If the operator is the operator , [...] and there are no
11880 // viable functions, then the operator is assumed to be the
11881 // built-in operator and interpreted according to clause 5.
11882 if (Opc == BO_Comma)
11883 break;
11884
11885 // For class as left operand for assignment or compound assigment
11886 // operator do not fall through to handling in built-in, but report that
11887 // no overloaded assignment operator found
11888 ExprResult Result = ExprError();
11889 if (Args[0]->getType()->isRecordType() &&
11890 Opc >= BO_Assign && Opc <= BO_OrAssign) {
11891 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11892 << BinaryOperator::getOpcodeStr(Opc)
11893 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11894 if (Args[0]->getType()->isIncompleteType()) {
11895 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11896 << Args[0]->getType()
11897 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11898 }
11899 } else {
11900 // This is an erroneous use of an operator which can be overloaded by
11901 // a non-member function. Check for non-member operators which were
11902 // defined too late to be candidates.
11903 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11904 // FIXME: Recover by calling the found function.
11905 return ExprError();
11906
11907 // No viable function; try to create a built-in operation, which will
11908 // produce an error. Then, show the non-viable candidates.
11909 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11910 }
11911 assert(Result.isInvalid() &&
11912 "C++ binary operator overloading is missing candidates!");
11913 if (Result.isInvalid())
11914 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11915 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11916 return Result;
11917 }
11918
11919 case OR_Ambiguous:
11920 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
11921 << BinaryOperator::getOpcodeStr(Opc)
11922 << Args[0]->getType() << Args[1]->getType()
11923 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11924 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11925 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11926 return ExprError();
11927
11928 case OR_Deleted:
11929 if (isImplicitlyDeleted(Best->Function)) {
11930 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11931 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11932 << Context.getRecordType(Method->getParent())
11933 << getSpecialMember(Method);
11934
11935 // The user probably meant to call this special member. Just
11936 // explain why it's deleted.
11937 NoteDeletedFunction(Method);
11938 return ExprError();
11939 } else {
11940 Diag(OpLoc, diag::err_ovl_deleted_oper)
11941 << Best->Function->isDeleted()
11942 << BinaryOperator::getOpcodeStr(Opc)
11943 << getDeletedOrUnavailableSuffix(Best->Function)
11944 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11945 }
11946 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11947 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11948 return ExprError();
11949 }
11950
11951 // We matched a built-in operator; build it.
11952 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11953 }
11954
11955 ExprResult
CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,SourceLocation RLoc,Expr * Base,Expr * Idx)11956 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11957 SourceLocation RLoc,
11958 Expr *Base, Expr *Idx) {
11959 Expr *Args[2] = { Base, Idx };
11960 DeclarationName OpName =
11961 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11962
11963 // If either side is type-dependent, create an appropriate dependent
11964 // expression.
11965 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11966
11967 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11968 // CHECKME: no 'operator' keyword?
11969 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11970 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11971 UnresolvedLookupExpr *Fn
11972 = UnresolvedLookupExpr::Create(Context, NamingClass,
11973 NestedNameSpecifierLoc(), OpNameInfo,
11974 /*ADL*/ true, /*Overloaded*/ false,
11975 UnresolvedSetIterator(),
11976 UnresolvedSetIterator());
11977 // Can't add any actual overloads yet
11978
11979 return new (Context)
11980 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11981 Context.DependentTy, VK_RValue, RLoc, false);
11982 }
11983
11984 // Handle placeholders on both operands.
11985 if (checkPlaceholderForOverload(*this, Args[0]))
11986 return ExprError();
11987 if (checkPlaceholderForOverload(*this, Args[1]))
11988 return ExprError();
11989
11990 // Build an empty overload set.
11991 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11992
11993 // Subscript can only be overloaded as a member function.
11994
11995 // Add operator candidates that are member functions.
11996 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11997
11998 // Add builtin operator candidates.
11999 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12000
12001 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12002
12003 // Perform overload resolution.
12004 OverloadCandidateSet::iterator Best;
12005 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12006 case OR_Success: {
12007 // We found a built-in operator or an overloaded operator.
12008 FunctionDecl *FnDecl = Best->Function;
12009
12010 if (FnDecl) {
12011 // We matched an overloaded operator. Build a call to that
12012 // operator.
12013
12014 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12015
12016 // Convert the arguments.
12017 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12018 ExprResult Arg0 =
12019 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12020 Best->FoundDecl, Method);
12021 if (Arg0.isInvalid())
12022 return ExprError();
12023 Args[0] = Arg0.get();
12024
12025 // Convert the arguments.
12026 ExprResult InputInit
12027 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12028 Context,
12029 FnDecl->getParamDecl(0)),
12030 SourceLocation(),
12031 Args[1]);
12032 if (InputInit.isInvalid())
12033 return ExprError();
12034
12035 Args[1] = InputInit.getAs<Expr>();
12036
12037 // Build the actual expression node.
12038 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12039 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12040 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12041 Best->FoundDecl,
12042 HadMultipleCandidates,
12043 OpLocInfo.getLoc(),
12044 OpLocInfo.getInfo());
12045 if (FnExpr.isInvalid())
12046 return ExprError();
12047
12048 // Determine the result type
12049 QualType ResultTy = FnDecl->getReturnType();
12050 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12051 ResultTy = ResultTy.getNonLValueExprType(Context);
12052
12053 CXXOperatorCallExpr *TheCall =
12054 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12055 FnExpr.get(), Args,
12056 ResultTy, VK, RLoc,
12057 false);
12058
12059 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12060 return ExprError();
12061
12062 return MaybeBindToTemporary(TheCall);
12063 } else {
12064 // We matched a built-in operator. Convert the arguments, then
12065 // break out so that we will build the appropriate built-in
12066 // operator node.
12067 ExprResult ArgsRes0 =
12068 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12069 Best->Conversions[0], AA_Passing);
12070 if (ArgsRes0.isInvalid())
12071 return ExprError();
12072 Args[0] = ArgsRes0.get();
12073
12074 ExprResult ArgsRes1 =
12075 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12076 Best->Conversions[1], AA_Passing);
12077 if (ArgsRes1.isInvalid())
12078 return ExprError();
12079 Args[1] = ArgsRes1.get();
12080
12081 break;
12082 }
12083 }
12084
12085 case OR_No_Viable_Function: {
12086 if (CandidateSet.empty())
12087 Diag(LLoc, diag::err_ovl_no_oper)
12088 << Args[0]->getType() << /*subscript*/ 0
12089 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12090 else
12091 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12092 << Args[0]->getType()
12093 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12094 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12095 "[]", LLoc);
12096 return ExprError();
12097 }
12098
12099 case OR_Ambiguous:
12100 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
12101 << "[]"
12102 << Args[0]->getType() << Args[1]->getType()
12103 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12104 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12105 "[]", LLoc);
12106 return ExprError();
12107
12108 case OR_Deleted:
12109 Diag(LLoc, diag::err_ovl_deleted_oper)
12110 << Best->Function->isDeleted() << "[]"
12111 << getDeletedOrUnavailableSuffix(Best->Function)
12112 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12113 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12114 "[]", LLoc);
12115 return ExprError();
12116 }
12117
12118 // We matched a built-in operator; build it.
12119 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12120 }
12121
12122 /// BuildCallToMemberFunction - Build a call to a member
12123 /// function. MemExpr is the expression that refers to the member
12124 /// function (and includes the object parameter), Args/NumArgs are the
12125 /// arguments to the function call (not including the object
12126 /// parameter). The caller needs to validate that the member
12127 /// expression refers to a non-static member function or an overloaded
12128 /// member function.
12129 ExprResult
BuildCallToMemberFunction(Scope * S,Expr * MemExprE,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc)12130 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12131 SourceLocation LParenLoc,
12132 MultiExprArg Args,
12133 SourceLocation RParenLoc) {
12134 assert(MemExprE->getType() == Context.BoundMemberTy ||
12135 MemExprE->getType() == Context.OverloadTy);
12136
12137 // Dig out the member expression. This holds both the object
12138 // argument and the member function we're referring to.
12139 Expr *NakedMemExpr = MemExprE->IgnoreParens();
12140
12141 // Determine whether this is a call to a pointer-to-member function.
12142 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12143 assert(op->getType() == Context.BoundMemberTy);
12144 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12145
12146 QualType fnType =
12147 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12148
12149 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12150 QualType resultType = proto->getCallResultType(Context);
12151 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12152
12153 // Check that the object type isn't more qualified than the
12154 // member function we're calling.
12155 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12156
12157 QualType objectType = op->getLHS()->getType();
12158 if (op->getOpcode() == BO_PtrMemI)
12159 objectType = objectType->castAs<PointerType>()->getPointeeType();
12160 Qualifiers objectQuals = objectType.getQualifiers();
12161
12162 Qualifiers difference = objectQuals - funcQuals;
12163 difference.removeObjCGCAttr();
12164 difference.removeAddressSpace();
12165 if (difference) {
12166 std::string qualsString = difference.getAsString();
12167 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12168 << fnType.getUnqualifiedType()
12169 << qualsString
12170 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12171 }
12172
12173 CXXMemberCallExpr *call
12174 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12175 resultType, valueKind, RParenLoc);
12176
12177 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12178 call, nullptr))
12179 return ExprError();
12180
12181 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12182 return ExprError();
12183
12184 if (CheckOtherCall(call, proto))
12185 return ExprError();
12186
12187 return MaybeBindToTemporary(call);
12188 }
12189
12190 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12191 return new (Context)
12192 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12193
12194 UnbridgedCastsSet UnbridgedCasts;
12195 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12196 return ExprError();
12197
12198 MemberExpr *MemExpr;
12199 CXXMethodDecl *Method = nullptr;
12200 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12201 NestedNameSpecifier *Qualifier = nullptr;
12202 if (isa<MemberExpr>(NakedMemExpr)) {
12203 MemExpr = cast<MemberExpr>(NakedMemExpr);
12204 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12205 FoundDecl = MemExpr->getFoundDecl();
12206 Qualifier = MemExpr->getQualifier();
12207 UnbridgedCasts.restore();
12208 } else {
12209 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12210 Qualifier = UnresExpr->getQualifier();
12211
12212 QualType ObjectType = UnresExpr->getBaseType();
12213 Expr::Classification ObjectClassification
12214 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12215 : UnresExpr->getBase()->Classify(Context);
12216
12217 // Add overload candidates
12218 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12219 OverloadCandidateSet::CSK_Normal);
12220
12221 // FIXME: avoid copy.
12222 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12223 if (UnresExpr->hasExplicitTemplateArgs()) {
12224 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12225 TemplateArgs = &TemplateArgsBuffer;
12226 }
12227
12228 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12229 E = UnresExpr->decls_end(); I != E; ++I) {
12230
12231 NamedDecl *Func = *I;
12232 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12233 if (isa<UsingShadowDecl>(Func))
12234 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12235
12236
12237 // Microsoft supports direct constructor calls.
12238 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12239 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12240 Args, CandidateSet);
12241 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12242 // If explicit template arguments were provided, we can't call a
12243 // non-template member function.
12244 if (TemplateArgs)
12245 continue;
12246
12247 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12248 ObjectClassification, Args, CandidateSet,
12249 /*SuppressUserConversions=*/false);
12250 } else {
12251 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12252 I.getPair(), ActingDC, TemplateArgs,
12253 ObjectType, ObjectClassification,
12254 Args, CandidateSet,
12255 /*SuppressUsedConversions=*/false);
12256 }
12257 }
12258
12259 DeclarationName DeclName = UnresExpr->getMemberName();
12260
12261 UnbridgedCasts.restore();
12262
12263 OverloadCandidateSet::iterator Best;
12264 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12265 Best)) {
12266 case OR_Success:
12267 Method = cast<CXXMethodDecl>(Best->Function);
12268 FoundDecl = Best->FoundDecl;
12269 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12270 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12271 return ExprError();
12272 // If FoundDecl is different from Method (such as if one is a template
12273 // and the other a specialization), make sure DiagnoseUseOfDecl is
12274 // called on both.
12275 // FIXME: This would be more comprehensively addressed by modifying
12276 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12277 // being used.
12278 if (Method != FoundDecl.getDecl() &&
12279 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12280 return ExprError();
12281 break;
12282
12283 case OR_No_Viable_Function:
12284 Diag(UnresExpr->getMemberLoc(),
12285 diag::err_ovl_no_viable_member_function_in_call)
12286 << DeclName << MemExprE->getSourceRange();
12287 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12288 // FIXME: Leaking incoming expressions!
12289 return ExprError();
12290
12291 case OR_Ambiguous:
12292 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12293 << DeclName << MemExprE->getSourceRange();
12294 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12295 // FIXME: Leaking incoming expressions!
12296 return ExprError();
12297
12298 case OR_Deleted:
12299 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12300 << Best->Function->isDeleted()
12301 << DeclName
12302 << getDeletedOrUnavailableSuffix(Best->Function)
12303 << MemExprE->getSourceRange();
12304 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12305 // FIXME: Leaking incoming expressions!
12306 return ExprError();
12307 }
12308
12309 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12310
12311 // If overload resolution picked a static member, build a
12312 // non-member call based on that function.
12313 if (Method->isStatic()) {
12314 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12315 RParenLoc);
12316 }
12317
12318 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12319 }
12320
12321 QualType ResultType = Method->getReturnType();
12322 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12323 ResultType = ResultType.getNonLValueExprType(Context);
12324
12325 assert(Method && "Member call to something that isn't a method?");
12326 CXXMemberCallExpr *TheCall =
12327 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12328 ResultType, VK, RParenLoc);
12329
12330 // (CUDA B.1): Check for invalid calls between targets.
12331 if (getLangOpts().CUDA) {
12332 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12333 if (CheckCUDATarget(Caller, Method)) {
12334 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12335 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12336 << IdentifyCUDATarget(Caller);
12337 return ExprError();
12338 }
12339 }
12340 }
12341
12342 // Check for a valid return type.
12343 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12344 TheCall, Method))
12345 return ExprError();
12346
12347 // Convert the object argument (for a non-static member function call).
12348 // We only need to do this if there was actually an overload; otherwise
12349 // it was done at lookup.
12350 if (!Method->isStatic()) {
12351 ExprResult ObjectArg =
12352 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12353 FoundDecl, Method);
12354 if (ObjectArg.isInvalid())
12355 return ExprError();
12356 MemExpr->setBase(ObjectArg.get());
12357 }
12358
12359 // Convert the rest of the arguments
12360 const FunctionProtoType *Proto =
12361 Method->getType()->getAs<FunctionProtoType>();
12362 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12363 RParenLoc))
12364 return ExprError();
12365
12366 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12367
12368 if (CheckFunctionCall(Method, TheCall, Proto))
12369 return ExprError();
12370
12371 // In the case the method to call was not selected by the overloading
12372 // resolution process, we still need to handle the enable_if attribute. Do
12373 // that here, so it will not hide previous -- and more relevant -- errors
12374 if (isa<MemberExpr>(NakedMemExpr)) {
12375 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12376 Diag(MemExprE->getLocStart(),
12377 diag::err_ovl_no_viable_member_function_in_call)
12378 << Method << Method->getSourceRange();
12379 Diag(Method->getLocation(),
12380 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12381 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12382 return ExprError();
12383 }
12384 }
12385
12386 if ((isa<CXXConstructorDecl>(CurContext) ||
12387 isa<CXXDestructorDecl>(CurContext)) &&
12388 TheCall->getMethodDecl()->isPure()) {
12389 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12390
12391 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12392 MemExpr->performsVirtualDispatch(getLangOpts())) {
12393 Diag(MemExpr->getLocStart(),
12394 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12395 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12396 << MD->getParent()->getDeclName();
12397
12398 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12399 if (getLangOpts().AppleKext)
12400 Diag(MemExpr->getLocStart(),
12401 diag::note_pure_qualified_call_kext)
12402 << MD->getParent()->getDeclName()
12403 << MD->getDeclName();
12404 }
12405 }
12406
12407 if (CXXDestructorDecl *DD =
12408 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12409 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12410 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12411 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12412 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12413 MemExpr->getMemberLoc());
12414 }
12415
12416 return MaybeBindToTemporary(TheCall);
12417 }
12418
12419 /// BuildCallToObjectOfClassType - Build a call to an object of class
12420 /// type (C++ [over.call.object]), which can end up invoking an
12421 /// overloaded function call operator (@c operator()) or performing a
12422 /// user-defined conversion on the object argument.
12423 ExprResult
BuildCallToObjectOfClassType(Scope * S,Expr * Obj,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc)12424 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12425 SourceLocation LParenLoc,
12426 MultiExprArg Args,
12427 SourceLocation RParenLoc) {
12428 if (checkPlaceholderForOverload(*this, Obj))
12429 return ExprError();
12430 ExprResult Object = Obj;
12431
12432 UnbridgedCastsSet UnbridgedCasts;
12433 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12434 return ExprError();
12435
12436 assert(Object.get()->getType()->isRecordType() &&
12437 "Requires object type argument");
12438 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12439
12440 // C++ [over.call.object]p1:
12441 // If the primary-expression E in the function call syntax
12442 // evaluates to a class object of type "cv T", then the set of
12443 // candidate functions includes at least the function call
12444 // operators of T. The function call operators of T are obtained by
12445 // ordinary lookup of the name operator() in the context of
12446 // (E).operator().
12447 OverloadCandidateSet CandidateSet(LParenLoc,
12448 OverloadCandidateSet::CSK_Operator);
12449 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12450
12451 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12452 diag::err_incomplete_object_call, Object.get()))
12453 return true;
12454
12455 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12456 LookupQualifiedName(R, Record->getDecl());
12457 R.suppressDiagnostics();
12458
12459 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12460 Oper != OperEnd; ++Oper) {
12461 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12462 Object.get()->Classify(Context),
12463 Args, CandidateSet,
12464 /*SuppressUserConversions=*/ false);
12465 }
12466
12467 // C++ [over.call.object]p2:
12468 // In addition, for each (non-explicit in C++0x) conversion function
12469 // declared in T of the form
12470 //
12471 // operator conversion-type-id () cv-qualifier;
12472 //
12473 // where cv-qualifier is the same cv-qualification as, or a
12474 // greater cv-qualification than, cv, and where conversion-type-id
12475 // denotes the type "pointer to function of (P1,...,Pn) returning
12476 // R", or the type "reference to pointer to function of
12477 // (P1,...,Pn) returning R", or the type "reference to function
12478 // of (P1,...,Pn) returning R", a surrogate call function [...]
12479 // is also considered as a candidate function. Similarly,
12480 // surrogate call functions are added to the set of candidate
12481 // functions for each conversion function declared in an
12482 // accessible base class provided the function is not hidden
12483 // within T by another intervening declaration.
12484 const auto &Conversions =
12485 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12486 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12487 NamedDecl *D = *I;
12488 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12489 if (isa<UsingShadowDecl>(D))
12490 D = cast<UsingShadowDecl>(D)->getTargetDecl();
12491
12492 // Skip over templated conversion functions; they aren't
12493 // surrogates.
12494 if (isa<FunctionTemplateDecl>(D))
12495 continue;
12496
12497 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12498 if (!Conv->isExplicit()) {
12499 // Strip the reference type (if any) and then the pointer type (if
12500 // any) to get down to what might be a function type.
12501 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12502 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12503 ConvType = ConvPtrType->getPointeeType();
12504
12505 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12506 {
12507 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12508 Object.get(), Args, CandidateSet);
12509 }
12510 }
12511 }
12512
12513 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12514
12515 // Perform overload resolution.
12516 OverloadCandidateSet::iterator Best;
12517 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12518 Best)) {
12519 case OR_Success:
12520 // Overload resolution succeeded; we'll build the appropriate call
12521 // below.
12522 break;
12523
12524 case OR_No_Viable_Function:
12525 if (CandidateSet.empty())
12526 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12527 << Object.get()->getType() << /*call*/ 1
12528 << Object.get()->getSourceRange();
12529 else
12530 Diag(Object.get()->getLocStart(),
12531 diag::err_ovl_no_viable_object_call)
12532 << Object.get()->getType() << Object.get()->getSourceRange();
12533 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12534 break;
12535
12536 case OR_Ambiguous:
12537 Diag(Object.get()->getLocStart(),
12538 diag::err_ovl_ambiguous_object_call)
12539 << Object.get()->getType() << Object.get()->getSourceRange();
12540 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12541 break;
12542
12543 case OR_Deleted:
12544 Diag(Object.get()->getLocStart(),
12545 diag::err_ovl_deleted_object_call)
12546 << Best->Function->isDeleted()
12547 << Object.get()->getType()
12548 << getDeletedOrUnavailableSuffix(Best->Function)
12549 << Object.get()->getSourceRange();
12550 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12551 break;
12552 }
12553
12554 if (Best == CandidateSet.end())
12555 return true;
12556
12557 UnbridgedCasts.restore();
12558
12559 if (Best->Function == nullptr) {
12560 // Since there is no function declaration, this is one of the
12561 // surrogate candidates. Dig out the conversion function.
12562 CXXConversionDecl *Conv
12563 = cast<CXXConversionDecl>(
12564 Best->Conversions[0].UserDefined.ConversionFunction);
12565
12566 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12567 Best->FoundDecl);
12568 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12569 return ExprError();
12570 assert(Conv == Best->FoundDecl.getDecl() &&
12571 "Found Decl & conversion-to-functionptr should be same, right?!");
12572 // We selected one of the surrogate functions that converts the
12573 // object parameter to a function pointer. Perform the conversion
12574 // on the object argument, then let ActOnCallExpr finish the job.
12575
12576 // Create an implicit member expr to refer to the conversion operator.
12577 // and then call it.
12578 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12579 Conv, HadMultipleCandidates);
12580 if (Call.isInvalid())
12581 return ExprError();
12582 // Record usage of conversion in an implicit cast.
12583 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12584 CK_UserDefinedConversion, Call.get(),
12585 nullptr, VK_RValue);
12586
12587 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12588 }
12589
12590 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12591
12592 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12593 // that calls this method, using Object for the implicit object
12594 // parameter and passing along the remaining arguments.
12595 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12596
12597 // An error diagnostic has already been printed when parsing the declaration.
12598 if (Method->isInvalidDecl())
12599 return ExprError();
12600
12601 const FunctionProtoType *Proto =
12602 Method->getType()->getAs<FunctionProtoType>();
12603
12604 unsigned NumParams = Proto->getNumParams();
12605
12606 DeclarationNameInfo OpLocInfo(
12607 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12608 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12609 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12610 HadMultipleCandidates,
12611 OpLocInfo.getLoc(),
12612 OpLocInfo.getInfo());
12613 if (NewFn.isInvalid())
12614 return true;
12615
12616 // Build the full argument list for the method call (the implicit object
12617 // parameter is placed at the beginning of the list).
12618 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12619 MethodArgs[0] = Object.get();
12620 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12621
12622 // Once we've built TheCall, all of the expressions are properly
12623 // owned.
12624 QualType ResultTy = Method->getReturnType();
12625 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12626 ResultTy = ResultTy.getNonLValueExprType(Context);
12627
12628 CXXOperatorCallExpr *TheCall = new (Context)
12629 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12630 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12631 ResultTy, VK, RParenLoc, false);
12632 MethodArgs.reset();
12633
12634 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12635 return true;
12636
12637 // We may have default arguments. If so, we need to allocate more
12638 // slots in the call for them.
12639 if (Args.size() < NumParams)
12640 TheCall->setNumArgs(Context, NumParams + 1);
12641
12642 bool IsError = false;
12643
12644 // Initialize the implicit object parameter.
12645 ExprResult ObjRes =
12646 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12647 Best->FoundDecl, Method);
12648 if (ObjRes.isInvalid())
12649 IsError = true;
12650 else
12651 Object = ObjRes;
12652 TheCall->setArg(0, Object.get());
12653
12654 // Check the argument types.
12655 for (unsigned i = 0; i != NumParams; i++) {
12656 Expr *Arg;
12657 if (i < Args.size()) {
12658 Arg = Args[i];
12659
12660 // Pass the argument.
12661
12662 ExprResult InputInit
12663 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12664 Context,
12665 Method->getParamDecl(i)),
12666 SourceLocation(), Arg);
12667
12668 IsError |= InputInit.isInvalid();
12669 Arg = InputInit.getAs<Expr>();
12670 } else {
12671 ExprResult DefArg
12672 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12673 if (DefArg.isInvalid()) {
12674 IsError = true;
12675 break;
12676 }
12677
12678 Arg = DefArg.getAs<Expr>();
12679 }
12680
12681 TheCall->setArg(i + 1, Arg);
12682 }
12683
12684 // If this is a variadic call, handle args passed through "...".
12685 if (Proto->isVariadic()) {
12686 // Promote the arguments (C99 6.5.2.2p7).
12687 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12688 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12689 nullptr);
12690 IsError |= Arg.isInvalid();
12691 TheCall->setArg(i + 1, Arg.get());
12692 }
12693 }
12694
12695 if (IsError) return true;
12696
12697 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12698
12699 if (CheckFunctionCall(Method, TheCall, Proto))
12700 return true;
12701
12702 return MaybeBindToTemporary(TheCall);
12703 }
12704
12705 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12706 /// (if one exists), where @c Base is an expression of class type and
12707 /// @c Member is the name of the member we're trying to find.
12708 ExprResult
BuildOverloadedArrowExpr(Scope * S,Expr * Base,SourceLocation OpLoc,bool * NoArrowOperatorFound)12709 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12710 bool *NoArrowOperatorFound) {
12711 assert(Base->getType()->isRecordType() &&
12712 "left-hand side must have class type");
12713
12714 if (checkPlaceholderForOverload(*this, Base))
12715 return ExprError();
12716
12717 SourceLocation Loc = Base->getExprLoc();
12718
12719 // C++ [over.ref]p1:
12720 //
12721 // [...] An expression x->m is interpreted as (x.operator->())->m
12722 // for a class object x of type T if T::operator->() exists and if
12723 // the operator is selected as the best match function by the
12724 // overload resolution mechanism (13.3).
12725 DeclarationName OpName =
12726 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12727 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12728 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12729
12730 if (RequireCompleteType(Loc, Base->getType(),
12731 diag::err_typecheck_incomplete_tag, Base))
12732 return ExprError();
12733
12734 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12735 LookupQualifiedName(R, BaseRecord->getDecl());
12736 R.suppressDiagnostics();
12737
12738 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12739 Oper != OperEnd; ++Oper) {
12740 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12741 None, CandidateSet, /*SuppressUserConversions=*/false);
12742 }
12743
12744 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12745
12746 // Perform overload resolution.
12747 OverloadCandidateSet::iterator Best;
12748 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12749 case OR_Success:
12750 // Overload resolution succeeded; we'll build the call below.
12751 break;
12752
12753 case OR_No_Viable_Function:
12754 if (CandidateSet.empty()) {
12755 QualType BaseType = Base->getType();
12756 if (NoArrowOperatorFound) {
12757 // Report this specific error to the caller instead of emitting a
12758 // diagnostic, as requested.
12759 *NoArrowOperatorFound = true;
12760 return ExprError();
12761 }
12762 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12763 << BaseType << Base->getSourceRange();
12764 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12765 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12766 << FixItHint::CreateReplacement(OpLoc, ".");
12767 }
12768 } else
12769 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12770 << "operator->" << Base->getSourceRange();
12771 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12772 return ExprError();
12773
12774 case OR_Ambiguous:
12775 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12776 << "->" << Base->getType() << Base->getSourceRange();
12777 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12778 return ExprError();
12779
12780 case OR_Deleted:
12781 Diag(OpLoc, diag::err_ovl_deleted_oper)
12782 << Best->Function->isDeleted()
12783 << "->"
12784 << getDeletedOrUnavailableSuffix(Best->Function)
12785 << Base->getSourceRange();
12786 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12787 return ExprError();
12788 }
12789
12790 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12791
12792 // Convert the object parameter.
12793 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12794 ExprResult BaseResult =
12795 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12796 Best->FoundDecl, Method);
12797 if (BaseResult.isInvalid())
12798 return ExprError();
12799 Base = BaseResult.get();
12800
12801 // Build the operator call.
12802 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12803 HadMultipleCandidates, OpLoc);
12804 if (FnExpr.isInvalid())
12805 return ExprError();
12806
12807 QualType ResultTy = Method->getReturnType();
12808 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12809 ResultTy = ResultTy.getNonLValueExprType(Context);
12810 CXXOperatorCallExpr *TheCall =
12811 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12812 Base, ResultTy, VK, OpLoc, false);
12813
12814 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12815 return ExprError();
12816
12817 return MaybeBindToTemporary(TheCall);
12818 }
12819
12820 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12821 /// a literal operator described by the provided lookup results.
BuildLiteralOperatorCall(LookupResult & R,DeclarationNameInfo & SuffixInfo,ArrayRef<Expr * > Args,SourceLocation LitEndLoc,TemplateArgumentListInfo * TemplateArgs)12822 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12823 DeclarationNameInfo &SuffixInfo,
12824 ArrayRef<Expr*> Args,
12825 SourceLocation LitEndLoc,
12826 TemplateArgumentListInfo *TemplateArgs) {
12827 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12828
12829 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12830 OverloadCandidateSet::CSK_Normal);
12831 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12832 /*SuppressUserConversions=*/true);
12833
12834 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12835
12836 // Perform overload resolution. This will usually be trivial, but might need
12837 // to perform substitutions for a literal operator template.
12838 OverloadCandidateSet::iterator Best;
12839 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12840 case OR_Success:
12841 case OR_Deleted:
12842 break;
12843
12844 case OR_No_Viable_Function:
12845 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12846 << R.getLookupName();
12847 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12848 return ExprError();
12849
12850 case OR_Ambiguous:
12851 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12852 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12853 return ExprError();
12854 }
12855
12856 FunctionDecl *FD = Best->Function;
12857 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12858 HadMultipleCandidates,
12859 SuffixInfo.getLoc(),
12860 SuffixInfo.getInfo());
12861 if (Fn.isInvalid())
12862 return true;
12863
12864 // Check the argument types. This should almost always be a no-op, except
12865 // that array-to-pointer decay is applied to string literals.
12866 Expr *ConvArgs[2];
12867 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12868 ExprResult InputInit = PerformCopyInitialization(
12869 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12870 SourceLocation(), Args[ArgIdx]);
12871 if (InputInit.isInvalid())
12872 return true;
12873 ConvArgs[ArgIdx] = InputInit.get();
12874 }
12875
12876 QualType ResultTy = FD->getReturnType();
12877 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12878 ResultTy = ResultTy.getNonLValueExprType(Context);
12879
12880 UserDefinedLiteral *UDL =
12881 new (Context) UserDefinedLiteral(Context, Fn.get(),
12882 llvm::makeArrayRef(ConvArgs, Args.size()),
12883 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12884
12885 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12886 return ExprError();
12887
12888 if (CheckFunctionCall(FD, UDL, nullptr))
12889 return ExprError();
12890
12891 return MaybeBindToTemporary(UDL);
12892 }
12893
12894 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12895 /// given LookupResult is non-empty, it is assumed to describe a member which
12896 /// will be invoked. Otherwise, the function will be found via argument
12897 /// dependent lookup.
12898 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12899 /// otherwise CallExpr is set to ExprError() and some non-success value
12900 /// is returned.
12901 Sema::ForRangeStatus
BuildForRangeBeginEndCall(SourceLocation Loc,SourceLocation RangeLoc,const DeclarationNameInfo & NameInfo,LookupResult & MemberLookup,OverloadCandidateSet * CandidateSet,Expr * Range,ExprResult * CallExpr)12902 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12903 SourceLocation RangeLoc,
12904 const DeclarationNameInfo &NameInfo,
12905 LookupResult &MemberLookup,
12906 OverloadCandidateSet *CandidateSet,
12907 Expr *Range, ExprResult *CallExpr) {
12908 Scope *S = nullptr;
12909
12910 CandidateSet->clear();
12911 if (!MemberLookup.empty()) {
12912 ExprResult MemberRef =
12913 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12914 /*IsPtr=*/false, CXXScopeSpec(),
12915 /*TemplateKWLoc=*/SourceLocation(),
12916 /*FirstQualifierInScope=*/nullptr,
12917 MemberLookup,
12918 /*TemplateArgs=*/nullptr, S);
12919 if (MemberRef.isInvalid()) {
12920 *CallExpr = ExprError();
12921 return FRS_DiagnosticIssued;
12922 }
12923 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12924 if (CallExpr->isInvalid()) {
12925 *CallExpr = ExprError();
12926 return FRS_DiagnosticIssued;
12927 }
12928 } else {
12929 UnresolvedSet<0> FoundNames;
12930 UnresolvedLookupExpr *Fn =
12931 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12932 NestedNameSpecifierLoc(), NameInfo,
12933 /*NeedsADL=*/true, /*Overloaded=*/false,
12934 FoundNames.begin(), FoundNames.end());
12935
12936 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12937 CandidateSet, CallExpr);
12938 if (CandidateSet->empty() || CandidateSetError) {
12939 *CallExpr = ExprError();
12940 return FRS_NoViableFunction;
12941 }
12942 OverloadCandidateSet::iterator Best;
12943 OverloadingResult OverloadResult =
12944 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12945
12946 if (OverloadResult == OR_No_Viable_Function) {
12947 *CallExpr = ExprError();
12948 return FRS_NoViableFunction;
12949 }
12950 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12951 Loc, nullptr, CandidateSet, &Best,
12952 OverloadResult,
12953 /*AllowTypoCorrection=*/false);
12954 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12955 *CallExpr = ExprError();
12956 return FRS_DiagnosticIssued;
12957 }
12958 }
12959 return FRS_Success;
12960 }
12961
12962
12963 /// FixOverloadedFunctionReference - E is an expression that refers to
12964 /// a C++ overloaded function (possibly with some parentheses and
12965 /// perhaps a '&' around it). We have resolved the overloaded function
12966 /// to the function declaration Fn, so patch up the expression E to
12967 /// refer (possibly indirectly) to Fn. Returns the new expr.
FixOverloadedFunctionReference(Expr * E,DeclAccessPair Found,FunctionDecl * Fn)12968 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12969 FunctionDecl *Fn) {
12970 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12971 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12972 Found, Fn);
12973 if (SubExpr == PE->getSubExpr())
12974 return PE;
12975
12976 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12977 }
12978
12979 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12980 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12981 Found, Fn);
12982 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12983 SubExpr->getType()) &&
12984 "Implicit cast type cannot be determined from overload");
12985 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12986 if (SubExpr == ICE->getSubExpr())
12987 return ICE;
12988
12989 return ImplicitCastExpr::Create(Context, ICE->getType(),
12990 ICE->getCastKind(),
12991 SubExpr, nullptr,
12992 ICE->getValueKind());
12993 }
12994
12995 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12996 assert(UnOp->getOpcode() == UO_AddrOf &&
12997 "Can only take the address of an overloaded function");
12998 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12999 if (Method->isStatic()) {
13000 // Do nothing: static member functions aren't any different
13001 // from non-member functions.
13002 } else {
13003 // Fix the subexpression, which really has to be an
13004 // UnresolvedLookupExpr holding an overloaded member function
13005 // or template.
13006 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13007 Found, Fn);
13008 if (SubExpr == UnOp->getSubExpr())
13009 return UnOp;
13010
13011 assert(isa<DeclRefExpr>(SubExpr)
13012 && "fixed to something other than a decl ref");
13013 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13014 && "fixed to a member ref with no nested name qualifier");
13015
13016 // We have taken the address of a pointer to member
13017 // function. Perform the computation here so that we get the
13018 // appropriate pointer to member type.
13019 QualType ClassType
13020 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13021 QualType MemPtrType
13022 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13023 // Under the MS ABI, lock down the inheritance model now.
13024 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13025 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13026
13027 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13028 VK_RValue, OK_Ordinary,
13029 UnOp->getOperatorLoc());
13030 }
13031 }
13032 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13033 Found, Fn);
13034 if (SubExpr == UnOp->getSubExpr())
13035 return UnOp;
13036
13037 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13038 Context.getPointerType(SubExpr->getType()),
13039 VK_RValue, OK_Ordinary,
13040 UnOp->getOperatorLoc());
13041 }
13042
13043 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13044 // FIXME: avoid copy.
13045 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13046 if (ULE->hasExplicitTemplateArgs()) {
13047 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13048 TemplateArgs = &TemplateArgsBuffer;
13049 }
13050
13051 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13052 ULE->getQualifierLoc(),
13053 ULE->getTemplateKeywordLoc(),
13054 Fn,
13055 /*enclosing*/ false, // FIXME?
13056 ULE->getNameLoc(),
13057 Fn->getType(),
13058 VK_LValue,
13059 Found.getDecl(),
13060 TemplateArgs);
13061 MarkDeclRefReferenced(DRE);
13062 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13063 return DRE;
13064 }
13065
13066 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13067 // FIXME: avoid copy.
13068 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13069 if (MemExpr->hasExplicitTemplateArgs()) {
13070 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13071 TemplateArgs = &TemplateArgsBuffer;
13072 }
13073
13074 Expr *Base;
13075
13076 // If we're filling in a static method where we used to have an
13077 // implicit member access, rewrite to a simple decl ref.
13078 if (MemExpr->isImplicitAccess()) {
13079 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13080 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13081 MemExpr->getQualifierLoc(),
13082 MemExpr->getTemplateKeywordLoc(),
13083 Fn,
13084 /*enclosing*/ false,
13085 MemExpr->getMemberLoc(),
13086 Fn->getType(),
13087 VK_LValue,
13088 Found.getDecl(),
13089 TemplateArgs);
13090 MarkDeclRefReferenced(DRE);
13091 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13092 return DRE;
13093 } else {
13094 SourceLocation Loc = MemExpr->getMemberLoc();
13095 if (MemExpr->getQualifier())
13096 Loc = MemExpr->getQualifierLoc().getBeginLoc();
13097 CheckCXXThisCapture(Loc);
13098 Base = new (Context) CXXThisExpr(Loc,
13099 MemExpr->getBaseType(),
13100 /*isImplicit=*/true);
13101 }
13102 } else
13103 Base = MemExpr->getBase();
13104
13105 ExprValueKind valueKind;
13106 QualType type;
13107 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13108 valueKind = VK_LValue;
13109 type = Fn->getType();
13110 } else {
13111 valueKind = VK_RValue;
13112 type = Context.BoundMemberTy;
13113 }
13114
13115 MemberExpr *ME = MemberExpr::Create(
13116 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13117 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13118 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13119 OK_Ordinary);
13120 ME->setHadMultipleCandidates(true);
13121 MarkMemberReferenced(ME);
13122 return ME;
13123 }
13124
13125 llvm_unreachable("Invalid reference to overloaded function");
13126 }
13127
FixOverloadedFunctionReference(ExprResult E,DeclAccessPair Found,FunctionDecl * Fn)13128 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13129 DeclAccessPair Found,
13130 FunctionDecl *Fn) {
13131 return FixOverloadedFunctionReference(E.get(), Found, Fn);
13132 }
13133