Bug Summary

File:tools/clang/lib/Sema/SemaOverload.cpp
Location:line 9135, column 50
Description:Called C++ object pointer is null

Annotated Source Code

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
38using namespace clang;
39using namespace sema;
40
41static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42 return std::any_of(FD->param_begin(), FD->param_end(),
43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
44}
45
46/// A convenience routine for creating a decayed reference to a function.
47static ExprResult
48CreateFunctionRefExpr(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
72static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
73 bool InOverloadResolution,
74 StandardConversionSequence &SCS,
75 bool CStyle,
76 bool AllowObjCWritebackConversion);
77
78static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79 QualType &ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
82 bool CStyle);
83static OverloadingResult
84IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
85 UserDefinedConversionSequence& User,
86 OverloadCandidateSet& Conversions,
87 bool AllowExplicit,
88 bool AllowObjCConversionOnExplicit);
89
90
91static ImplicitConversionSequence::CompareKind
92CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
93 const StandardConversionSequence& SCS1,
94 const StandardConversionSequence& SCS2);
95
96static ImplicitConversionSequence::CompareKind
97CompareQualificationConversions(Sema &S,
98 const StandardConversionSequence& SCS1,
99 const StandardConversionSequence& SCS2);
100
101static ImplicitConversionSequence::CompareKind
102CompareDerivedToBaseConversions(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.
108ImplicitConversionRank 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.
145static 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.
179void 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.
198ImplicitConversionRank 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).
213bool 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).
233bool
234StandardConversionSequence::
235isPointerConversionToVoidPointer(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.
254static 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_FloatingToIntegral:
262 case CK_FloatingToBoolean:
263 case CK_FloatingCast:
264 Converted = ICE->getSubExpr();
265 continue;
266
267 default:
268 return Converted;
269 }
270 }
271
272 return Converted;
273}
274
275/// Check if this standard conversion sequence represents a narrowing
276/// conversion, according to C++11 [dcl.init.list]p7.
277///
278/// \param Ctx The AST context.
279/// \param Converted The result of applying this standard conversion sequence.
280/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
281/// value of the expression prior to the narrowing conversion.
282/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
283/// type of the expression prior to the narrowing conversion.
284NarrowingKind
285StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
286 const Expr *Converted,
287 APValue &ConstantValue,
288 QualType &ConstantType) const {
289 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++")((Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"
) ? static_cast<void> (0) : __assert_fail ("Ctx.getLangOpts().CPlusPlus && \"narrowing check outside C++\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 289, __PRETTY_FUNCTION__))
;
290
291 // C++11 [dcl.init.list]p7:
292 // A narrowing conversion is an implicit conversion ...
293 QualType FromType = getToType(0);
294 QualType ToType = getToType(1);
295 switch (Second) {
296 // 'bool' is an integral type; dispatch to the right place to handle it.
297 case ICK_Boolean_Conversion:
298 if (FromType->isRealFloatingType())
299 goto FloatingIntegralConversion;
300 if (FromType->isIntegralOrUnscopedEnumerationType())
301 goto IntegralConversion;
302 // Boolean conversions can be from pointers and pointers to members
303 // [conv.bool], and those aren't considered narrowing conversions.
304 return NK_Not_Narrowing;
305
306 // -- from a floating-point type to an integer type, or
307 //
308 // -- from an integer type or unscoped enumeration type to a floating-point
309 // type, except where the source is a constant expression and the actual
310 // value after conversion will fit into the target type and will produce
311 // the original value when converted back to the original type, or
312 case ICK_Floating_Integral:
313 FloatingIntegralConversion:
314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315 return NK_Type_Narrowing;
316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317 llvm::APSInt IntConstantValue;
318 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319 if (Initializer &&
320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321 // Convert the integer to the floating type.
322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324 llvm::APFloat::rmNearestTiesToEven);
325 // And back.
326 llvm::APSInt ConvertedValue = IntConstantValue;
327 bool ignored;
328 Result.convertToInteger(ConvertedValue,
329 llvm::APFloat::rmTowardZero, &ignored);
330 // If the resulting value is different, this was a narrowing conversion.
331 if (IntConstantValue != ConvertedValue) {
332 ConstantValue = APValue(IntConstantValue);
333 ConstantType = Initializer->getType();
334 return NK_Constant_Narrowing;
335 }
336 } else {
337 // Variables are always narrowings.
338 return NK_Variable_Narrowing;
339 }
340 }
341 return NK_Not_Narrowing;
342
343 // -- from long double to double or float, or from double to float, except
344 // where the source is a constant expression and the actual value after
345 // conversion is within the range of values that can be represented (even
346 // if it cannot be represented exactly), or
347 case ICK_Floating_Conversion:
348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350 // FromType is larger than ToType.
351 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353 // Constant!
354 assert(ConstantValue.isFloat())((ConstantValue.isFloat()) ? static_cast<void> (0) : __assert_fail
("ConstantValue.isFloat()", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 354, __PRETTY_FUNCTION__))
;
355 llvm::APFloat FloatVal = ConstantValue.getFloat();
356 // Convert the source value into the target type.
357 bool ignored;
358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359 Ctx.getFloatTypeSemantics(ToType),
360 llvm::APFloat::rmNearestTiesToEven, &ignored);
361 // If there was no overflow, the source value is within the range of
362 // values that can be represented.
363 if (ConvertStatus & llvm::APFloat::opOverflow) {
364 ConstantType = Initializer->getType();
365 return NK_Constant_Narrowing;
366 }
367 } else {
368 return NK_Variable_Narrowing;
369 }
370 }
371 return NK_Not_Narrowing;
372
373 // -- from an integer type or unscoped enumeration type to an integer type
374 // that cannot represent all the values of the original type, except where
375 // the source is a constant expression and the actual value after
376 // conversion will fit into the target type and will produce the original
377 // value when converted back to the original type.
378 case ICK_Integral_Conversion:
379 IntegralConversion: {
380 assert(FromType->isIntegralOrUnscopedEnumerationType())((FromType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("FromType->isIntegralOrUnscopedEnumerationType()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 380, __PRETTY_FUNCTION__))
;
381 assert(ToType->isIntegralOrUnscopedEnumerationType())((ToType->isIntegralOrUnscopedEnumerationType()) ? static_cast
<void> (0) : __assert_fail ("ToType->isIntegralOrUnscopedEnumerationType()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 381, __PRETTY_FUNCTION__))
;
382 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
383 const unsigned FromWidth = Ctx.getIntWidth(FromType);
384 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
385 const unsigned ToWidth = Ctx.getIntWidth(ToType);
386
387 if (FromWidth > ToWidth ||
388 (FromWidth == ToWidth && FromSigned != ToSigned) ||
389 (FromSigned && !ToSigned)) {
390 // Not all values of FromType can be represented in ToType.
391 llvm::APSInt InitializerValue;
392 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
393 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
394 // Such conversions on variables are always narrowing.
395 return NK_Variable_Narrowing;
396 }
397 bool Narrowing = false;
398 if (FromWidth < ToWidth) {
399 // Negative -> unsigned is narrowing. Otherwise, more bits is never
400 // narrowing.
401 if (InitializerValue.isSigned() && InitializerValue.isNegative())
402 Narrowing = true;
403 } else {
404 // Add a bit to the InitializerValue so we don't have to worry about
405 // signed vs. unsigned comparisons.
406 InitializerValue = InitializerValue.extend(
407 InitializerValue.getBitWidth() + 1);
408 // Convert the initializer to and from the target width and signed-ness.
409 llvm::APSInt ConvertedValue = InitializerValue;
410 ConvertedValue = ConvertedValue.trunc(ToWidth);
411 ConvertedValue.setIsSigned(ToSigned);
412 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
413 ConvertedValue.setIsSigned(InitializerValue.isSigned());
414 // If the result is different, this was a narrowing conversion.
415 if (ConvertedValue != InitializerValue)
416 Narrowing = true;
417 }
418 if (Narrowing) {
419 ConstantType = Initializer->getType();
420 ConstantValue = APValue(InitializerValue);
421 return NK_Constant_Narrowing;
422 }
423 }
424 return NK_Not_Narrowing;
425 }
426
427 default:
428 // Other kinds of conversions are not narrowings.
429 return NK_Not_Narrowing;
430 }
431}
432
433/// dump - Print this standard conversion sequence to standard
434/// error. Useful for debugging overloading issues.
435void StandardConversionSequence::dump() const {
436 raw_ostream &OS = llvm::errs();
437 bool PrintedSomething = false;
438 if (First != ICK_Identity) {
439 OS << GetImplicitConversionName(First);
440 PrintedSomething = true;
441 }
442
443 if (Second != ICK_Identity) {
444 if (PrintedSomething) {
445 OS << " -> ";
446 }
447 OS << GetImplicitConversionName(Second);
448
449 if (CopyConstructor) {
450 OS << " (by copy constructor)";
451 } else if (DirectBinding) {
452 OS << " (direct reference binding)";
453 } else if (ReferenceBinding) {
454 OS << " (reference binding)";
455 }
456 PrintedSomething = true;
457 }
458
459 if (Third != ICK_Identity) {
460 if (PrintedSomething) {
461 OS << " -> ";
462 }
463 OS << GetImplicitConversionName(Third);
464 PrintedSomething = true;
465 }
466
467 if (!PrintedSomething) {
468 OS << "No conversions required";
469 }
470}
471
472/// dump - Print this user-defined conversion sequence to standard
473/// error. Useful for debugging overloading issues.
474void UserDefinedConversionSequence::dump() const {
475 raw_ostream &OS = llvm::errs();
476 if (Before.First || Before.Second || Before.Third) {
477 Before.dump();
478 OS << " -> ";
479 }
480 if (ConversionFunction)
481 OS << '\'' << *ConversionFunction << '\'';
482 else
483 OS << "aggregate initialization";
484 if (After.First || After.Second || After.Third) {
485 OS << " -> ";
486 After.dump();
487 }
488}
489
490/// dump - Print this implicit conversion sequence to standard
491/// error. Useful for debugging overloading issues.
492void ImplicitConversionSequence::dump() const {
493 raw_ostream &OS = llvm::errs();
494 if (isStdInitializerListElement())
495 OS << "Worst std::initializer_list element conversion: ";
496 switch (ConversionKind) {
497 case StandardConversion:
498 OS << "Standard conversion: ";
499 Standard.dump();
500 break;
501 case UserDefinedConversion:
502 OS << "User-defined conversion: ";
503 UserDefined.dump();
504 break;
505 case EllipsisConversion:
506 OS << "Ellipsis conversion";
507 break;
508 case AmbiguousConversion:
509 OS << "Ambiguous conversion";
510 break;
511 case BadConversion:
512 OS << "Bad conversion";
513 break;
514 }
515
516 OS << "\n";
517}
518
519void AmbiguousConversionSequence::construct() {
520 new (&conversions()) ConversionSet();
521}
522
523void AmbiguousConversionSequence::destruct() {
524 conversions().~ConversionSet();
525}
526
527void
528AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
529 FromTypePtr = O.FromTypePtr;
530 ToTypePtr = O.ToTypePtr;
531 new (&conversions()) ConversionSet(O.conversions());
532}
533
534namespace {
535 // Structure used by DeductionFailureInfo to store
536 // template argument information.
537 struct DFIArguments {
538 TemplateArgument FirstArg;
539 TemplateArgument SecondArg;
540 };
541 // Structure used by DeductionFailureInfo to store
542 // template parameter and template argument information.
543 struct DFIParamWithArguments : DFIArguments {
544 TemplateParameter Param;
545 };
546 // Structure used by DeductionFailureInfo to store template argument
547 // information and the index of the problematic call argument.
548 struct DFIDeducedMismatchArgs : DFIArguments {
549 TemplateArgumentList *TemplateArgs;
550 unsigned CallArgIndex;
551 };
552}
553
554/// \brief Convert from Sema's representation of template deduction information
555/// to the form used in overload-candidate information.
556DeductionFailureInfo
557clang::MakeDeductionFailureInfo(ASTContext &Context,
558 Sema::TemplateDeductionResult TDK,
559 TemplateDeductionInfo &Info) {
560 DeductionFailureInfo Result;
561 Result.Result = static_cast<unsigned>(TDK);
562 Result.HasDiagnostic = false;
563 switch (TDK) {
564 case Sema::TDK_Success:
565 case Sema::TDK_Invalid:
566 case Sema::TDK_InstantiationDepth:
567 case Sema::TDK_TooManyArguments:
568 case Sema::TDK_TooFewArguments:
569 case Sema::TDK_MiscellaneousDeductionFailure:
570 Result.Data = nullptr;
571 break;
572
573 case Sema::TDK_Incomplete:
574 case Sema::TDK_InvalidExplicitArguments:
575 Result.Data = Info.Param.getOpaqueValue();
576 break;
577
578 case Sema::TDK_DeducedMismatch: {
579 // FIXME: Should allocate from normal heap so that we can free this later.
580 auto *Saved = new (Context) DFIDeducedMismatchArgs;
581 Saved->FirstArg = Info.FirstArg;
582 Saved->SecondArg = Info.SecondArg;
583 Saved->TemplateArgs = Info.take();
584 Saved->CallArgIndex = Info.CallArgIndex;
585 Result.Data = Saved;
586 break;
587 }
588
589 case Sema::TDK_NonDeducedMismatch: {
590 // FIXME: Should allocate from normal heap so that we can free this later.
591 DFIArguments *Saved = new (Context) DFIArguments;
592 Saved->FirstArg = Info.FirstArg;
593 Saved->SecondArg = Info.SecondArg;
594 Result.Data = Saved;
595 break;
596 }
597
598 case Sema::TDK_Inconsistent:
599 case Sema::TDK_Underqualified: {
600 // FIXME: Should allocate from normal heap so that we can free this later.
601 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
602 Saved->Param = Info.Param;
603 Saved->FirstArg = Info.FirstArg;
604 Saved->SecondArg = Info.SecondArg;
605 Result.Data = Saved;
606 break;
607 }
608
609 case Sema::TDK_SubstitutionFailure:
610 Result.Data = Info.take();
611 if (Info.hasSFINAEDiagnostic()) {
612 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
613 SourceLocation(), PartialDiagnostic::NullDiagnostic());
614 Info.takeSFINAEDiagnostic(*Diag);
615 Result.HasDiagnostic = true;
616 }
617 break;
618
619 case Sema::TDK_FailedOverloadResolution:
620 Result.Data = Info.Expression;
621 break;
622 }
623
624 return Result;
625}
626
627void DeductionFailureInfo::Destroy() {
628 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
629 case Sema::TDK_Success:
630 case Sema::TDK_Invalid:
631 case Sema::TDK_InstantiationDepth:
632 case Sema::TDK_Incomplete:
633 case Sema::TDK_TooManyArguments:
634 case Sema::TDK_TooFewArguments:
635 case Sema::TDK_InvalidExplicitArguments:
636 case Sema::TDK_FailedOverloadResolution:
637 break;
638
639 case Sema::TDK_Inconsistent:
640 case Sema::TDK_Underqualified:
641 case Sema::TDK_DeducedMismatch:
642 case Sema::TDK_NonDeducedMismatch:
643 // FIXME: Destroy the data?
644 Data = nullptr;
645 break;
646
647 case Sema::TDK_SubstitutionFailure:
648 // FIXME: Destroy the template argument list?
649 Data = nullptr;
650 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
651 Diag->~PartialDiagnosticAt();
652 HasDiagnostic = false;
653 }
654 break;
655
656 // Unhandled
657 case Sema::TDK_MiscellaneousDeductionFailure:
658 break;
659 }
660}
661
662PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
663 if (HasDiagnostic)
664 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
665 return nullptr;
666}
667
668TemplateParameter DeductionFailureInfo::getTemplateParameter() {
669 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
670 case Sema::TDK_Success:
671 case Sema::TDK_Invalid:
672 case Sema::TDK_InstantiationDepth:
673 case Sema::TDK_TooManyArguments:
674 case Sema::TDK_TooFewArguments:
675 case Sema::TDK_SubstitutionFailure:
676 case Sema::TDK_DeducedMismatch:
677 case Sema::TDK_NonDeducedMismatch:
678 case Sema::TDK_FailedOverloadResolution:
679 return TemplateParameter();
680
681 case Sema::TDK_Incomplete:
682 case Sema::TDK_InvalidExplicitArguments:
683 return TemplateParameter::getFromOpaqueValue(Data);
684
685 case Sema::TDK_Inconsistent:
686 case Sema::TDK_Underqualified:
687 return static_cast<DFIParamWithArguments*>(Data)->Param;
688
689 // Unhandled
690 case Sema::TDK_MiscellaneousDeductionFailure:
691 break;
692 }
693
694 return TemplateParameter();
695}
696
697TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
698 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
699 case Sema::TDK_Success:
700 case Sema::TDK_Invalid:
701 case Sema::TDK_InstantiationDepth:
702 case Sema::TDK_TooManyArguments:
703 case Sema::TDK_TooFewArguments:
704 case Sema::TDK_Incomplete:
705 case Sema::TDK_InvalidExplicitArguments:
706 case Sema::TDK_Inconsistent:
707 case Sema::TDK_Underqualified:
708 case Sema::TDK_NonDeducedMismatch:
709 case Sema::TDK_FailedOverloadResolution:
710 return nullptr;
711
712 case Sema::TDK_DeducedMismatch:
713 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
714
715 case Sema::TDK_SubstitutionFailure:
716 return static_cast<TemplateArgumentList*>(Data);
717
718 // Unhandled
719 case Sema::TDK_MiscellaneousDeductionFailure:
720 break;
721 }
722
723 return nullptr;
724}
725
726const TemplateArgument *DeductionFailureInfo::getFirstArg() {
727 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
728 case Sema::TDK_Success:
729 case Sema::TDK_Invalid:
730 case Sema::TDK_InstantiationDepth:
731 case Sema::TDK_Incomplete:
732 case Sema::TDK_TooManyArguments:
733 case Sema::TDK_TooFewArguments:
734 case Sema::TDK_InvalidExplicitArguments:
735 case Sema::TDK_SubstitutionFailure:
736 case Sema::TDK_FailedOverloadResolution:
737 return nullptr;
738
739 case Sema::TDK_Inconsistent:
740 case Sema::TDK_Underqualified:
741 case Sema::TDK_DeducedMismatch:
742 case Sema::TDK_NonDeducedMismatch:
743 return &static_cast<DFIArguments*>(Data)->FirstArg;
744
745 // Unhandled
746 case Sema::TDK_MiscellaneousDeductionFailure:
747 break;
748 }
749
750 return nullptr;
751}
752
753const TemplateArgument *DeductionFailureInfo::getSecondArg() {
754 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
755 case Sema::TDK_Success:
756 case Sema::TDK_Invalid:
757 case Sema::TDK_InstantiationDepth:
758 case Sema::TDK_Incomplete:
759 case Sema::TDK_TooManyArguments:
760 case Sema::TDK_TooFewArguments:
761 case Sema::TDK_InvalidExplicitArguments:
762 case Sema::TDK_SubstitutionFailure:
763 case Sema::TDK_FailedOverloadResolution:
764 return nullptr;
765
766 case Sema::TDK_Inconsistent:
767 case Sema::TDK_Underqualified:
768 case Sema::TDK_DeducedMismatch:
769 case Sema::TDK_NonDeducedMismatch:
770 return &static_cast<DFIArguments*>(Data)->SecondArg;
771
772 // Unhandled
773 case Sema::TDK_MiscellaneousDeductionFailure:
774 break;
775 }
776
777 return nullptr;
778}
779
780Expr *DeductionFailureInfo::getExpr() {
781 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
782 Sema::TDK_FailedOverloadResolution)
783 return static_cast<Expr*>(Data);
784
785 return nullptr;
786}
787
788llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
789 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
790 Sema::TDK_DeducedMismatch)
791 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
792
793 return llvm::None;
794}
795
796void OverloadCandidateSet::destroyCandidates() {
797 for (iterator i = begin(), e = end(); i != e; ++i) {
798 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
799 i->Conversions[ii].~ImplicitConversionSequence();
800 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
801 i->DeductionFailure.Destroy();
802 }
803}
804
805void OverloadCandidateSet::clear() {
806 destroyCandidates();
807 NumInlineSequences = 0;
808 Candidates.clear();
809 Functions.clear();
810}
811
812namespace {
813 class UnbridgedCastsSet {
814 struct Entry {
815 Expr **Addr;
816 Expr *Saved;
817 };
818 SmallVector<Entry, 2> Entries;
819
820 public:
821 void save(Sema &S, Expr *&E) {
822 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 822, __PRETTY_FUNCTION__))
;
823 Entry entry = { &E, E };
824 Entries.push_back(entry);
825 E = S.stripARCUnbridgedCast(E);
826 }
827
828 void restore() {
829 for (SmallVectorImpl<Entry>::iterator
830 i = Entries.begin(), e = Entries.end(); i != e; ++i)
831 *i->Addr = i->Saved;
832 }
833 };
834}
835
836/// checkPlaceholderForOverload - Do any interesting placeholder-like
837/// preprocessing on the given expression.
838///
839/// \param unbridgedCasts a collection to which to add unbridged casts;
840/// without this, they will be immediately diagnosed as errors
841///
842/// Return true on unrecoverable error.
843static bool
844checkPlaceholderForOverload(Sema &S, Expr *&E,
845 UnbridgedCastsSet *unbridgedCasts = nullptr) {
846 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
847 // We can't handle overloaded expressions here because overload
848 // resolution might reasonably tweak them.
849 if (placeholder->getKind() == BuiltinType::Overload) return false;
850
851 // If the context potentially accepts unbridged ARC casts, strip
852 // the unbridged cast and add it to the collection for later restoration.
853 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
854 unbridgedCasts) {
855 unbridgedCasts->save(S, E);
856 return false;
857 }
858
859 // Go ahead and check everything else.
860 ExprResult result = S.CheckPlaceholderExpr(E);
861 if (result.isInvalid())
862 return true;
863
864 E = result.get();
865 return false;
866 }
867
868 // Nothing to do.
869 return false;
870}
871
872/// checkArgPlaceholdersForOverload - Check a set of call operands for
873/// placeholders.
874static bool checkArgPlaceholdersForOverload(Sema &S,
875 MultiExprArg Args,
876 UnbridgedCastsSet &unbridged) {
877 for (unsigned i = 0, e = Args.size(); i != e; ++i)
878 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
879 return true;
880
881 return false;
882}
883
884// IsOverload - Determine whether the given New declaration is an
885// overload of the declarations in Old. This routine returns false if
886// New and Old cannot be overloaded, e.g., if New has the same
887// signature as some function in Old (C++ 1.3.10) or if the Old
888// declarations aren't functions (or function templates) at all. When
889// it does return false, MatchedDecl will point to the decl that New
890// cannot be overloaded with. This decl may be a UsingShadowDecl on
891// top of the underlying declaration.
892//
893// Example: Given the following input:
894//
895// void f(int, float); // #1
896// void f(int, int); // #2
897// int f(int, int); // #3
898//
899// When we process #1, there is no previous declaration of "f",
900// so IsOverload will not be used.
901//
902// When we process #2, Old contains only the FunctionDecl for #1. By
903// comparing the parameter types, we see that #1 and #2 are overloaded
904// (since they have different signatures), so this routine returns
905// false; MatchedDecl is unchanged.
906//
907// When we process #3, Old is an overload set containing #1 and #2. We
908// compare the signatures of #3 to #1 (they're overloaded, so we do
909// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
910// identical (return types of functions are not part of the
911// signature), IsOverload returns false and MatchedDecl will be set to
912// point to the FunctionDecl for #2.
913//
914// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
915// into a class by a using declaration. The rules for whether to hide
916// shadow declarations ignore some properties which otherwise figure
917// into a function template's signature.
918Sema::OverloadKind
919Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
920 NamedDecl *&Match, bool NewIsUsingDecl) {
921 for (LookupResult::iterator I = Old.begin(), E = Old.end();
922 I != E; ++I) {
923 NamedDecl *OldD = *I;
924
925 bool OldIsUsingDecl = false;
926 if (isa<UsingShadowDecl>(OldD)) {
927 OldIsUsingDecl = true;
928
929 // We can always introduce two using declarations into the same
930 // context, even if they have identical signatures.
931 if (NewIsUsingDecl) continue;
932
933 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
934 }
935
936 // A using-declaration does not conflict with another declaration
937 // if one of them is hidden.
938 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
939 continue;
940
941 // If either declaration was introduced by a using declaration,
942 // we'll need to use slightly different rules for matching.
943 // Essentially, these rules are the normal rules, except that
944 // function templates hide function templates with different
945 // return types or template parameter lists.
946 bool UseMemberUsingDeclRules =
947 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
948 !New->getFriendObjectKind();
949
950 if (FunctionDecl *OldF = OldD->getAsFunction()) {
951 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
952 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
953 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
954 continue;
955 }
956
957 if (!isa<FunctionTemplateDecl>(OldD) &&
958 !shouldLinkPossiblyHiddenDecl(*I, New))
959 continue;
960
961 Match = *I;
962 return Ovl_Match;
963 }
964 } else if (isa<UsingDecl>(OldD)) {
965 // We can overload with these, which can show up when doing
966 // redeclaration checks for UsingDecls.
967 assert(Old.getLookupKind() == LookupUsingDeclName)((Old.getLookupKind() == LookupUsingDeclName) ? static_cast<
void> (0) : __assert_fail ("Old.getLookupKind() == LookupUsingDeclName"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 967, __PRETTY_FUNCTION__))
;
968 } else if (isa<TagDecl>(OldD)) {
969 // We can always overload with tags by hiding them.
970 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
971 // Optimistically assume that an unresolved using decl will
972 // overload; if it doesn't, we'll have to diagnose during
973 // template instantiation.
974 } else {
975 // (C++ 13p1):
976 // Only function declarations can be overloaded; object and type
977 // declarations cannot be overloaded.
978 Match = *I;
979 return Ovl_NonFunction;
980 }
981 }
982
983 return Ovl_Overload;
984}
985
986bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
987 bool UseUsingDeclRules) {
988 // C++ [basic.start.main]p2: This function shall not be overloaded.
989 if (New->isMain())
990 return false;
991
992 // MSVCRT user defined entry points cannot be overloaded.
993 if (New->isMSVCRTEntryPoint())
994 return false;
995
996 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
997 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
998
999 // C++ [temp.fct]p2:
1000 // A function template can be overloaded with other function templates
1001 // and with normal (non-template) functions.
1002 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1003 return true;
1004
1005 // Is the function New an overload of the function Old?
1006 QualType OldQType = Context.getCanonicalType(Old->getType());
1007 QualType NewQType = Context.getCanonicalType(New->getType());
1008
1009 // Compare the signatures (C++ 1.3.10) of the two functions to
1010 // determine whether they are overloads. If we find any mismatch
1011 // in the signature, they are overloads.
1012
1013 // If either of these functions is a K&R-style function (no
1014 // prototype), then we consider them to have matching signatures.
1015 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1016 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1017 return false;
1018
1019 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1020 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1021
1022 // The signature of a function includes the types of its
1023 // parameters (C++ 1.3.10), which includes the presence or absence
1024 // of the ellipsis; see C++ DR 357).
1025 if (OldQType != NewQType &&
1026 (OldType->getNumParams() != NewType->getNumParams() ||
1027 OldType->isVariadic() != NewType->isVariadic() ||
1028 !FunctionParamTypesAreEqual(OldType, NewType)))
1029 return true;
1030
1031 // C++ [temp.over.link]p4:
1032 // The signature of a function template consists of its function
1033 // signature, its return type and its template parameter list. The names
1034 // of the template parameters are significant only for establishing the
1035 // relationship between the template parameters and the rest of the
1036 // signature.
1037 //
1038 // We check the return type and template parameter lists for function
1039 // templates first; the remaining checks follow.
1040 //
1041 // However, we don't consider either of these when deciding whether
1042 // a member introduced by a shadow declaration is hidden.
1043 if (!UseUsingDeclRules && NewTemplate &&
1044 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1045 OldTemplate->getTemplateParameters(),
1046 false, TPL_TemplateMatch) ||
1047 OldType->getReturnType() != NewType->getReturnType()))
1048 return true;
1049
1050 // If the function is a class member, its signature includes the
1051 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1052 //
1053 // As part of this, also check whether one of the member functions
1054 // is static, in which case they are not overloads (C++
1055 // 13.1p2). While not part of the definition of the signature,
1056 // this check is important to determine whether these functions
1057 // can be overloaded.
1058 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1059 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1060 if (OldMethod && NewMethod &&
1061 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1062 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1063 if (!UseUsingDeclRules &&
1064 (OldMethod->getRefQualifier() == RQ_None ||
1065 NewMethod->getRefQualifier() == RQ_None)) {
1066 // C++0x [over.load]p2:
1067 // - Member function declarations with the same name and the same
1068 // parameter-type-list as well as member function template
1069 // declarations with the same name, the same parameter-type-list, and
1070 // the same template parameter lists cannot be overloaded if any of
1071 // them, but not all, have a ref-qualifier (8.3.5).
1072 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1073 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1074 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1075 }
1076 return true;
1077 }
1078
1079 // We may not have applied the implicit const for a constexpr member
1080 // function yet (because we haven't yet resolved whether this is a static
1081 // or non-static member function). Add it now, on the assumption that this
1082 // is a redeclaration of OldMethod.
1083 unsigned OldQuals = OldMethod->getTypeQualifiers();
1084 unsigned NewQuals = NewMethod->getTypeQualifiers();
1085 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1086 !isa<CXXConstructorDecl>(NewMethod))
1087 NewQuals |= Qualifiers::Const;
1088
1089 // We do not allow overloading based off of '__restrict'.
1090 OldQuals &= ~Qualifiers::Restrict;
1091 NewQuals &= ~Qualifiers::Restrict;
1092 if (OldQuals != NewQuals)
1093 return true;
1094 }
1095
1096 // Though pass_object_size is placed on parameters and takes an argument, we
1097 // consider it to be a function-level modifier for the sake of function
1098 // identity. Either the function has one or more parameters with
1099 // pass_object_size or it doesn't.
1100 if (functionHasPassObjectSizeParams(New) !=
1101 functionHasPassObjectSizeParams(Old))
1102 return true;
1103
1104 // enable_if attributes are an order-sensitive part of the signature.
1105 for (specific_attr_iterator<EnableIfAttr>
1106 NewI = New->specific_attr_begin<EnableIfAttr>(),
1107 NewE = New->specific_attr_end<EnableIfAttr>(),
1108 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1109 OldE = Old->specific_attr_end<EnableIfAttr>();
1110 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1111 if (NewI == NewE || OldI == OldE)
1112 return true;
1113 llvm::FoldingSetNodeID NewID, OldID;
1114 NewI->getCond()->Profile(NewID, Context, true);
1115 OldI->getCond()->Profile(OldID, Context, true);
1116 if (NewID != OldID)
1117 return true;
1118 }
1119
1120 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) {
1121 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1122 OldTarget = IdentifyCUDATarget(Old);
1123 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global)
1124 return false;
1125
1126 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.")(((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."
) ? static_cast<void> (0) : __assert_fail ("(OldTarget != CFT_InvalidTarget) && \"Unexpected invalid target.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1126, __PRETTY_FUNCTION__))
;
1127
1128 // Don't allow mixing of HD with other kinds. This guarantees that
1129 // we have only one viable function with this signature on any
1130 // side of CUDA compilation .
1131 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice))
1132 return false;
1133
1134 // Allow overloading of functions with same signature, but
1135 // different CUDA target attributes.
1136 return NewTarget != OldTarget;
1137 }
1138
1139 // The signatures match; this is not an overload.
1140 return false;
1141}
1142
1143/// \brief Checks availability of the function depending on the current
1144/// function context. Inside an unavailable function, unavailability is ignored.
1145///
1146/// \returns true if \arg FD is unavailable and current context is inside
1147/// an available function, false otherwise.
1148bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1149 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1150}
1151
1152/// \brief Tries a user-defined conversion from From to ToType.
1153///
1154/// Produces an implicit conversion sequence for when a standard conversion
1155/// is not an option. See TryImplicitConversion for more information.
1156static ImplicitConversionSequence
1157TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1158 bool SuppressUserConversions,
1159 bool AllowExplicit,
1160 bool InOverloadResolution,
1161 bool CStyle,
1162 bool AllowObjCWritebackConversion,
1163 bool AllowObjCConversionOnExplicit) {
1164 ImplicitConversionSequence ICS;
1165
1166 if (SuppressUserConversions) {
1167 // We're not in the case above, so there is no conversion that
1168 // we can perform.
1169 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1170 return ICS;
1171 }
1172
1173 // Attempt user-defined conversion.
1174 OverloadCandidateSet Conversions(From->getExprLoc(),
1175 OverloadCandidateSet::CSK_Normal);
1176 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1177 Conversions, AllowExplicit,
1178 AllowObjCConversionOnExplicit)) {
1179 case OR_Success:
1180 case OR_Deleted:
1181 ICS.setUserDefined();
1182 ICS.UserDefined.Before.setAsIdentityConversion();
1183 // C++ [over.ics.user]p4:
1184 // A conversion of an expression of class type to the same class
1185 // type is given Exact Match rank, and a conversion of an
1186 // expression of class type to a base class of that type is
1187 // given Conversion rank, in spite of the fact that a copy
1188 // constructor (i.e., a user-defined conversion function) is
1189 // called for those cases.
1190 if (CXXConstructorDecl *Constructor
1191 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1192 QualType FromCanon
1193 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1194 QualType ToCanon
1195 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1196 if (Constructor->isCopyConstructor() &&
1197 (FromCanon == ToCanon ||
1198 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1199 // Turn this into a "standard" conversion sequence, so that it
1200 // gets ranked with standard conversion sequences.
1201 ICS.setStandard();
1202 ICS.Standard.setAsIdentityConversion();
1203 ICS.Standard.setFromType(From->getType());
1204 ICS.Standard.setAllToTypes(ToType);
1205 ICS.Standard.CopyConstructor = Constructor;
1206 if (ToCanon != FromCanon)
1207 ICS.Standard.Second = ICK_Derived_To_Base;
1208 }
1209 }
1210 break;
1211
1212 case OR_Ambiguous:
1213 ICS.setAmbiguous();
1214 ICS.Ambiguous.setFromType(From->getType());
1215 ICS.Ambiguous.setToType(ToType);
1216 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1217 Cand != Conversions.end(); ++Cand)
1218 if (Cand->Viable)
1219 ICS.Ambiguous.addConversion(Cand->Function);
1220 break;
1221
1222 // Fall through.
1223 case OR_No_Viable_Function:
1224 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1225 break;
1226 }
1227
1228 return ICS;
1229}
1230
1231/// TryImplicitConversion - Attempt to perform an implicit conversion
1232/// from the given expression (Expr) to the given type (ToType). This
1233/// function returns an implicit conversion sequence that can be used
1234/// to perform the initialization. Given
1235///
1236/// void f(float f);
1237/// void g(int i) { f(i); }
1238///
1239/// this routine would produce an implicit conversion sequence to
1240/// describe the initialization of f from i, which will be a standard
1241/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1242/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1243//
1244/// Note that this routine only determines how the conversion can be
1245/// performed; it does not actually perform the conversion. As such,
1246/// it will not produce any diagnostics if no conversion is available,
1247/// but will instead return an implicit conversion sequence of kind
1248/// "BadConversion".
1249///
1250/// If @p SuppressUserConversions, then user-defined conversions are
1251/// not permitted.
1252/// If @p AllowExplicit, then explicit user-defined conversions are
1253/// permitted.
1254///
1255/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1256/// writeback conversion, which allows __autoreleasing id* parameters to
1257/// be initialized with __strong id* or __weak id* arguments.
1258static ImplicitConversionSequence
1259TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1260 bool SuppressUserConversions,
1261 bool AllowExplicit,
1262 bool InOverloadResolution,
1263 bool CStyle,
1264 bool AllowObjCWritebackConversion,
1265 bool AllowObjCConversionOnExplicit) {
1266 ImplicitConversionSequence ICS;
1267 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1268 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1269 ICS.setStandard();
1270 return ICS;
1271 }
1272
1273 if (!S.getLangOpts().CPlusPlus) {
1274 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1275 return ICS;
1276 }
1277
1278 // C++ [over.ics.user]p4:
1279 // A conversion of an expression of class type to the same class
1280 // type is given Exact Match rank, and a conversion of an
1281 // expression of class type to a base class of that type is
1282 // given Conversion rank, in spite of the fact that a copy/move
1283 // constructor (i.e., a user-defined conversion function) is
1284 // called for those cases.
1285 QualType FromType = From->getType();
1286 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1287 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1288 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1289 ICS.setStandard();
1290 ICS.Standard.setAsIdentityConversion();
1291 ICS.Standard.setFromType(FromType);
1292 ICS.Standard.setAllToTypes(ToType);
1293
1294 // We don't actually check at this point whether there is a valid
1295 // copy/move constructor, since overloading just assumes that it
1296 // exists. When we actually perform initialization, we'll find the
1297 // appropriate constructor to copy the returned object, if needed.
1298 ICS.Standard.CopyConstructor = nullptr;
1299
1300 // Determine whether this is considered a derived-to-base conversion.
1301 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1302 ICS.Standard.Second = ICK_Derived_To_Base;
1303
1304 return ICS;
1305 }
1306
1307 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1308 AllowExplicit, InOverloadResolution, CStyle,
1309 AllowObjCWritebackConversion,
1310 AllowObjCConversionOnExplicit);
1311}
1312
1313ImplicitConversionSequence
1314Sema::TryImplicitConversion(Expr *From, QualType ToType,
1315 bool SuppressUserConversions,
1316 bool AllowExplicit,
1317 bool InOverloadResolution,
1318 bool CStyle,
1319 bool AllowObjCWritebackConversion) {
1320 return ::TryImplicitConversion(*this, From, ToType,
1321 SuppressUserConversions, AllowExplicit,
1322 InOverloadResolution, CStyle,
1323 AllowObjCWritebackConversion,
1324 /*AllowObjCConversionOnExplicit=*/false);
1325}
1326
1327/// PerformImplicitConversion - Perform an implicit conversion of the
1328/// expression From to the type ToType. Returns the
1329/// converted expression. Flavor is the kind of conversion we're
1330/// performing, used in the error message. If @p AllowExplicit,
1331/// explicit user-defined conversions are permitted.
1332ExprResult
1333Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1334 AssignmentAction Action, bool AllowExplicit) {
1335 ImplicitConversionSequence ICS;
1336 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1337}
1338
1339ExprResult
1340Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1341 AssignmentAction Action, bool AllowExplicit,
1342 ImplicitConversionSequence& ICS) {
1343 if (checkPlaceholderForOverload(*this, From))
1344 return ExprError();
1345
1346 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1347 bool AllowObjCWritebackConversion
1348 = getLangOpts().ObjCAutoRefCount &&
1349 (Action == AA_Passing || Action == AA_Sending);
1350 if (getLangOpts().ObjC1)
1351 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1352 ToType, From->getType(), From);
1353 ICS = ::TryImplicitConversion(*this, From, ToType,
1354 /*SuppressUserConversions=*/false,
1355 AllowExplicit,
1356 /*InOverloadResolution=*/false,
1357 /*CStyle=*/false,
1358 AllowObjCWritebackConversion,
1359 /*AllowObjCConversionOnExplicit=*/false);
1360 return PerformImplicitConversion(From, ToType, ICS, Action);
1361}
1362
1363/// \brief Determine whether the conversion from FromType to ToType is a valid
1364/// conversion that strips "noreturn" off the nested function type.
1365bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1366 QualType &ResultTy) {
1367 if (Context.hasSameUnqualifiedType(FromType, ToType))
1368 return false;
1369
1370 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1371 // where F adds one of the following at most once:
1372 // - a pointer
1373 // - a member pointer
1374 // - a block pointer
1375 CanQualType CanTo = Context.getCanonicalType(ToType);
1376 CanQualType CanFrom = Context.getCanonicalType(FromType);
1377 Type::TypeClass TyClass = CanTo->getTypeClass();
1378 if (TyClass != CanFrom->getTypeClass()) return false;
1379 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1380 if (TyClass == Type::Pointer) {
1381 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1382 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1383 } else if (TyClass == Type::BlockPointer) {
1384 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1385 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1386 } else if (TyClass == Type::MemberPointer) {
1387 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1388 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1389 } else {
1390 return false;
1391 }
1392
1393 TyClass = CanTo->getTypeClass();
1394 if (TyClass != CanFrom->getTypeClass()) return false;
1395 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1396 return false;
1397 }
1398
1399 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1400 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1401 if (!EInfo.getNoReturn()) return false;
1402
1403 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1404 assert(QualType(FromFn, 0).isCanonical())((QualType(FromFn, 0).isCanonical()) ? static_cast<void>
(0) : __assert_fail ("QualType(FromFn, 0).isCanonical()", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1404, __PRETTY_FUNCTION__))
;
1405 if (QualType(FromFn, 0) != CanTo) return false;
1406
1407 ResultTy = ToType;
1408 return true;
1409}
1410
1411/// \brief Determine whether the conversion from FromType to ToType is a valid
1412/// vector conversion.
1413///
1414/// \param ICK Will be set to the vector conversion kind, if this is a vector
1415/// conversion.
1416static bool IsVectorConversion(Sema &S, QualType FromType,
1417 QualType ToType, ImplicitConversionKind &ICK) {
1418 // We need at least one of these types to be a vector type to have a vector
1419 // conversion.
1420 if (!ToType->isVectorType() && !FromType->isVectorType())
1421 return false;
1422
1423 // Identical types require no conversions.
1424 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1425 return false;
1426
1427 // There are no conversions between extended vector types, only identity.
1428 if (ToType->isExtVectorType()) {
1429 // There are no conversions between extended vector types other than the
1430 // identity conversion.
1431 if (FromType->isExtVectorType())
1432 return false;
1433
1434 // Vector splat from any arithmetic type to a vector.
1435 if (FromType->isArithmeticType()) {
1436 ICK = ICK_Vector_Splat;
1437 return true;
1438 }
1439 }
1440
1441 // We can perform the conversion between vector types in the following cases:
1442 // 1)vector types are equivalent AltiVec and GCC vector types
1443 // 2)lax vector conversions are permitted and the vector types are of the
1444 // same size
1445 if (ToType->isVectorType() && FromType->isVectorType()) {
1446 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1447 S.isLaxVectorConversion(FromType, ToType)) {
1448 ICK = ICK_Vector_Conversion;
1449 return true;
1450 }
1451 }
1452
1453 return false;
1454}
1455
1456static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1457 bool InOverloadResolution,
1458 StandardConversionSequence &SCS,
1459 bool CStyle);
1460
1461/// IsStandardConversion - Determines whether there is a standard
1462/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1463/// expression From to the type ToType. Standard conversion sequences
1464/// only consider non-class types; for conversions that involve class
1465/// types, use TryImplicitConversion. If a conversion exists, SCS will
1466/// contain the standard conversion sequence required to perform this
1467/// conversion and this routine will return true. Otherwise, this
1468/// routine will return false and the value of SCS is unspecified.
1469static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1470 bool InOverloadResolution,
1471 StandardConversionSequence &SCS,
1472 bool CStyle,
1473 bool AllowObjCWritebackConversion) {
1474 QualType FromType = From->getType();
1475
1476 // Standard conversions (C++ [conv])
1477 SCS.setAsIdentityConversion();
1478 SCS.IncompatibleObjC = false;
1479 SCS.setFromType(FromType);
1480 SCS.CopyConstructor = nullptr;
1481
1482 // There are no standard conversions for class types in C++, so
1483 // abort early. When overloading in C, however, we do permit them.
1484 if (S.getLangOpts().CPlusPlus &&
1485 (FromType->isRecordType() || ToType->isRecordType()))
1486 return false;
1487
1488 // The first conversion can be an lvalue-to-rvalue conversion,
1489 // array-to-pointer conversion, or function-to-pointer conversion
1490 // (C++ 4p1).
1491
1492 if (FromType == S.Context.OverloadTy) {
1493 DeclAccessPair AccessPair;
1494 if (FunctionDecl *Fn
1495 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1496 AccessPair)) {
1497 // We were able to resolve the address of the overloaded function,
1498 // so we can convert to the type of that function.
1499 FromType = Fn->getType();
1500 SCS.setFromType(FromType);
1501
1502 // we can sometimes resolve &foo<int> regardless of ToType, so check
1503 // if the type matches (identity) or we are converting to bool
1504 if (!S.Context.hasSameUnqualifiedType(
1505 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1506 QualType resultTy;
1507 // if the function type matches except for [[noreturn]], it's ok
1508 if (!S.IsNoReturnConversion(FromType,
1509 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1510 // otherwise, only a boolean conversion is standard
1511 if (!ToType->isBooleanType())
1512 return false;
1513 }
1514
1515 // Check if the "from" expression is taking the address of an overloaded
1516 // function and recompute the FromType accordingly. Take advantage of the
1517 // fact that non-static member functions *must* have such an address-of
1518 // expression.
1519 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1520 if (Method && !Method->isStatic()) {
1521 assert(isa<UnaryOperator>(From->IgnoreParens()) &&((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1522, __PRETTY_FUNCTION__))
1522 "Non-unary operator on non-static member address")((isa<UnaryOperator>(From->IgnoreParens()) &&
"Non-unary operator on non-static member address") ? static_cast
<void> (0) : __assert_fail ("isa<UnaryOperator>(From->IgnoreParens()) && \"Non-unary operator on non-static member address\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1522, __PRETTY_FUNCTION__))
;
1523 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1525, __PRETTY_FUNCTION__))
1524 == UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1525, __PRETTY_FUNCTION__))
1525 "Non-address-of operator on non-static member address")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator on non-static member address"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator on non-static member address\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1525, __PRETTY_FUNCTION__))
;
1526 const Type *ClassType
1527 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1528 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1529 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1530 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1532, __PRETTY_FUNCTION__))
1531 UO_AddrOf &&((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1532, __PRETTY_FUNCTION__))
1532 "Non-address-of operator for overloaded function expression")((cast<UnaryOperator>(From->IgnoreParens())->getOpcode
() == UO_AddrOf && "Non-address-of operator for overloaded function expression"
) ? static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == UO_AddrOf && \"Non-address-of operator for overloaded function expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1532, __PRETTY_FUNCTION__))
;
1533 FromType = S.Context.getPointerType(FromType);
1534 }
1535
1536 // Check that we've computed the proper type after overload resolution.
1537 assert(S.Context.hasSameType(((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1539, __PRETTY_FUNCTION__))
1538 FromType,((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1539, __PRETTY_FUNCTION__))
1539 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()))((S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference
(From, AccessPair, Fn)->getType())) ? static_cast<void>
(0) : __assert_fail ("S.Context.hasSameType( FromType, S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 1539, __PRETTY_FUNCTION__))
;
1540 } else {
1541 return false;
1542 }
1543 }
1544 // Lvalue-to-rvalue conversion (C++11 4.1):
1545 // A glvalue (3.10) of a non-function, non-array type T can
1546 // be converted to a prvalue.
1547 bool argIsLValue = From->isGLValue();
1548 if (argIsLValue &&
1549 !FromType->isFunctionType() && !FromType->isArrayType() &&
1550 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1551 SCS.First = ICK_Lvalue_To_Rvalue;
1552
1553 // C11 6.3.2.1p2:
1554 // ... if the lvalue has atomic type, the value has the non-atomic version
1555 // of the type of the lvalue ...
1556 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1557 FromType = Atomic->getValueType();
1558
1559 // If T is a non-class type, the type of the rvalue is the
1560 // cv-unqualified version of T. Otherwise, the type of the rvalue
1561 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1562 // just strip the qualifiers because they don't matter.
1563 FromType = FromType.getUnqualifiedType();
1564 } else if (FromType->isArrayType()) {
1565 // Array-to-pointer conversion (C++ 4.2)
1566 SCS.First = ICK_Array_To_Pointer;
1567
1568 // An lvalue or rvalue of type "array of N T" or "array of unknown
1569 // bound of T" can be converted to an rvalue of type "pointer to
1570 // T" (C++ 4.2p1).
1571 FromType = S.Context.getArrayDecayedType(FromType);
1572
1573 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1574 // This conversion is deprecated in C++03 (D.4)
1575 SCS.DeprecatedStringLiteralToCharPtr = true;
1576
1577 // For the purpose of ranking in overload resolution
1578 // (13.3.3.1.1), this conversion is considered an
1579 // array-to-pointer conversion followed by a qualification
1580 // conversion (4.4). (C++ 4.2p2)
1581 SCS.Second = ICK_Identity;
1582 SCS.Third = ICK_Qualification;
1583 SCS.QualificationIncludesObjCLifetime = false;
1584 SCS.setAllToTypes(FromType);
1585 return true;
1586 }
1587 } else if (FromType->isFunctionType() && argIsLValue) {
1588 // Function-to-pointer conversion (C++ 4.3).
1589 SCS.First = ICK_Function_To_Pointer;
1590
1591 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1592 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1593 if (!S.checkAddressOfFunctionIsAvailable(FD))
1594 return false;
1595
1596 // An lvalue of function type T can be converted to an rvalue of
1597 // type "pointer to T." The result is a pointer to the
1598 // function. (C++ 4.3p1).
1599 FromType = S.Context.getPointerType(FromType);
1600 } else {
1601 // We don't require any conversions for the first step.
1602 SCS.First = ICK_Identity;
1603 }
1604 SCS.setToType(0, FromType);
1605
1606 // The second conversion can be an integral promotion, floating
1607 // point promotion, integral conversion, floating point conversion,
1608 // floating-integral conversion, pointer conversion,
1609 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1610 // For overloading in C, this can also be a "compatible-type"
1611 // conversion.
1612 bool IncompatibleObjC = false;
1613 ImplicitConversionKind SecondICK = ICK_Identity;
1614 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1615 // The unqualified versions of the types are the same: there's no
1616 // conversion to do.
1617 SCS.Second = ICK_Identity;
1618 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1619 // Integral promotion (C++ 4.5).
1620 SCS.Second = ICK_Integral_Promotion;
1621 FromType = ToType.getUnqualifiedType();
1622 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1623 // Floating point promotion (C++ 4.6).
1624 SCS.Second = ICK_Floating_Promotion;
1625 FromType = ToType.getUnqualifiedType();
1626 } else if (S.IsComplexPromotion(FromType, ToType)) {
1627 // Complex promotion (Clang extension)
1628 SCS.Second = ICK_Complex_Promotion;
1629 FromType = ToType.getUnqualifiedType();
1630 } else if (ToType->isBooleanType() &&
1631 (FromType->isArithmeticType() ||
1632 FromType->isAnyPointerType() ||
1633 FromType->isBlockPointerType() ||
1634 FromType->isMemberPointerType() ||
1635 FromType->isNullPtrType())) {
1636 // Boolean conversions (C++ 4.12).
1637 SCS.Second = ICK_Boolean_Conversion;
1638 FromType = S.Context.BoolTy;
1639 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1640 ToType->isIntegralType(S.Context)) {
1641 // Integral conversions (C++ 4.7).
1642 SCS.Second = ICK_Integral_Conversion;
1643 FromType = ToType.getUnqualifiedType();
1644 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1645 // Complex conversions (C99 6.3.1.6)
1646 SCS.Second = ICK_Complex_Conversion;
1647 FromType = ToType.getUnqualifiedType();
1648 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1649 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1650 // Complex-real conversions (C99 6.3.1.7)
1651 SCS.Second = ICK_Complex_Real;
1652 FromType = ToType.getUnqualifiedType();
1653 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1654 // Floating point conversions (C++ 4.8).
1655 SCS.Second = ICK_Floating_Conversion;
1656 FromType = ToType.getUnqualifiedType();
1657 } else if ((FromType->isRealFloatingType() &&
1658 ToType->isIntegralType(S.Context)) ||
1659 (FromType->isIntegralOrUnscopedEnumerationType() &&
1660 ToType->isRealFloatingType())) {
1661 // Floating-integral conversions (C++ 4.9).
1662 SCS.Second = ICK_Floating_Integral;
1663 FromType = ToType.getUnqualifiedType();
1664 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1665 SCS.Second = ICK_Block_Pointer_Conversion;
1666 } else if (AllowObjCWritebackConversion &&
1667 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1668 SCS.Second = ICK_Writeback_Conversion;
1669 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1670 FromType, IncompatibleObjC)) {
1671 // Pointer conversions (C++ 4.10).
1672 SCS.Second = ICK_Pointer_Conversion;
1673 SCS.IncompatibleObjC = IncompatibleObjC;
1674 FromType = FromType.getUnqualifiedType();
1675 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1676 InOverloadResolution, FromType)) {
1677 // Pointer to member conversions (4.11).
1678 SCS.Second = ICK_Pointer_Member;
1679 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1680 SCS.Second = SecondICK;
1681 FromType = ToType.getUnqualifiedType();
1682 } else if (!S.getLangOpts().CPlusPlus &&
1683 S.Context.typesAreCompatible(ToType, FromType)) {
1684 // Compatible conversions (Clang extension for C function overloading)
1685 SCS.Second = ICK_Compatible_Conversion;
1686 FromType = ToType.getUnqualifiedType();
1687 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1688 // Treat a conversion that strips "noreturn" as an identity conversion.
1689 SCS.Second = ICK_NoReturn_Adjustment;
1690 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1691 InOverloadResolution,
1692 SCS, CStyle)) {
1693 SCS.Second = ICK_TransparentUnionConversion;
1694 FromType = ToType;
1695 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1696 CStyle)) {
1697 // tryAtomicConversion has updated the standard conversion sequence
1698 // appropriately.
1699 return true;
1700 } else if (ToType->isEventT() &&
1701 From->isIntegerConstantExpr(S.getASTContext()) &&
1702 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1703 SCS.Second = ICK_Zero_Event_Conversion;
1704 FromType = ToType;
1705 } else {
1706 // No second conversion required.
1707 SCS.Second = ICK_Identity;
1708 }
1709 SCS.setToType(1, FromType);
1710
1711 QualType CanonFrom;
1712 QualType CanonTo;
1713 // The third conversion can be a qualification conversion (C++ 4p1).
1714 bool ObjCLifetimeConversion;
1715 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1716 ObjCLifetimeConversion)) {
1717 SCS.Third = ICK_Qualification;
1718 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1719 FromType = ToType;
1720 CanonFrom = S.Context.getCanonicalType(FromType);
1721 CanonTo = S.Context.getCanonicalType(ToType);
1722 } else {
1723 // No conversion required
1724 SCS.Third = ICK_Identity;
1725
1726 // C++ [over.best.ics]p6:
1727 // [...] Any difference in top-level cv-qualification is
1728 // subsumed by the initialization itself and does not constitute
1729 // a conversion. [...]
1730 CanonFrom = S.Context.getCanonicalType(FromType);
1731 CanonTo = S.Context.getCanonicalType(ToType);
1732 if (CanonFrom.getLocalUnqualifiedType()
1733 == CanonTo.getLocalUnqualifiedType() &&
1734 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1735 FromType = ToType;
1736 CanonFrom = CanonTo;
1737 }
1738 }
1739 SCS.setToType(2, FromType);
1740
1741 if (CanonFrom == CanonTo)
1742 return true;
1743
1744 // If we have not converted the argument type to the parameter type,
1745 // this is a bad conversion sequence, unless we're resolving an overload in C.
1746 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1747 return false;
1748
1749 ExprResult ER = ExprResult{From};
1750 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER,
1751 /*Diagnose=*/false,
1752 /*DiagnoseCFAudited=*/false,
1753 /*ConvertRHS=*/false);
1754 if (Conv != Sema::Compatible)
1755 return false;
1756
1757 SCS.setAllToTypes(ToType);
1758 // We need to set all three because we want this conversion to rank terribly,
1759 // and we don't know what conversions it may overlap with.
1760 SCS.First = ICK_C_Only_Conversion;
1761 SCS.Second = ICK_C_Only_Conversion;
1762 SCS.Third = ICK_C_Only_Conversion;
1763 return true;
1764}
1765
1766static bool
1767IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1768 QualType &ToType,
1769 bool InOverloadResolution,
1770 StandardConversionSequence &SCS,
1771 bool CStyle) {
1772
1773 const RecordType *UT = ToType->getAsUnionType();
1774 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1775 return false;
1776 // The field to initialize within the transparent union.
1777 RecordDecl *UD = UT->getDecl();
1778 // It's compatible if the expression matches any of the fields.
1779 for (const auto *it : UD->fields()) {
1780 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1781 CStyle, /*ObjCWritebackConversion=*/false)) {
1782 ToType = it->getType();
1783 return true;
1784 }
1785 }
1786 return false;
1787}
1788
1789/// IsIntegralPromotion - Determines whether the conversion from the
1790/// expression From (whose potentially-adjusted type is FromType) to
1791/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1792/// sets PromotedType to the promoted type.
1793bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1794 const BuiltinType *To = ToType->getAs<BuiltinType>();
1795 // All integers are built-in.
1796 if (!To) {
1797 return false;
1798 }
1799
1800 // An rvalue of type char, signed char, unsigned char, short int, or
1801 // unsigned short int can be converted to an rvalue of type int if
1802 // int can represent all the values of the source type; otherwise,
1803 // the source rvalue can be converted to an rvalue of type unsigned
1804 // int (C++ 4.5p1).
1805 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1806 !FromType->isEnumeralType()) {
1807 if (// We can promote any signed, promotable integer type to an int
1808 (FromType->isSignedIntegerType() ||
1809 // We can promote any unsigned integer type whose size is
1810 // less than int to an int.
1811 (!FromType->isSignedIntegerType() &&
1812 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1813 return To->getKind() == BuiltinType::Int;
1814 }
1815
1816 return To->getKind() == BuiltinType::UInt;
1817 }
1818
1819 // C++11 [conv.prom]p3:
1820 // A prvalue of an unscoped enumeration type whose underlying type is not
1821 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1822 // following types that can represent all the values of the enumeration
1823 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1824 // unsigned int, long int, unsigned long int, long long int, or unsigned
1825 // long long int. If none of the types in that list can represent all the
1826 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1827 // type can be converted to an rvalue a prvalue of the extended integer type
1828 // with lowest integer conversion rank (4.13) greater than the rank of long
1829 // long in which all the values of the enumeration can be represented. If
1830 // there are two such extended types, the signed one is chosen.
1831 // C++11 [conv.prom]p4:
1832 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1833 // can be converted to a prvalue of its underlying type. Moreover, if
1834 // integral promotion can be applied to its underlying type, a prvalue of an
1835 // unscoped enumeration type whose underlying type is fixed can also be
1836 // converted to a prvalue of the promoted underlying type.
1837 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1838 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1839 // provided for a scoped enumeration.
1840 if (FromEnumType->getDecl()->isScoped())
1841 return false;
1842
1843 // We can perform an integral promotion to the underlying type of the enum,
1844 // even if that's not the promoted type. Note that the check for promoting
1845 // the underlying type is based on the type alone, and does not consider
1846 // the bitfield-ness of the actual source expression.
1847 if (FromEnumType->getDecl()->isFixed()) {
1848 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1849 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1850 IsIntegralPromotion(nullptr, Underlying, ToType);
1851 }
1852
1853 // We have already pre-calculated the promotion type, so this is trivial.
1854 if (ToType->isIntegerType() &&
1855 isCompleteType(From->getLocStart(), FromType))
1856 return Context.hasSameUnqualifiedType(
1857 ToType, FromEnumType->getDecl()->getPromotionType());
1858 }
1859
1860 // C++0x [conv.prom]p2:
1861 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1862 // to an rvalue a prvalue of the first of the following types that can
1863 // represent all the values of its underlying type: int, unsigned int,
1864 // long int, unsigned long int, long long int, or unsigned long long int.
1865 // If none of the types in that list can represent all the values of its
1866 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1867 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1868 // type.
1869 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1870 ToType->isIntegerType()) {
1871 // Determine whether the type we're converting from is signed or
1872 // unsigned.
1873 bool FromIsSigned = FromType->isSignedIntegerType();
1874 uint64_t FromSize = Context.getTypeSize(FromType);
1875
1876 // The types we'll try to promote to, in the appropriate
1877 // order. Try each of these types.
1878 QualType PromoteTypes[6] = {
1879 Context.IntTy, Context.UnsignedIntTy,
1880 Context.LongTy, Context.UnsignedLongTy ,
1881 Context.LongLongTy, Context.UnsignedLongLongTy
1882 };
1883 for (int Idx = 0; Idx < 6; ++Idx) {
1884 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1885 if (FromSize < ToSize ||
1886 (FromSize == ToSize &&
1887 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1888 // We found the type that we can promote to. If this is the
1889 // type we wanted, we have a promotion. Otherwise, no
1890 // promotion.
1891 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1892 }
1893 }
1894 }
1895
1896 // An rvalue for an integral bit-field (9.6) can be converted to an
1897 // rvalue of type int if int can represent all the values of the
1898 // bit-field; otherwise, it can be converted to unsigned int if
1899 // unsigned int can represent all the values of the bit-field. If
1900 // the bit-field is larger yet, no integral promotion applies to
1901 // it. If the bit-field has an enumerated type, it is treated as any
1902 // other value of that type for promotion purposes (C++ 4.5p3).
1903 // FIXME: We should delay checking of bit-fields until we actually perform the
1904 // conversion.
1905 if (From) {
1906 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1907 llvm::APSInt BitWidth;
1908 if (FromType->isIntegralType(Context) &&
1909 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1910 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1911 ToSize = Context.getTypeSize(ToType);
1912
1913 // Are we promoting to an int from a bitfield that fits in an int?
1914 if (BitWidth < ToSize ||
1915 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1916 return To->getKind() == BuiltinType::Int;
1917 }
1918
1919 // Are we promoting to an unsigned int from an unsigned bitfield
1920 // that fits into an unsigned int?
1921 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1922 return To->getKind() == BuiltinType::UInt;
1923 }
1924
1925 return false;
1926 }
1927 }
1928 }
1929
1930 // An rvalue of type bool can be converted to an rvalue of type int,
1931 // with false becoming zero and true becoming one (C++ 4.5p4).
1932 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1933 return true;
1934 }
1935
1936 return false;
1937}
1938
1939/// IsFloatingPointPromotion - Determines whether the conversion from
1940/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1941/// returns true and sets PromotedType to the promoted type.
1942bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1943 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1944 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1945 /// An rvalue of type float can be converted to an rvalue of type
1946 /// double. (C++ 4.6p1).
1947 if (FromBuiltin->getKind() == BuiltinType::Float &&
1948 ToBuiltin->getKind() == BuiltinType::Double)
1949 return true;
1950
1951 // C99 6.3.1.5p1:
1952 // When a float is promoted to double or long double, or a
1953 // double is promoted to long double [...].
1954 if (!getLangOpts().CPlusPlus &&
1955 (FromBuiltin->getKind() == BuiltinType::Float ||
1956 FromBuiltin->getKind() == BuiltinType::Double) &&
1957 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1958 return true;
1959
1960 // Half can be promoted to float.
1961 if (!getLangOpts().NativeHalfType &&
1962 FromBuiltin->getKind() == BuiltinType::Half &&
1963 ToBuiltin->getKind() == BuiltinType::Float)
1964 return true;
1965 }
1966
1967 return false;
1968}
1969
1970/// \brief Determine if a conversion is a complex promotion.
1971///
1972/// A complex promotion is defined as a complex -> complex conversion
1973/// where the conversion between the underlying real types is a
1974/// floating-point or integral promotion.
1975bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1976 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1977 if (!FromComplex)
1978 return false;
1979
1980 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1981 if (!ToComplex)
1982 return false;
1983
1984 return IsFloatingPointPromotion(FromComplex->getElementType(),
1985 ToComplex->getElementType()) ||
1986 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1987 ToComplex->getElementType());
1988}
1989
1990/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1991/// the pointer type FromPtr to a pointer to type ToPointee, with the
1992/// same type qualifiers as FromPtr has on its pointee type. ToType,
1993/// if non-empty, will be a pointer to ToType that may or may not have
1994/// the right set of qualifiers on its pointee.
1995///
1996static QualType
1997BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1998 QualType ToPointee, QualType ToType,
1999 ASTContext &Context,
2000 bool StripObjCLifetime = false) {
2001 assert((FromPtr->getTypeClass() == Type::Pointer ||(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2003, __PRETTY_FUNCTION__))
2002 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2003, __PRETTY_FUNCTION__))
2003 "Invalid similarly-qualified pointer type")(((FromPtr->getTypeClass() == Type::Pointer || FromPtr->
getTypeClass() == Type::ObjCObjectPointer) && "Invalid similarly-qualified pointer type"
) ? static_cast<void> (0) : __assert_fail ("(FromPtr->getTypeClass() == Type::Pointer || FromPtr->getTypeClass() == Type::ObjCObjectPointer) && \"Invalid similarly-qualified pointer type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2003, __PRETTY_FUNCTION__))
;
2004
2005 /// Conversions to 'id' subsume cv-qualifier conversions.
2006 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2007 return ToType.getUnqualifiedType();
2008
2009 QualType CanonFromPointee
2010 = Context.getCanonicalType(FromPtr->getPointeeType());
2011 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2012 Qualifiers Quals = CanonFromPointee.getQualifiers();
2013
2014 if (StripObjCLifetime)
2015 Quals.removeObjCLifetime();
2016
2017 // Exact qualifier match -> return the pointer type we're converting to.
2018 if (CanonToPointee.getLocalQualifiers() == Quals) {
2019 // ToType is exactly what we need. Return it.
2020 if (!ToType.isNull())
2021 return ToType.getUnqualifiedType();
2022
2023 // Build a pointer to ToPointee. It has the right qualifiers
2024 // already.
2025 if (isa<ObjCObjectPointerType>(ToType))
2026 return Context.getObjCObjectPointerType(ToPointee);
2027 return Context.getPointerType(ToPointee);
2028 }
2029
2030 // Just build a canonical type that has the right qualifiers.
2031 QualType QualifiedCanonToPointee
2032 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2033
2034 if (isa<ObjCObjectPointerType>(ToType))
2035 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2036 return Context.getPointerType(QualifiedCanonToPointee);
2037}
2038
2039static bool isNullPointerConstantForConversion(Expr *Expr,
2040 bool InOverloadResolution,
2041 ASTContext &Context) {
2042 // Handle value-dependent integral null pointer constants correctly.
2043 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2044 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2045 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2046 return !InOverloadResolution;
2047
2048 return Expr->isNullPointerConstant(Context,
2049 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2050 : Expr::NPC_ValueDependentIsNull);
2051}
2052
2053/// IsPointerConversion - Determines whether the conversion of the
2054/// expression From, which has the (possibly adjusted) type FromType,
2055/// can be converted to the type ToType via a pointer conversion (C++
2056/// 4.10). If so, returns true and places the converted type (that
2057/// might differ from ToType in its cv-qualifiers at some level) into
2058/// ConvertedType.
2059///
2060/// This routine also supports conversions to and from block pointers
2061/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2062/// pointers to interfaces. FIXME: Once we've determined the
2063/// appropriate overloading rules for Objective-C, we may want to
2064/// split the Objective-C checks into a different routine; however,
2065/// GCC seems to consider all of these conversions to be pointer
2066/// conversions, so for now they live here. IncompatibleObjC will be
2067/// set if the conversion is an allowed Objective-C conversion that
2068/// should result in a warning.
2069bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2070 bool InOverloadResolution,
2071 QualType& ConvertedType,
2072 bool &IncompatibleObjC) {
2073 IncompatibleObjC = false;
2074 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2075 IncompatibleObjC))
2076 return true;
2077
2078 // Conversion from a null pointer constant to any Objective-C pointer type.
2079 if (ToType->isObjCObjectPointerType() &&
2080 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2081 ConvertedType = ToType;
2082 return true;
2083 }
2084
2085 // Blocks: Block pointers can be converted to void*.
2086 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2087 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2088 ConvertedType = ToType;
2089 return true;
2090 }
2091 // Blocks: A null pointer constant can be converted to a block
2092 // pointer type.
2093 if (ToType->isBlockPointerType() &&
2094 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2095 ConvertedType = ToType;
2096 return true;
2097 }
2098
2099 // If the left-hand-side is nullptr_t, the right side can be a null
2100 // pointer constant.
2101 if (ToType->isNullPtrType() &&
2102 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2103 ConvertedType = ToType;
2104 return true;
2105 }
2106
2107 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2108 if (!ToTypePtr)
2109 return false;
2110
2111 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2112 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2113 ConvertedType = ToType;
2114 return true;
2115 }
2116
2117 // Beyond this point, both types need to be pointers
2118 // , including objective-c pointers.
2119 QualType ToPointeeType = ToTypePtr->getPointeeType();
2120 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2121 !getLangOpts().ObjCAutoRefCount) {
2122 ConvertedType = BuildSimilarlyQualifiedPointerType(
2123 FromType->getAs<ObjCObjectPointerType>(),
2124 ToPointeeType,
2125 ToType, Context);
2126 return true;
2127 }
2128 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2129 if (!FromTypePtr)
2130 return false;
2131
2132 QualType FromPointeeType = FromTypePtr->getPointeeType();
2133
2134 // If the unqualified pointee types are the same, this can't be a
2135 // pointer conversion, so don't do all of the work below.
2136 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2137 return false;
2138
2139 // An rvalue of type "pointer to cv T," where T is an object type,
2140 // can be converted to an rvalue of type "pointer to cv void" (C++
2141 // 4.10p2).
2142 if (FromPointeeType->isIncompleteOrObjectType() &&
2143 ToPointeeType->isVoidType()) {
2144 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2145 ToPointeeType,
2146 ToType, Context,
2147 /*StripObjCLifetime=*/true);
2148 return true;
2149 }
2150
2151 // MSVC allows implicit function to void* type conversion.
2152 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2153 ToPointeeType->isVoidType()) {
2154 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2155 ToPointeeType,
2156 ToType, Context);
2157 return true;
2158 }
2159
2160 // When we're overloading in C, we allow a special kind of pointer
2161 // conversion for compatible-but-not-identical pointee types.
2162 if (!getLangOpts().CPlusPlus &&
2163 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2164 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2165 ToPointeeType,
2166 ToType, Context);
2167 return true;
2168 }
2169
2170 // C++ [conv.ptr]p3:
2171 //
2172 // An rvalue of type "pointer to cv D," where D is a class type,
2173 // can be converted to an rvalue of type "pointer to cv B," where
2174 // B is a base class (clause 10) of D. If B is an inaccessible
2175 // (clause 11) or ambiguous (10.2) base class of D, a program that
2176 // necessitates this conversion is ill-formed. The result of the
2177 // conversion is a pointer to the base class sub-object of the
2178 // derived class object. The null pointer value is converted to
2179 // the null pointer value of the destination type.
2180 //
2181 // Note that we do not check for ambiguity or inaccessibility
2182 // here. That is handled by CheckPointerConversion.
2183 if (getLangOpts().CPlusPlus &&
2184 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2185 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2186 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2187 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2188 ToPointeeType,
2189 ToType, Context);
2190 return true;
2191 }
2192
2193 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2194 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2195 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2196 ToPointeeType,
2197 ToType, Context);
2198 return true;
2199 }
2200
2201 return false;
2202}
2203
2204/// \brief Adopt the given qualifiers for the given type.
2205static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2206 Qualifiers TQs = T.getQualifiers();
2207
2208 // Check whether qualifiers already match.
2209 if (TQs == Qs)
2210 return T;
2211
2212 if (Qs.compatiblyIncludes(TQs))
2213 return Context.getQualifiedType(T, Qs);
2214
2215 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2216}
2217
2218/// isObjCPointerConversion - Determines whether this is an
2219/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2220/// with the same arguments and return values.
2221bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2222 QualType& ConvertedType,
2223 bool &IncompatibleObjC) {
2224 if (!getLangOpts().ObjC1)
2225 return false;
2226
2227 // The set of qualifiers on the type we're converting from.
2228 Qualifiers FromQualifiers = FromType.getQualifiers();
2229
2230 // First, we handle all conversions on ObjC object pointer types.
2231 const ObjCObjectPointerType* ToObjCPtr =
2232 ToType->getAs<ObjCObjectPointerType>();
2233 const ObjCObjectPointerType *FromObjCPtr =
2234 FromType->getAs<ObjCObjectPointerType>();
2235
2236 if (ToObjCPtr && FromObjCPtr) {
2237 // If the pointee types are the same (ignoring qualifications),
2238 // then this is not a pointer conversion.
2239 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2240 FromObjCPtr->getPointeeType()))
2241 return false;
2242
2243 // Conversion between Objective-C pointers.
2244 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2245 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2246 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2247 if (getLangOpts().CPlusPlus && LHS && RHS &&
2248 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2249 FromObjCPtr->getPointeeType()))
2250 return false;
2251 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2252 ToObjCPtr->getPointeeType(),
2253 ToType, Context);
2254 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2255 return true;
2256 }
2257
2258 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2259 // Okay: this is some kind of implicit downcast of Objective-C
2260 // interfaces, which is permitted. However, we're going to
2261 // complain about it.
2262 IncompatibleObjC = true;
2263 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2264 ToObjCPtr->getPointeeType(),
2265 ToType, Context);
2266 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2267 return true;
2268 }
2269 }
2270 // Beyond this point, both types need to be C pointers or block pointers.
2271 QualType ToPointeeType;
2272 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2273 ToPointeeType = ToCPtr->getPointeeType();
2274 else if (const BlockPointerType *ToBlockPtr =
2275 ToType->getAs<BlockPointerType>()) {
2276 // Objective C++: We're able to convert from a pointer to any object
2277 // to a block pointer type.
2278 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2279 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2280 return true;
2281 }
2282 ToPointeeType = ToBlockPtr->getPointeeType();
2283 }
2284 else if (FromType->getAs<BlockPointerType>() &&
2285 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2286 // Objective C++: We're able to convert from a block pointer type to a
2287 // pointer to any object.
2288 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2289 return true;
2290 }
2291 else
2292 return false;
2293
2294 QualType FromPointeeType;
2295 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2296 FromPointeeType = FromCPtr->getPointeeType();
2297 else if (const BlockPointerType *FromBlockPtr =
2298 FromType->getAs<BlockPointerType>())
2299 FromPointeeType = FromBlockPtr->getPointeeType();
2300 else
2301 return false;
2302
2303 // If we have pointers to pointers, recursively check whether this
2304 // is an Objective-C conversion.
2305 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2306 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2307 IncompatibleObjC)) {
2308 // We always complain about this conversion.
2309 IncompatibleObjC = true;
2310 ConvertedType = Context.getPointerType(ConvertedType);
2311 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2312 return true;
2313 }
2314 // Allow conversion of pointee being objective-c pointer to another one;
2315 // as in I* to id.
2316 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2317 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2318 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2319 IncompatibleObjC)) {
2320
2321 ConvertedType = Context.getPointerType(ConvertedType);
2322 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2323 return true;
2324 }
2325
2326 // If we have pointers to functions or blocks, check whether the only
2327 // differences in the argument and result types are in Objective-C
2328 // pointer conversions. If so, we permit the conversion (but
2329 // complain about it).
2330 const FunctionProtoType *FromFunctionType
2331 = FromPointeeType->getAs<FunctionProtoType>();
2332 const FunctionProtoType *ToFunctionType
2333 = ToPointeeType->getAs<FunctionProtoType>();
2334 if (FromFunctionType && ToFunctionType) {
2335 // If the function types are exactly the same, this isn't an
2336 // Objective-C pointer conversion.
2337 if (Context.getCanonicalType(FromPointeeType)
2338 == Context.getCanonicalType(ToPointeeType))
2339 return false;
2340
2341 // Perform the quick checks that will tell us whether these
2342 // function types are obviously different.
2343 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2344 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2345 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2346 return false;
2347
2348 bool HasObjCConversion = false;
2349 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2350 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2351 // Okay, the types match exactly. Nothing to do.
2352 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2353 ToFunctionType->getReturnType(),
2354 ConvertedType, IncompatibleObjC)) {
2355 // Okay, we have an Objective-C pointer conversion.
2356 HasObjCConversion = true;
2357 } else {
2358 // Function types are too different. Abort.
2359 return false;
2360 }
2361
2362 // Check argument types.
2363 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2364 ArgIdx != NumArgs; ++ArgIdx) {
2365 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2366 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2367 if (Context.getCanonicalType(FromArgType)
2368 == Context.getCanonicalType(ToArgType)) {
2369 // Okay, the types match exactly. Nothing to do.
2370 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2371 ConvertedType, IncompatibleObjC)) {
2372 // Okay, we have an Objective-C pointer conversion.
2373 HasObjCConversion = true;
2374 } else {
2375 // Argument types are too different. Abort.
2376 return false;
2377 }
2378 }
2379
2380 if (HasObjCConversion) {
2381 // We had an Objective-C conversion. Allow this pointer
2382 // conversion, but complain about it.
2383 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2384 IncompatibleObjC = true;
2385 return true;
2386 }
2387 }
2388
2389 return false;
2390}
2391
2392/// \brief Determine whether this is an Objective-C writeback conversion,
2393/// used for parameter passing when performing automatic reference counting.
2394///
2395/// \param FromType The type we're converting form.
2396///
2397/// \param ToType The type we're converting to.
2398///
2399/// \param ConvertedType The type that will be produced after applying
2400/// this conversion.
2401bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2402 QualType &ConvertedType) {
2403 if (!getLangOpts().ObjCAutoRefCount ||
2404 Context.hasSameUnqualifiedType(FromType, ToType))
2405 return false;
2406
2407 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2408 QualType ToPointee;
2409 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2410 ToPointee = ToPointer->getPointeeType();
2411 else
2412 return false;
2413
2414 Qualifiers ToQuals = ToPointee.getQualifiers();
2415 if (!ToPointee->isObjCLifetimeType() ||
2416 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2417 !ToQuals.withoutObjCLifetime().empty())
2418 return false;
2419
2420 // Argument must be a pointer to __strong to __weak.
2421 QualType FromPointee;
2422 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2423 FromPointee = FromPointer->getPointeeType();
2424 else
2425 return false;
2426
2427 Qualifiers FromQuals = FromPointee.getQualifiers();
2428 if (!FromPointee->isObjCLifetimeType() ||
2429 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2430 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2431 return false;
2432
2433 // Make sure that we have compatible qualifiers.
2434 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2435 if (!ToQuals.compatiblyIncludes(FromQuals))
2436 return false;
2437
2438 // Remove qualifiers from the pointee type we're converting from; they
2439 // aren't used in the compatibility check belong, and we'll be adding back
2440 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2441 FromPointee = FromPointee.getUnqualifiedType();
2442
2443 // The unqualified form of the pointee types must be compatible.
2444 ToPointee = ToPointee.getUnqualifiedType();
2445 bool IncompatibleObjC;
2446 if (Context.typesAreCompatible(FromPointee, ToPointee))
2447 FromPointee = ToPointee;
2448 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2449 IncompatibleObjC))
2450 return false;
2451
2452 /// \brief Construct the type we're converting to, which is a pointer to
2453 /// __autoreleasing pointee.
2454 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2455 ConvertedType = Context.getPointerType(FromPointee);
2456 return true;
2457}
2458
2459bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2460 QualType& ConvertedType) {
2461 QualType ToPointeeType;
2462 if (const BlockPointerType *ToBlockPtr =
2463 ToType->getAs<BlockPointerType>())
2464 ToPointeeType = ToBlockPtr->getPointeeType();
2465 else
2466 return false;
2467
2468 QualType FromPointeeType;
2469 if (const BlockPointerType *FromBlockPtr =
2470 FromType->getAs<BlockPointerType>())
2471 FromPointeeType = FromBlockPtr->getPointeeType();
2472 else
2473 return false;
2474 // We have pointer to blocks, check whether the only
2475 // differences in the argument and result types are in Objective-C
2476 // pointer conversions. If so, we permit the conversion.
2477
2478 const FunctionProtoType *FromFunctionType
2479 = FromPointeeType->getAs<FunctionProtoType>();
2480 const FunctionProtoType *ToFunctionType
2481 = ToPointeeType->getAs<FunctionProtoType>();
2482
2483 if (!FromFunctionType || !ToFunctionType)
2484 return false;
2485
2486 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2487 return true;
2488
2489 // Perform the quick checks that will tell us whether these
2490 // function types are obviously different.
2491 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2492 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2493 return false;
2494
2495 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2496 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2497 if (FromEInfo != ToEInfo)
2498 return false;
2499
2500 bool IncompatibleObjC = false;
2501 if (Context.hasSameType(FromFunctionType->getReturnType(),
2502 ToFunctionType->getReturnType())) {
2503 // Okay, the types match exactly. Nothing to do.
2504 } else {
2505 QualType RHS = FromFunctionType->getReturnType();
2506 QualType LHS = ToFunctionType->getReturnType();
2507 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2508 !RHS.hasQualifiers() && LHS.hasQualifiers())
2509 LHS = LHS.getUnqualifiedType();
2510
2511 if (Context.hasSameType(RHS,LHS)) {
2512 // OK exact match.
2513 } else if (isObjCPointerConversion(RHS, LHS,
2514 ConvertedType, IncompatibleObjC)) {
2515 if (IncompatibleObjC)
2516 return false;
2517 // Okay, we have an Objective-C pointer conversion.
2518 }
2519 else
2520 return false;
2521 }
2522
2523 // Check argument types.
2524 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2525 ArgIdx != NumArgs; ++ArgIdx) {
2526 IncompatibleObjC = false;
2527 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2528 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2529 if (Context.hasSameType(FromArgType, ToArgType)) {
2530 // Okay, the types match exactly. Nothing to do.
2531 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2532 ConvertedType, IncompatibleObjC)) {
2533 if (IncompatibleObjC)
2534 return false;
2535 // Okay, we have an Objective-C pointer conversion.
2536 } else
2537 // Argument types are too different. Abort.
2538 return false;
2539 }
2540 if (LangOpts.ObjCAutoRefCount &&
2541 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2542 ToFunctionType))
2543 return false;
2544
2545 ConvertedType = ToType;
2546 return true;
2547}
2548
2549enum {
2550 ft_default,
2551 ft_different_class,
2552 ft_parameter_arity,
2553 ft_parameter_mismatch,
2554 ft_return_type,
2555 ft_qualifer_mismatch
2556};
2557
2558/// Attempts to get the FunctionProtoType from a Type. Handles
2559/// MemberFunctionPointers properly.
2560static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2561 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2562 return FPT;
2563
2564 if (auto *MPT = FromType->getAs<MemberPointerType>())
2565 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2566
2567 return nullptr;
2568}
2569
2570/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2571/// function types. Catches different number of parameter, mismatch in
2572/// parameter types, and different return types.
2573void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2574 QualType FromType, QualType ToType) {
2575 // If either type is not valid, include no extra info.
2576 if (FromType.isNull() || ToType.isNull()) {
2577 PDiag << ft_default;
2578 return;
2579 }
2580
2581 // Get the function type from the pointers.
2582 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2583 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2584 *ToMember = ToType->getAs<MemberPointerType>();
2585 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2586 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2587 << QualType(FromMember->getClass(), 0);
2588 return;
2589 }
2590 FromType = FromMember->getPointeeType();
2591 ToType = ToMember->getPointeeType();
2592 }
2593
2594 if (FromType->isPointerType())
2595 FromType = FromType->getPointeeType();
2596 if (ToType->isPointerType())
2597 ToType = ToType->getPointeeType();
2598
2599 // Remove references.
2600 FromType = FromType.getNonReferenceType();
2601 ToType = ToType.getNonReferenceType();
2602
2603 // Don't print extra info for non-specialized template functions.
2604 if (FromType->isInstantiationDependentType() &&
2605 !FromType->getAs<TemplateSpecializationType>()) {
2606 PDiag << ft_default;
2607 return;
2608 }
2609
2610 // No extra info for same types.
2611 if (Context.hasSameType(FromType, ToType)) {
2612 PDiag << ft_default;
2613 return;
2614 }
2615
2616 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2617 *ToFunction = tryGetFunctionProtoType(ToType);
2618
2619 // Both types need to be function types.
2620 if (!FromFunction || !ToFunction) {
2621 PDiag << ft_default;
2622 return;
2623 }
2624
2625 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2626 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2627 << FromFunction->getNumParams();
2628 return;
2629 }
2630
2631 // Handle different parameter types.
2632 unsigned ArgPos;
2633 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2634 PDiag << ft_parameter_mismatch << ArgPos + 1
2635 << ToFunction->getParamType(ArgPos)
2636 << FromFunction->getParamType(ArgPos);
2637 return;
2638 }
2639
2640 // Handle different return type.
2641 if (!Context.hasSameType(FromFunction->getReturnType(),
2642 ToFunction->getReturnType())) {
2643 PDiag << ft_return_type << ToFunction->getReturnType()
2644 << FromFunction->getReturnType();
2645 return;
2646 }
2647
2648 unsigned FromQuals = FromFunction->getTypeQuals(),
2649 ToQuals = ToFunction->getTypeQuals();
2650 if (FromQuals != ToQuals) {
2651 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2652 return;
2653 }
2654
2655 // Unable to find a difference, so add no extra info.
2656 PDiag << ft_default;
2657}
2658
2659/// FunctionParamTypesAreEqual - This routine checks two function proto types
2660/// for equality of their argument types. Caller has already checked that
2661/// they have same number of arguments. If the parameters are different,
2662/// ArgPos will have the parameter index of the first different parameter.
2663bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2664 const FunctionProtoType *NewType,
2665 unsigned *ArgPos) {
2666 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2667 N = NewType->param_type_begin(),
2668 E = OldType->param_type_end();
2669 O && (O != E); ++O, ++N) {
2670 if (!Context.hasSameType(O->getUnqualifiedType(),
2671 N->getUnqualifiedType())) {
2672 if (ArgPos)
2673 *ArgPos = O - OldType->param_type_begin();
2674 return false;
2675 }
2676 }
2677 return true;
2678}
2679
2680/// CheckPointerConversion - Check the pointer conversion from the
2681/// expression From to the type ToType. This routine checks for
2682/// ambiguous or inaccessible derived-to-base pointer
2683/// conversions for which IsPointerConversion has already returned
2684/// true. It returns true and produces a diagnostic if there was an
2685/// error, or returns false otherwise.
2686bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2687 CastKind &Kind,
2688 CXXCastPath& BasePath,
2689 bool IgnoreBaseAccess) {
2690 QualType FromType = From->getType();
2691 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2692
2693 Kind = CK_BitCast;
2694
2695 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2696 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2697 Expr::NPCK_ZeroExpression) {
2698 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2699 DiagRuntimeBehavior(From->getExprLoc(), From,
2700 PDiag(diag::warn_impcast_bool_to_null_pointer)
2701 << ToType << From->getSourceRange());
2702 else if (!isUnevaluatedContext())
2703 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2704 << ToType << From->getSourceRange();
2705 }
2706 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2707 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2708 QualType FromPointeeType = FromPtrType->getPointeeType(),
2709 ToPointeeType = ToPtrType->getPointeeType();
2710
2711 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2712 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2713 // We must have a derived-to-base conversion. Check an
2714 // ambiguous or inaccessible conversion.
2715 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2716 From->getExprLoc(),
2717 From->getSourceRange(), &BasePath,
2718 IgnoreBaseAccess))
2719 return true;
2720
2721 // The conversion was successful.
2722 Kind = CK_DerivedToBase;
2723 }
2724
2725 if (!IsCStyleOrFunctionalCast && FromPointeeType->isFunctionType() &&
2726 ToPointeeType->isVoidType()) {
2727 assert(getLangOpts().MSVCCompat &&((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2728, __PRETTY_FUNCTION__))
2728 "this should only be possible with MSVCCompat!")((getLangOpts().MSVCCompat && "this should only be possible with MSVCCompat!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"this should only be possible with MSVCCompat!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2728, __PRETTY_FUNCTION__))
;
2729 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2730 << From->getSourceRange();
2731 }
2732 }
2733 } else if (const ObjCObjectPointerType *ToPtrType =
2734 ToType->getAs<ObjCObjectPointerType>()) {
2735 if (const ObjCObjectPointerType *FromPtrType =
2736 FromType->getAs<ObjCObjectPointerType>()) {
2737 // Objective-C++ conversions are always okay.
2738 // FIXME: We should have a different class of conversions for the
2739 // Objective-C++ implicit conversions.
2740 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2741 return false;
2742 } else if (FromType->isBlockPointerType()) {
2743 Kind = CK_BlockPointerToObjCPointerCast;
2744 } else {
2745 Kind = CK_CPointerToObjCPointerCast;
2746 }
2747 } else if (ToType->isBlockPointerType()) {
2748 if (!FromType->isBlockPointerType())
2749 Kind = CK_AnyPointerToBlockPointerCast;
2750 }
2751
2752 // We shouldn't fall into this case unless it's valid for other
2753 // reasons.
2754 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2755 Kind = CK_NullToPointer;
2756
2757 return false;
2758}
2759
2760/// IsMemberPointerConversion - Determines whether the conversion of the
2761/// expression From, which has the (possibly adjusted) type FromType, can be
2762/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2763/// If so, returns true and places the converted type (that might differ from
2764/// ToType in its cv-qualifiers at some level) into ConvertedType.
2765bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2766 QualType ToType,
2767 bool InOverloadResolution,
2768 QualType &ConvertedType) {
2769 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2770 if (!ToTypePtr)
2771 return false;
2772
2773 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2774 if (From->isNullPointerConstant(Context,
2775 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2776 : Expr::NPC_ValueDependentIsNull)) {
2777 ConvertedType = ToType;
2778 return true;
2779 }
2780
2781 // Otherwise, both types have to be member pointers.
2782 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2783 if (!FromTypePtr)
2784 return false;
2785
2786 // A pointer to member of B can be converted to a pointer to member of D,
2787 // where D is derived from B (C++ 4.11p2).
2788 QualType FromClass(FromTypePtr->getClass(), 0);
2789 QualType ToClass(ToTypePtr->getClass(), 0);
2790
2791 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2792 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2793 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2794 ToClass.getTypePtr());
2795 return true;
2796 }
2797
2798 return false;
2799}
2800
2801/// CheckMemberPointerConversion - Check the member pointer conversion from the
2802/// expression From to the type ToType. This routine checks for ambiguous or
2803/// virtual or inaccessible base-to-derived member pointer conversions
2804/// for which IsMemberPointerConversion has already returned true. It returns
2805/// true and produces a diagnostic if there was an error, or returns false
2806/// otherwise.
2807bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2808 CastKind &Kind,
2809 CXXCastPath &BasePath,
2810 bool IgnoreBaseAccess) {
2811 QualType FromType = From->getType();
2812 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2813 if (!FromPtrType) {
2814 // This must be a null pointer to member pointer conversion
2815 assert(From->isNullPointerConstant(Context,((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2817, __PRETTY_FUNCTION__))
2816 Expr::NPC_ValueDependentIsNull) &&((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2817, __PRETTY_FUNCTION__))
2817 "Expr must be null pointer constant!")((From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull
) && "Expr must be null pointer constant!") ? static_cast
<void> (0) : __assert_fail ("From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull) && \"Expr must be null pointer constant!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2817, __PRETTY_FUNCTION__))
;
2818 Kind = CK_NullToMemberPointer;
2819 return false;
2820 }
2821
2822 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2823 assert(ToPtrType && "No member pointer cast has a target type "((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2824, __PRETTY_FUNCTION__))
2824 "that is not a member pointer.")((ToPtrType && "No member pointer cast has a target type "
"that is not a member pointer.") ? static_cast<void> (
0) : __assert_fail ("ToPtrType && \"No member pointer cast has a target type \" \"that is not a member pointer.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2824, __PRETTY_FUNCTION__))
;
2825
2826 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2827 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2828
2829 // FIXME: What about dependent types?
2830 assert(FromClass->isRecordType() && "Pointer into non-class.")((FromClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("FromClass->isRecordType() && \"Pointer into non-class.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2830, __PRETTY_FUNCTION__))
;
2831 assert(ToClass->isRecordType() && "Pointer into non-class.")((ToClass->isRecordType() && "Pointer into non-class."
) ? static_cast<void> (0) : __assert_fail ("ToClass->isRecordType() && \"Pointer into non-class.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2831, __PRETTY_FUNCTION__))
;
2832
2833 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2834 /*DetectVirtual=*/true);
2835 bool DerivationOkay =
2836 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2837 assert(DerivationOkay &&((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2838, __PRETTY_FUNCTION__))
2838 "Should not have been called if derivation isn't OK.")((DerivationOkay && "Should not have been called if derivation isn't OK."
) ? static_cast<void> (0) : __assert_fail ("DerivationOkay && \"Should not have been called if derivation isn't OK.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 2838, __PRETTY_FUNCTION__))
;
2839 (void)DerivationOkay;
2840
2841 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2842 getUnqualifiedType())) {
2843 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2844 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2845 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2846 return true;
2847 }
2848
2849 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2850 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2851 << FromClass << ToClass << QualType(VBase, 0)
2852 << From->getSourceRange();
2853 return true;
2854 }
2855
2856 if (!IgnoreBaseAccess)
2857 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2858 Paths.front(),
2859 diag::err_downcast_from_inaccessible_base);
2860
2861 // Must be a base to derived member conversion.
2862 BuildBasePathArray(Paths, BasePath);
2863 Kind = CK_BaseToDerivedMemberPointer;
2864 return false;
2865}
2866
2867/// Determine whether the lifetime conversion between the two given
2868/// qualifiers sets is nontrivial.
2869static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2870 Qualifiers ToQuals) {
2871 // Converting anything to const __unsafe_unretained is trivial.
2872 if (ToQuals.hasConst() &&
2873 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2874 return false;
2875
2876 return true;
2877}
2878
2879/// IsQualificationConversion - Determines whether the conversion from
2880/// an rvalue of type FromType to ToType is a qualification conversion
2881/// (C++ 4.4).
2882///
2883/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2884/// when the qualification conversion involves a change in the Objective-C
2885/// object lifetime.
2886bool
2887Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2888 bool CStyle, bool &ObjCLifetimeConversion) {
2889 FromType = Context.getCanonicalType(FromType);
2890 ToType = Context.getCanonicalType(ToType);
2891 ObjCLifetimeConversion = false;
2892
2893 // If FromType and ToType are the same type, this is not a
2894 // qualification conversion.
2895 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2896 return false;
2897
2898 // (C++ 4.4p4):
2899 // A conversion can add cv-qualifiers at levels other than the first
2900 // in multi-level pointers, subject to the following rules: [...]
2901 bool PreviousToQualsIncludeConst = true;
2902 bool UnwrappedAnyPointer = false;
2903 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2904 // Within each iteration of the loop, we check the qualifiers to
2905 // determine if this still looks like a qualification
2906 // conversion. Then, if all is well, we unwrap one more level of
2907 // pointers or pointers-to-members and do it all again
2908 // until there are no more pointers or pointers-to-members left to
2909 // unwrap.
2910 UnwrappedAnyPointer = true;
2911
2912 Qualifiers FromQuals = FromType.getQualifiers();
2913 Qualifiers ToQuals = ToType.getQualifiers();
2914
2915 // Objective-C ARC:
2916 // Check Objective-C lifetime conversions.
2917 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2918 UnwrappedAnyPointer) {
2919 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2920 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2921 ObjCLifetimeConversion = true;
2922 FromQuals.removeObjCLifetime();
2923 ToQuals.removeObjCLifetime();
2924 } else {
2925 // Qualification conversions cannot cast between different
2926 // Objective-C lifetime qualifiers.
2927 return false;
2928 }
2929 }
2930
2931 // Allow addition/removal of GC attributes but not changing GC attributes.
2932 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2933 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2934 FromQuals.removeObjCGCAttr();
2935 ToQuals.removeObjCGCAttr();
2936 }
2937
2938 // -- for every j > 0, if const is in cv 1,j then const is in cv
2939 // 2,j, and similarly for volatile.
2940 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2941 return false;
2942
2943 // -- if the cv 1,j and cv 2,j are different, then const is in
2944 // every cv for 0 < k < j.
2945 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2946 && !PreviousToQualsIncludeConst)
2947 return false;
2948
2949 // Keep track of whether all prior cv-qualifiers in the "to" type
2950 // include const.
2951 PreviousToQualsIncludeConst
2952 = PreviousToQualsIncludeConst && ToQuals.hasConst();
2953 }
2954
2955 // We are left with FromType and ToType being the pointee types
2956 // after unwrapping the original FromType and ToType the same number
2957 // of types. If we unwrapped any pointers, and if FromType and
2958 // ToType have the same unqualified type (since we checked
2959 // qualifiers above), then this is a qualification conversion.
2960 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2961}
2962
2963/// \brief - Determine whether this is a conversion from a scalar type to an
2964/// atomic type.
2965///
2966/// If successful, updates \c SCS's second and third steps in the conversion
2967/// sequence to finish the conversion.
2968static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2969 bool InOverloadResolution,
2970 StandardConversionSequence &SCS,
2971 bool CStyle) {
2972 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2973 if (!ToAtomic)
2974 return false;
2975
2976 StandardConversionSequence InnerSCS;
2977 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2978 InOverloadResolution, InnerSCS,
2979 CStyle, /*AllowObjCWritebackConversion=*/false))
2980 return false;
2981
2982 SCS.Second = InnerSCS.Second;
2983 SCS.setToType(1, InnerSCS.getToType(1));
2984 SCS.Third = InnerSCS.Third;
2985 SCS.QualificationIncludesObjCLifetime
2986 = InnerSCS.QualificationIncludesObjCLifetime;
2987 SCS.setToType(2, InnerSCS.getToType(2));
2988 return true;
2989}
2990
2991static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2992 CXXConstructorDecl *Constructor,
2993 QualType Type) {
2994 const FunctionProtoType *CtorType =
2995 Constructor->getType()->getAs<FunctionProtoType>();
2996 if (CtorType->getNumParams() > 0) {
2997 QualType FirstArg = CtorType->getParamType(0);
2998 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2999 return true;
3000 }
3001 return false;
3002}
3003
3004static OverloadingResult
3005IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3006 CXXRecordDecl *To,
3007 UserDefinedConversionSequence &User,
3008 OverloadCandidateSet &CandidateSet,
3009 bool AllowExplicit) {
3010 DeclContext::lookup_result R = S.LookupConstructors(To);
3011 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3012 Con != ConEnd; ++Con) {
3013 NamedDecl *D = *Con;
3014 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3015
3016 // Find the constructor (which may be a template).
3017 CXXConstructorDecl *Constructor = nullptr;
3018 FunctionTemplateDecl *ConstructorTmpl
3019 = dyn_cast<FunctionTemplateDecl>(D);
3020 if (ConstructorTmpl)
3021 Constructor
3022 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3023 else
3024 Constructor = cast<CXXConstructorDecl>(D);
3025
3026 bool Usable = !Constructor->isInvalidDecl() &&
3027 S.isInitListConstructor(Constructor) &&
3028 (AllowExplicit || !Constructor->isExplicit());
3029 if (Usable) {
3030 // If the first argument is (a reference to) the target type,
3031 // suppress conversions.
3032 bool SuppressUserConversions =
3033 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
3034 if (ConstructorTmpl)
3035 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3036 /*ExplicitArgs*/ nullptr,
3037 From, CandidateSet,
3038 SuppressUserConversions);
3039 else
3040 S.AddOverloadCandidate(Constructor, FoundDecl,
3041 From, CandidateSet,
3042 SuppressUserConversions);
3043 }
3044 }
3045
3046 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3047
3048 OverloadCandidateSet::iterator Best;
3049 switch (auto Result =
3050 CandidateSet.BestViableFunction(S, From->getLocStart(),
3051 Best, true)) {
3052 case OR_Deleted:
3053 case OR_Success: {
3054 // Record the standard conversion we used and the conversion function.
3055 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3056 QualType ThisType = Constructor->getThisType(S.Context);
3057 // Initializer lists don't have conversions as such.
3058 User.Before.setAsIdentityConversion();
3059 User.HadMultipleCandidates = HadMultipleCandidates;
3060 User.ConversionFunction = Constructor;
3061 User.FoundConversionFunction = Best->FoundDecl;
3062 User.After.setAsIdentityConversion();
3063 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3064 User.After.setAllToTypes(ToType);
3065 return Result;
3066 }
3067
3068 case OR_No_Viable_Function:
3069 return OR_No_Viable_Function;
3070 case OR_Ambiguous:
3071 return OR_Ambiguous;
3072 }
3073
3074 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3074)
;
3075}
3076
3077/// Determines whether there is a user-defined conversion sequence
3078/// (C++ [over.ics.user]) that converts expression From to the type
3079/// ToType. If such a conversion exists, User will contain the
3080/// user-defined conversion sequence that performs such a conversion
3081/// and this routine will return true. Otherwise, this routine returns
3082/// false and User is unspecified.
3083///
3084/// \param AllowExplicit true if the conversion should consider C++0x
3085/// "explicit" conversion functions as well as non-explicit conversion
3086/// functions (C++0x [class.conv.fct]p2).
3087///
3088/// \param AllowObjCConversionOnExplicit true if the conversion should
3089/// allow an extra Objective-C pointer conversion on uses of explicit
3090/// constructors. Requires \c AllowExplicit to also be set.
3091static OverloadingResult
3092IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3093 UserDefinedConversionSequence &User,
3094 OverloadCandidateSet &CandidateSet,
3095 bool AllowExplicit,
3096 bool AllowObjCConversionOnExplicit) {
3097 assert(AllowExplicit || !AllowObjCConversionOnExplicit)((AllowExplicit || !AllowObjCConversionOnExplicit) ? static_cast
<void> (0) : __assert_fail ("AllowExplicit || !AllowObjCConversionOnExplicit"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3097, __PRETTY_FUNCTION__))
;
3098
3099 // Whether we will only visit constructors.
3100 bool ConstructorsOnly = false;
3101
3102 // If the type we are conversion to is a class type, enumerate its
3103 // constructors.
3104 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3105 // C++ [over.match.ctor]p1:
3106 // When objects of class type are direct-initialized (8.5), or
3107 // copy-initialized from an expression of the same or a
3108 // derived class type (8.5), overload resolution selects the
3109 // constructor. [...] For copy-initialization, the candidate
3110 // functions are all the converting constructors (12.3.1) of
3111 // that class. The argument list is the expression-list within
3112 // the parentheses of the initializer.
3113 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3114 (From->getType()->getAs<RecordType>() &&
3115 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3116 ConstructorsOnly = true;
3117
3118 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3119 // We're not going to find any constructors.
3120 } else if (CXXRecordDecl *ToRecordDecl
3121 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3122
3123 Expr **Args = &From;
3124 unsigned NumArgs = 1;
3125 bool ListInitializing = false;
3126 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3127 // But first, see if there is an init-list-constructor that will work.
3128 OverloadingResult Result = IsInitializerListConstructorConversion(
3129 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3130 if (Result != OR_No_Viable_Function)
3131 return Result;
3132 // Never mind.
3133 CandidateSet.clear();
3134
3135 // If we're list-initializing, we pass the individual elements as
3136 // arguments, not the entire list.
3137 Args = InitList->getInits();
3138 NumArgs = InitList->getNumInits();
3139 ListInitializing = true;
3140 }
3141
3142 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3143 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3144 Con != ConEnd; ++Con) {
3145 NamedDecl *D = *Con;
3146 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3147
3148 // Find the constructor (which may be a template).
3149 CXXConstructorDecl *Constructor = nullptr;
3150 FunctionTemplateDecl *ConstructorTmpl
3151 = dyn_cast<FunctionTemplateDecl>(D);
3152 if (ConstructorTmpl)
3153 Constructor
3154 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3155 else
3156 Constructor = cast<CXXConstructorDecl>(D);
3157
3158 bool Usable = !Constructor->isInvalidDecl();
3159 if (ListInitializing)
3160 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3161 else
3162 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3163 if (Usable) {
3164 bool SuppressUserConversions = !ConstructorsOnly;
3165 if (SuppressUserConversions && ListInitializing) {
3166 SuppressUserConversions = false;
3167 if (NumArgs == 1) {
3168 // If the first argument is (a reference to) the target type,
3169 // suppress conversions.
3170 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3171 S.Context, Constructor, ToType);
3172 }
3173 }
3174 if (ConstructorTmpl)
3175 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3176 /*ExplicitArgs*/ nullptr,
3177 llvm::makeArrayRef(Args, NumArgs),
3178 CandidateSet, SuppressUserConversions);
3179 else
3180 // Allow one user-defined conversion when user specifies a
3181 // From->ToType conversion via an static cast (c-style, etc).
3182 S.AddOverloadCandidate(Constructor, FoundDecl,
3183 llvm::makeArrayRef(Args, NumArgs),
3184 CandidateSet, SuppressUserConversions);
3185 }
3186 }
3187 }
3188 }
3189
3190 // Enumerate conversion functions, if we're allowed to.
3191 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3192 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3193 // No conversion functions from incomplete types.
3194 } else if (const RecordType *FromRecordType
3195 = From->getType()->getAs<RecordType>()) {
3196 if (CXXRecordDecl *FromRecordDecl
3197 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3198 // Add all of the conversion functions as candidates.
3199 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3200 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3201 DeclAccessPair FoundDecl = I.getPair();
3202 NamedDecl *D = FoundDecl.getDecl();
3203 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3204 if (isa<UsingShadowDecl>(D))
3205 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3206
3207 CXXConversionDecl *Conv;
3208 FunctionTemplateDecl *ConvTemplate;
3209 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3210 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3211 else
3212 Conv = cast<CXXConversionDecl>(D);
3213
3214 if (AllowExplicit || !Conv->isExplicit()) {
3215 if (ConvTemplate)
3216 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3217 ActingContext, From, ToType,
3218 CandidateSet,
3219 AllowObjCConversionOnExplicit);
3220 else
3221 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3222 From, ToType, CandidateSet,
3223 AllowObjCConversionOnExplicit);
3224 }
3225 }
3226 }
3227 }
3228
3229 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3230
3231 OverloadCandidateSet::iterator Best;
3232 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3233 Best, true)) {
3234 case OR_Success:
3235 case OR_Deleted:
3236 // Record the standard conversion we used and the conversion function.
3237 if (CXXConstructorDecl *Constructor
3238 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3239 // C++ [over.ics.user]p1:
3240 // If the user-defined conversion is specified by a
3241 // constructor (12.3.1), the initial standard conversion
3242 // sequence converts the source type to the type required by
3243 // the argument of the constructor.
3244 //
3245 QualType ThisType = Constructor->getThisType(S.Context);
3246 if (isa<InitListExpr>(From)) {
3247 // Initializer lists don't have conversions as such.
3248 User.Before.setAsIdentityConversion();
3249 } else {
3250 if (Best->Conversions[0].isEllipsis())
3251 User.EllipsisConversion = true;
3252 else {
3253 User.Before = Best->Conversions[0].Standard;
3254 User.EllipsisConversion = false;
3255 }
3256 }
3257 User.HadMultipleCandidates = HadMultipleCandidates;
3258 User.ConversionFunction = Constructor;
3259 User.FoundConversionFunction = Best->FoundDecl;
3260 User.After.setAsIdentityConversion();
3261 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3262 User.After.setAllToTypes(ToType);
3263 return Result;
3264 }
3265 if (CXXConversionDecl *Conversion
3266 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3267 // C++ [over.ics.user]p1:
3268 //
3269 // [...] If the user-defined conversion is specified by a
3270 // conversion function (12.3.2), the initial standard
3271 // conversion sequence converts the source type to the
3272 // implicit object parameter of the conversion function.
3273 User.Before = Best->Conversions[0].Standard;
3274 User.HadMultipleCandidates = HadMultipleCandidates;
3275 User.ConversionFunction = Conversion;
3276 User.FoundConversionFunction = Best->FoundDecl;
3277 User.EllipsisConversion = false;
3278
3279 // C++ [over.ics.user]p2:
3280 // The second standard conversion sequence converts the
3281 // result of the user-defined conversion to the target type
3282 // for the sequence. Since an implicit conversion sequence
3283 // is an initialization, the special rules for
3284 // initialization by user-defined conversion apply when
3285 // selecting the best user-defined conversion for a
3286 // user-defined conversion sequence (see 13.3.3 and
3287 // 13.3.3.1).
3288 User.After = Best->FinalConversion;
3289 return Result;
3290 }
3291 llvm_unreachable("Not a constructor or conversion function?")::llvm::llvm_unreachable_internal("Not a constructor or conversion function?"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3291)
;
3292
3293 case OR_No_Viable_Function:
3294 return OR_No_Viable_Function;
3295
3296 case OR_Ambiguous:
3297 return OR_Ambiguous;
3298 }
3299
3300 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 3300)
;
3301}
3302
3303bool
3304Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3305 ImplicitConversionSequence ICS;
3306 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3307 OverloadCandidateSet::CSK_Normal);
3308 OverloadingResult OvResult =
3309 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3310 CandidateSet, false, false);
3311 if (OvResult == OR_Ambiguous)
3312 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3313 << From->getType() << ToType << From->getSourceRange();
3314 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3315 if (!RequireCompleteType(From->getLocStart(), ToType,
3316 diag::err_typecheck_nonviable_condition_incomplete,
3317 From->getType(), From->getSourceRange()))
3318 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3319 << false << From->getType() << From->getSourceRange() << ToType;
3320 } else
3321 return false;
3322 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3323 return true;
3324}
3325
3326/// \brief Compare the user-defined conversion functions or constructors
3327/// of two user-defined conversion sequences to determine whether any ordering
3328/// is possible.
3329static ImplicitConversionSequence::CompareKind
3330compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3331 FunctionDecl *Function2) {
3332 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3333 return ImplicitConversionSequence::Indistinguishable;
3334
3335 // Objective-C++:
3336 // If both conversion functions are implicitly-declared conversions from
3337 // a lambda closure type to a function pointer and a block pointer,
3338 // respectively, always prefer the conversion to a function pointer,
3339 // because the function pointer is more lightweight and is more likely
3340 // to keep code working.
3341 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3342 if (!Conv1)
3343 return ImplicitConversionSequence::Indistinguishable;
3344
3345 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3346 if (!Conv2)
3347 return ImplicitConversionSequence::Indistinguishable;
3348
3349 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3350 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3351 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3352 if (Block1 != Block2)
3353 return Block1 ? ImplicitConversionSequence::Worse
3354 : ImplicitConversionSequence::Better;
3355 }
3356
3357 return ImplicitConversionSequence::Indistinguishable;
3358}
3359
3360static bool hasDeprecatedStringLiteralToCharPtrConversion(
3361 const ImplicitConversionSequence &ICS) {
3362 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3363 (ICS.isUserDefined() &&
3364 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3365}
3366
3367/// CompareImplicitConversionSequences - Compare two implicit
3368/// conversion sequences to determine whether one is better than the
3369/// other or if they are indistinguishable (C++ 13.3.3.2).
3370static ImplicitConversionSequence::CompareKind
3371CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3372 const ImplicitConversionSequence& ICS1,
3373 const ImplicitConversionSequence& ICS2)
3374{
3375 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3376 // conversion sequences (as defined in 13.3.3.1)
3377 // -- a standard conversion sequence (13.3.3.1.1) is a better
3378 // conversion sequence than a user-defined conversion sequence or
3379 // an ellipsis conversion sequence, and
3380 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3381 // conversion sequence than an ellipsis conversion sequence
3382 // (13.3.3.1.3).
3383 //
3384 // C++0x [over.best.ics]p10:
3385 // For the purpose of ranking implicit conversion sequences as
3386 // described in 13.3.3.2, the ambiguous conversion sequence is
3387 // treated as a user-defined sequence that is indistinguishable
3388 // from any other user-defined conversion sequence.
3389
3390 // String literal to 'char *' conversion has been deprecated in C++03. It has
3391 // been removed from C++11. We still accept this conversion, if it happens at
3392 // the best viable function. Otherwise, this conversion is considered worse
3393 // than ellipsis conversion. Consider this as an extension; this is not in the
3394 // standard. For example:
3395 //
3396 // int &f(...); // #1
3397 // void f(char*); // #2
3398 // void g() { int &r = f("foo"); }
3399 //
3400 // In C++03, we pick #2 as the best viable function.
3401 // In C++11, we pick #1 as the best viable function, because ellipsis
3402 // conversion is better than string-literal to char* conversion (since there
3403 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3404 // convert arguments, #2 would be the best viable function in C++11.
3405 // If the best viable function has this conversion, a warning will be issued
3406 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3407
3408 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3409 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3410 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3411 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3412 ? ImplicitConversionSequence::Worse
3413 : ImplicitConversionSequence::Better;
3414
3415 if (ICS1.getKindRank() < ICS2.getKindRank())
3416 return ImplicitConversionSequence::Better;
3417 if (ICS2.getKindRank() < ICS1.getKindRank())
3418 return ImplicitConversionSequence::Worse;
3419
3420 // The following checks require both conversion sequences to be of
3421 // the same kind.
3422 if (ICS1.getKind() != ICS2.getKind())
3423 return ImplicitConversionSequence::Indistinguishable;
3424
3425 ImplicitConversionSequence::CompareKind Result =
3426 ImplicitConversionSequence::Indistinguishable;
3427
3428 // Two implicit conversion sequences of the same form are
3429 // indistinguishable conversion sequences unless one of the
3430 // following rules apply: (C++ 13.3.3.2p3):
3431
3432 // List-initialization sequence L1 is a better conversion sequence than
3433 // list-initialization sequence L2 if:
3434 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3435 // if not that,
3436 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3437 // and N1 is smaller than N2.,
3438 // even if one of the other rules in this paragraph would otherwise apply.
3439 if (!ICS1.isBad()) {
3440 if (ICS1.isStdInitializerListElement() &&
3441 !ICS2.isStdInitializerListElement())
3442 return ImplicitConversionSequence::Better;
3443 if (!ICS1.isStdInitializerListElement() &&
3444 ICS2.isStdInitializerListElement())
3445 return ImplicitConversionSequence::Worse;
3446 }
3447
3448 if (ICS1.isStandard())
3449 // Standard conversion sequence S1 is a better conversion sequence than
3450 // standard conversion sequence S2 if [...]
3451 Result = CompareStandardConversionSequences(S, Loc,
3452 ICS1.Standard, ICS2.Standard);
3453 else if (ICS1.isUserDefined()) {
3454 // User-defined conversion sequence U1 is a better conversion
3455 // sequence than another user-defined conversion sequence U2 if
3456 // they contain the same user-defined conversion function or
3457 // constructor and if the second standard conversion sequence of
3458 // U1 is better than the second standard conversion sequence of
3459 // U2 (C++ 13.3.3.2p3).
3460 if (ICS1.UserDefined.ConversionFunction ==
3461 ICS2.UserDefined.ConversionFunction)
3462 Result = CompareStandardConversionSequences(S, Loc,
3463 ICS1.UserDefined.After,
3464 ICS2.UserDefined.After);
3465 else
3466 Result = compareConversionFunctions(S,
3467 ICS1.UserDefined.ConversionFunction,
3468 ICS2.UserDefined.ConversionFunction);
3469 }
3470
3471 return Result;
3472}
3473
3474static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3475 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3476 Qualifiers Quals;
3477 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3478 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3479 }
3480
3481 return Context.hasSameUnqualifiedType(T1, T2);
3482}
3483
3484// Per 13.3.3.2p3, compare the given standard conversion sequences to
3485// determine if one is a proper subset of the other.
3486static ImplicitConversionSequence::CompareKind
3487compareStandardConversionSubsets(ASTContext &Context,
3488 const StandardConversionSequence& SCS1,
3489 const StandardConversionSequence& SCS2) {
3490 ImplicitConversionSequence::CompareKind Result
3491 = ImplicitConversionSequence::Indistinguishable;
3492
3493 // the identity conversion sequence is considered to be a subsequence of
3494 // any non-identity conversion sequence
3495 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3496 return ImplicitConversionSequence::Better;
3497 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3498 return ImplicitConversionSequence::Worse;
3499
3500 if (SCS1.Second != SCS2.Second) {
3501 if (SCS1.Second == ICK_Identity)
3502 Result = ImplicitConversionSequence::Better;
3503 else if (SCS2.Second == ICK_Identity)
3504 Result = ImplicitConversionSequence::Worse;
3505 else
3506 return ImplicitConversionSequence::Indistinguishable;
3507 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3508 return ImplicitConversionSequence::Indistinguishable;
3509
3510 if (SCS1.Third == SCS2.Third) {
3511 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3512 : ImplicitConversionSequence::Indistinguishable;
3513 }
3514
3515 if (SCS1.Third == ICK_Identity)
3516 return Result == ImplicitConversionSequence::Worse
3517 ? ImplicitConversionSequence::Indistinguishable
3518 : ImplicitConversionSequence::Better;
3519
3520 if (SCS2.Third == ICK_Identity)
3521 return Result == ImplicitConversionSequence::Better
3522 ? ImplicitConversionSequence::Indistinguishable
3523 : ImplicitConversionSequence::Worse;
3524
3525 return ImplicitConversionSequence::Indistinguishable;
3526}
3527
3528/// \brief Determine whether one of the given reference bindings is better
3529/// than the other based on what kind of bindings they are.
3530static bool
3531isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3532 const StandardConversionSequence &SCS2) {
3533 // C++0x [over.ics.rank]p3b4:
3534 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3535 // implicit object parameter of a non-static member function declared
3536 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3537 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3538 // lvalue reference to a function lvalue and S2 binds an rvalue
3539 // reference*.
3540 //
3541 // FIXME: Rvalue references. We're going rogue with the above edits,
3542 // because the semantics in the current C++0x working paper (N3225 at the
3543 // time of this writing) break the standard definition of std::forward
3544 // and std::reference_wrapper when dealing with references to functions.
3545 // Proposed wording changes submitted to CWG for consideration.
3546 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3547 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3548 return false;
3549
3550 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3551 SCS2.IsLvalueReference) ||
3552 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3553 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3554}
3555
3556/// CompareStandardConversionSequences - Compare two standard
3557/// conversion sequences to determine whether one is better than the
3558/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3559static ImplicitConversionSequence::CompareKind
3560CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3561 const StandardConversionSequence& SCS1,
3562 const StandardConversionSequence& SCS2)
3563{
3564 // Standard conversion sequence S1 is a better conversion sequence
3565 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3566
3567 // -- S1 is a proper subsequence of S2 (comparing the conversion
3568 // sequences in the canonical form defined by 13.3.3.1.1,
3569 // excluding any Lvalue Transformation; the identity conversion
3570 // sequence is considered to be a subsequence of any
3571 // non-identity conversion sequence) or, if not that,
3572 if (ImplicitConversionSequence::CompareKind CK
3573 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3574 return CK;
3575
3576 // -- the rank of S1 is better than the rank of S2 (by the rules
3577 // defined below), or, if not that,
3578 ImplicitConversionRank Rank1 = SCS1.getRank();
3579 ImplicitConversionRank Rank2 = SCS2.getRank();
3580 if (Rank1 < Rank2)
3581 return ImplicitConversionSequence::Better;
3582 else if (Rank2 < Rank1)
3583 return ImplicitConversionSequence::Worse;
3584
3585 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3586 // are indistinguishable unless one of the following rules
3587 // applies:
3588
3589 // A conversion that is not a conversion of a pointer, or
3590 // pointer to member, to bool is better than another conversion
3591 // that is such a conversion.
3592 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3593 return SCS2.isPointerConversionToBool()
3594 ? ImplicitConversionSequence::Better
3595 : ImplicitConversionSequence::Worse;
3596
3597 // C++ [over.ics.rank]p4b2:
3598 //
3599 // If class B is derived directly or indirectly from class A,
3600 // conversion of B* to A* is better than conversion of B* to
3601 // void*, and conversion of A* to void* is better than conversion
3602 // of B* to void*.
3603 bool SCS1ConvertsToVoid
3604 = SCS1.isPointerConversionToVoidPointer(S.Context);
3605 bool SCS2ConvertsToVoid
3606 = SCS2.isPointerConversionToVoidPointer(S.Context);
3607 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3608 // Exactly one of the conversion sequences is a conversion to
3609 // a void pointer; it's the worse conversion.
3610 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3611 : ImplicitConversionSequence::Worse;
3612 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3613 // Neither conversion sequence converts to a void pointer; compare
3614 // their derived-to-base conversions.
3615 if (ImplicitConversionSequence::CompareKind DerivedCK
3616 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3617 return DerivedCK;
3618 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3619 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3620 // Both conversion sequences are conversions to void
3621 // pointers. Compare the source types to determine if there's an
3622 // inheritance relationship in their sources.
3623 QualType FromType1 = SCS1.getFromType();
3624 QualType FromType2 = SCS2.getFromType();
3625
3626 // Adjust the types we're converting from via the array-to-pointer
3627 // conversion, if we need to.
3628 if (SCS1.First == ICK_Array_To_Pointer)
3629 FromType1 = S.Context.getArrayDecayedType(FromType1);
3630 if (SCS2.First == ICK_Array_To_Pointer)
3631 FromType2 = S.Context.getArrayDecayedType(FromType2);
3632
3633 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3634 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3635
3636 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3637 return ImplicitConversionSequence::Better;
3638 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3639 return ImplicitConversionSequence::Worse;
3640
3641 // Objective-C++: If one interface is more specific than the
3642 // other, it is the better one.
3643 const ObjCObjectPointerType* FromObjCPtr1
3644 = FromType1->getAs<ObjCObjectPointerType>();
3645 const ObjCObjectPointerType* FromObjCPtr2
3646 = FromType2->getAs<ObjCObjectPointerType>();
3647 if (FromObjCPtr1 && FromObjCPtr2) {
3648 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3649 FromObjCPtr2);
3650 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3651 FromObjCPtr1);
3652 if (AssignLeft != AssignRight) {
3653 return AssignLeft? ImplicitConversionSequence::Better
3654 : ImplicitConversionSequence::Worse;
3655 }
3656 }
3657 }
3658
3659 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3660 // bullet 3).
3661 if (ImplicitConversionSequence::CompareKind QualCK
3662 = CompareQualificationConversions(S, SCS1, SCS2))
3663 return QualCK;
3664
3665 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3666 // Check for a better reference binding based on the kind of bindings.
3667 if (isBetterReferenceBindingKind(SCS1, SCS2))
3668 return ImplicitConversionSequence::Better;
3669 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3670 return ImplicitConversionSequence::Worse;
3671
3672 // C++ [over.ics.rank]p3b4:
3673 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3674 // which the references refer are the same type except for
3675 // top-level cv-qualifiers, and the type to which the reference
3676 // initialized by S2 refers is more cv-qualified than the type
3677 // to which the reference initialized by S1 refers.
3678 QualType T1 = SCS1.getToType(2);
3679 QualType T2 = SCS2.getToType(2);
3680 T1 = S.Context.getCanonicalType(T1);
3681 T2 = S.Context.getCanonicalType(T2);
3682 Qualifiers T1Quals, T2Quals;
3683 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3684 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3685 if (UnqualT1 == UnqualT2) {
3686 // Objective-C++ ARC: If the references refer to objects with different
3687 // lifetimes, prefer bindings that don't change lifetime.
3688 if (SCS1.ObjCLifetimeConversionBinding !=
3689 SCS2.ObjCLifetimeConversionBinding) {
3690 return SCS1.ObjCLifetimeConversionBinding
3691 ? ImplicitConversionSequence::Worse
3692 : ImplicitConversionSequence::Better;
3693 }
3694
3695 // If the type is an array type, promote the element qualifiers to the
3696 // type for comparison.
3697 if (isa<ArrayType>(T1) && T1Quals)
3698 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3699 if (isa<ArrayType>(T2) && T2Quals)
3700 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3701 if (T2.isMoreQualifiedThan(T1))
3702 return ImplicitConversionSequence::Better;
3703 else if (T1.isMoreQualifiedThan(T2))
3704 return ImplicitConversionSequence::Worse;
3705 }
3706 }
3707
3708 // In Microsoft mode, prefer an integral conversion to a
3709 // floating-to-integral conversion if the integral conversion
3710 // is between types of the same size.
3711 // For example:
3712 // void f(float);
3713 // void f(int);
3714 // int main {
3715 // long a;
3716 // f(a);
3717 // }
3718 // Here, MSVC will call f(int) instead of generating a compile error
3719 // as clang will do in standard mode.
3720 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3721 SCS2.Second == ICK_Floating_Integral &&
3722 S.Context.getTypeSize(SCS1.getFromType()) ==
3723 S.Context.getTypeSize(SCS1.getToType(2)))
3724 return ImplicitConversionSequence::Better;
3725
3726 return ImplicitConversionSequence::Indistinguishable;
3727}
3728
3729/// CompareQualificationConversions - Compares two standard conversion
3730/// sequences to determine whether they can be ranked based on their
3731/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3732static ImplicitConversionSequence::CompareKind
3733CompareQualificationConversions(Sema &S,
3734 const StandardConversionSequence& SCS1,
3735 const StandardConversionSequence& SCS2) {
3736 // C++ 13.3.3.2p3:
3737 // -- S1 and S2 differ only in their qualification conversion and
3738 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3739 // cv-qualification signature of type T1 is a proper subset of
3740 // the cv-qualification signature of type T2, and S1 is not the
3741 // deprecated string literal array-to-pointer conversion (4.2).
3742 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3743 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3744 return ImplicitConversionSequence::Indistinguishable;
3745
3746 // FIXME: the example in the standard doesn't use a qualification
3747 // conversion (!)
3748 QualType T1 = SCS1.getToType(2);
3749 QualType T2 = SCS2.getToType(2);
3750 T1 = S.Context.getCanonicalType(T1);
3751 T2 = S.Context.getCanonicalType(T2);
3752 Qualifiers T1Quals, T2Quals;
3753 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3754 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3755
3756 // If the types are the same, we won't learn anything by unwrapped
3757 // them.
3758 if (UnqualT1 == UnqualT2)
3759 return ImplicitConversionSequence::Indistinguishable;
3760
3761 // If the type is an array type, promote the element qualifiers to the type
3762 // for comparison.
3763 if (isa<ArrayType>(T1) && T1Quals)
3764 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3765 if (isa<ArrayType>(T2) && T2Quals)
3766 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3767
3768 ImplicitConversionSequence::CompareKind Result
3769 = ImplicitConversionSequence::Indistinguishable;
3770
3771 // Objective-C++ ARC:
3772 // Prefer qualification conversions not involving a change in lifetime
3773 // to qualification conversions that do not change lifetime.
3774 if (SCS1.QualificationIncludesObjCLifetime !=
3775 SCS2.QualificationIncludesObjCLifetime) {
3776 Result = SCS1.QualificationIncludesObjCLifetime
3777 ? ImplicitConversionSequence::Worse
3778 : ImplicitConversionSequence::Better;
3779 }
3780
3781 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3782 // Within each iteration of the loop, we check the qualifiers to
3783 // determine if this still looks like a qualification
3784 // conversion. Then, if all is well, we unwrap one more level of
3785 // pointers or pointers-to-members and do it all again
3786 // until there are no more pointers or pointers-to-members left
3787 // to unwrap. This essentially mimics what
3788 // IsQualificationConversion does, but here we're checking for a
3789 // strict subset of qualifiers.
3790 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3791 // The qualifiers are the same, so this doesn't tell us anything
3792 // about how the sequences rank.
3793 ;
3794 else if (T2.isMoreQualifiedThan(T1)) {
3795 // T1 has fewer qualifiers, so it could be the better sequence.
3796 if (Result == ImplicitConversionSequence::Worse)
3797 // Neither has qualifiers that are a subset of the other's
3798 // qualifiers.
3799 return ImplicitConversionSequence::Indistinguishable;
3800
3801 Result = ImplicitConversionSequence::Better;
3802 } else if (T1.isMoreQualifiedThan(T2)) {
3803 // T2 has fewer qualifiers, so it could be the better sequence.
3804 if (Result == ImplicitConversionSequence::Better)
3805 // Neither has qualifiers that are a subset of the other's
3806 // qualifiers.
3807 return ImplicitConversionSequence::Indistinguishable;
3808
3809 Result = ImplicitConversionSequence::Worse;
3810 } else {
3811 // Qualifiers are disjoint.
3812 return ImplicitConversionSequence::Indistinguishable;
3813 }
3814
3815 // If the types after this point are equivalent, we're done.
3816 if (S.Context.hasSameUnqualifiedType(T1, T2))
3817 break;
3818 }
3819
3820 // Check that the winning standard conversion sequence isn't using
3821 // the deprecated string literal array to pointer conversion.
3822 switch (Result) {
3823 case ImplicitConversionSequence::Better:
3824 if (SCS1.DeprecatedStringLiteralToCharPtr)
3825 Result = ImplicitConversionSequence::Indistinguishable;
3826 break;
3827
3828 case ImplicitConversionSequence::Indistinguishable:
3829 break;
3830
3831 case ImplicitConversionSequence::Worse:
3832 if (SCS2.DeprecatedStringLiteralToCharPtr)
3833 Result = ImplicitConversionSequence::Indistinguishable;
3834 break;
3835 }
3836
3837 return Result;
3838}
3839
3840/// CompareDerivedToBaseConversions - Compares two standard conversion
3841/// sequences to determine whether they can be ranked based on their
3842/// various kinds of derived-to-base conversions (C++
3843/// [over.ics.rank]p4b3). As part of these checks, we also look at
3844/// conversions between Objective-C interface types.
3845static ImplicitConversionSequence::CompareKind
3846CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3847 const StandardConversionSequence& SCS1,
3848 const StandardConversionSequence& SCS2) {
3849 QualType FromType1 = SCS1.getFromType();
3850 QualType ToType1 = SCS1.getToType(1);
3851 QualType FromType2 = SCS2.getFromType();
3852 QualType ToType2 = SCS2.getToType(1);
3853
3854 // Adjust the types we're converting from via the array-to-pointer
3855 // conversion, if we need to.
3856 if (SCS1.First == ICK_Array_To_Pointer)
3857 FromType1 = S.Context.getArrayDecayedType(FromType1);
3858 if (SCS2.First == ICK_Array_To_Pointer)
3859 FromType2 = S.Context.getArrayDecayedType(FromType2);
3860
3861 // Canonicalize all of the types.
3862 FromType1 = S.Context.getCanonicalType(FromType1);
3863 ToType1 = S.Context.getCanonicalType(ToType1);
3864 FromType2 = S.Context.getCanonicalType(FromType2);
3865 ToType2 = S.Context.getCanonicalType(ToType2);
3866
3867 // C++ [over.ics.rank]p4b3:
3868 //
3869 // If class B is derived directly or indirectly from class A and
3870 // class C is derived directly or indirectly from B,
3871 //
3872 // Compare based on pointer conversions.
3873 if (SCS1.Second == ICK_Pointer_Conversion &&
3874 SCS2.Second == ICK_Pointer_Conversion &&
3875 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3876 FromType1->isPointerType() && FromType2->isPointerType() &&
3877 ToType1->isPointerType() && ToType2->isPointerType()) {
3878 QualType FromPointee1
3879 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3880 QualType ToPointee1
3881 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3882 QualType FromPointee2
3883 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3884 QualType ToPointee2
3885 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3886
3887 // -- conversion of C* to B* is better than conversion of C* to A*,
3888 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3889 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3890 return ImplicitConversionSequence::Better;
3891 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3892 return ImplicitConversionSequence::Worse;
3893 }
3894
3895 // -- conversion of B* to A* is better than conversion of C* to A*,
3896 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3897 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3898 return ImplicitConversionSequence::Better;
3899 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3900 return ImplicitConversionSequence::Worse;
3901 }
3902 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3903 SCS2.Second == ICK_Pointer_Conversion) {
3904 const ObjCObjectPointerType *FromPtr1
3905 = FromType1->getAs<ObjCObjectPointerType>();
3906 const ObjCObjectPointerType *FromPtr2
3907 = FromType2->getAs<ObjCObjectPointerType>();
3908 const ObjCObjectPointerType *ToPtr1
3909 = ToType1->getAs<ObjCObjectPointerType>();
3910 const ObjCObjectPointerType *ToPtr2
3911 = ToType2->getAs<ObjCObjectPointerType>();
3912
3913 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3914 // Apply the same conversion ranking rules for Objective-C pointer types
3915 // that we do for C++ pointers to class types. However, we employ the
3916 // Objective-C pseudo-subtyping relationship used for assignment of
3917 // Objective-C pointer types.
3918 bool FromAssignLeft
3919 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3920 bool FromAssignRight
3921 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3922 bool ToAssignLeft
3923 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3924 bool ToAssignRight
3925 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3926
3927 // A conversion to an a non-id object pointer type or qualified 'id'
3928 // type is better than a conversion to 'id'.
3929 if (ToPtr1->isObjCIdType() &&
3930 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3931 return ImplicitConversionSequence::Worse;
3932 if (ToPtr2->isObjCIdType() &&
3933 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3934 return ImplicitConversionSequence::Better;
3935
3936 // A conversion to a non-id object pointer type is better than a
3937 // conversion to a qualified 'id' type
3938 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3939 return ImplicitConversionSequence::Worse;
3940 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3941 return ImplicitConversionSequence::Better;
3942
3943 // A conversion to an a non-Class object pointer type or qualified 'Class'
3944 // type is better than a conversion to 'Class'.
3945 if (ToPtr1->isObjCClassType() &&
3946 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3947 return ImplicitConversionSequence::Worse;
3948 if (ToPtr2->isObjCClassType() &&
3949 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3950 return ImplicitConversionSequence::Better;
3951
3952 // A conversion to a non-Class object pointer type is better than a
3953 // conversion to a qualified 'Class' type.
3954 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3955 return ImplicitConversionSequence::Worse;
3956 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3957 return ImplicitConversionSequence::Better;
3958
3959 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3960 if (S.Context.hasSameType(FromType1, FromType2) &&
3961 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3962 (ToAssignLeft != ToAssignRight))
3963 return ToAssignLeft? ImplicitConversionSequence::Worse
3964 : ImplicitConversionSequence::Better;
3965
3966 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3967 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3968 (FromAssignLeft != FromAssignRight))
3969 return FromAssignLeft? ImplicitConversionSequence::Better
3970 : ImplicitConversionSequence::Worse;
3971 }
3972 }
3973
3974 // Ranking of member-pointer types.
3975 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3976 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3977 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3978 const MemberPointerType * FromMemPointer1 =
3979 FromType1->getAs<MemberPointerType>();
3980 const MemberPointerType * ToMemPointer1 =
3981 ToType1->getAs<MemberPointerType>();
3982 const MemberPointerType * FromMemPointer2 =
3983 FromType2->getAs<MemberPointerType>();
3984 const MemberPointerType * ToMemPointer2 =
3985 ToType2->getAs<MemberPointerType>();
3986 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3987 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3988 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3989 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3990 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3991 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3992 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3993 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3994 // conversion of A::* to B::* is better than conversion of A::* to C::*,
3995 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3996 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
3997 return ImplicitConversionSequence::Worse;
3998 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
3999 return ImplicitConversionSequence::Better;
4000 }
4001 // conversion of B::* to C::* is better than conversion of A::* to C::*
4002 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4003 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4004 return ImplicitConversionSequence::Better;
4005 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4006 return ImplicitConversionSequence::Worse;
4007 }
4008 }
4009
4010 if (SCS1.Second == ICK_Derived_To_Base) {
4011 // -- conversion of C to B is better than conversion of C to A,
4012 // -- binding of an expression of type C to a reference of type
4013 // B& is better than binding an expression of type C to a
4014 // reference of type A&,
4015 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4016 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4017 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4018 return ImplicitConversionSequence::Better;
4019 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4020 return ImplicitConversionSequence::Worse;
4021 }
4022
4023 // -- conversion of B to A is better than conversion of C to A.
4024 // -- binding of an expression of type B to a reference of type
4025 // A& is better than binding an expression of type C to a
4026 // reference of type A&,
4027 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4028 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4029 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4030 return ImplicitConversionSequence::Better;
4031 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4032 return ImplicitConversionSequence::Worse;
4033 }
4034 }
4035
4036 return ImplicitConversionSequence::Indistinguishable;
4037}
4038
4039/// \brief Determine whether the given type is valid, e.g., it is not an invalid
4040/// C++ class.
4041static bool isTypeValid(QualType T) {
4042 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4043 return !Record->isInvalidDecl();
4044
4045 return true;
4046}
4047
4048/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4049/// determine whether they are reference-related,
4050/// reference-compatible, reference-compatible with added
4051/// qualification, or incompatible, for use in C++ initialization by
4052/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4053/// type, and the first type (T1) is the pointee type of the reference
4054/// type being initialized.
4055Sema::ReferenceCompareResult
4056Sema::CompareReferenceRelationship(SourceLocation Loc,
4057 QualType OrigT1, QualType OrigT2,
4058 bool &DerivedToBase,
4059 bool &ObjCConversion,
4060 bool &ObjCLifetimeConversion) {
4061 assert(!OrigT1->isReferenceType() &&((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4062, __PRETTY_FUNCTION__))
4062 "T1 must be the pointee type of the reference type")((!OrigT1->isReferenceType() && "T1 must be the pointee type of the reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT1->isReferenceType() && \"T1 must be the pointee type of the reference type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4062, __PRETTY_FUNCTION__))
;
4063 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type")((!OrigT2->isReferenceType() && "T2 cannot be a reference type"
) ? static_cast<void> (0) : __assert_fail ("!OrigT2->isReferenceType() && \"T2 cannot be a reference type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4063, __PRETTY_FUNCTION__))
;
4064
4065 QualType T1 = Context.getCanonicalType(OrigT1);
4066 QualType T2 = Context.getCanonicalType(OrigT2);
4067 Qualifiers T1Quals, T2Quals;
4068 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4069 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4070
4071 // C++ [dcl.init.ref]p4:
4072 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4073 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4074 // T1 is a base class of T2.
4075 DerivedToBase = false;
4076 ObjCConversion = false;
4077 ObjCLifetimeConversion = false;
4078 if (UnqualT1 == UnqualT2) {
4079 // Nothing to do.
4080 } else if (isCompleteType(Loc, OrigT2) &&
4081 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4082 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4083 DerivedToBase = true;
4084 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4085 UnqualT2->isObjCObjectOrInterfaceType() &&
4086 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4087 ObjCConversion = true;
4088 else
4089 return Ref_Incompatible;
4090
4091 // At this point, we know that T1 and T2 are reference-related (at
4092 // least).
4093
4094 // If the type is an array type, promote the element qualifiers to the type
4095 // for comparison.
4096 if (isa<ArrayType>(T1) && T1Quals)
4097 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4098 if (isa<ArrayType>(T2) && T2Quals)
4099 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4100
4101 // C++ [dcl.init.ref]p4:
4102 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4103 // reference-related to T2 and cv1 is the same cv-qualification
4104 // as, or greater cv-qualification than, cv2. For purposes of
4105 // overload resolution, cases for which cv1 is greater
4106 // cv-qualification than cv2 are identified as
4107 // reference-compatible with added qualification (see 13.3.3.2).
4108 //
4109 // Note that we also require equivalence of Objective-C GC and address-space
4110 // qualifiers when performing these computations, so that e.g., an int in
4111 // address space 1 is not reference-compatible with an int in address
4112 // space 2.
4113 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4114 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4115 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4116 ObjCLifetimeConversion = true;
4117
4118 T1Quals.removeObjCLifetime();
4119 T2Quals.removeObjCLifetime();
4120 }
4121
4122 if (T1Quals == T2Quals)
4123 return Ref_Compatible;
4124 else if (T1Quals.compatiblyIncludes(T2Quals))
4125 return Ref_Compatible_With_Added_Qualification;
4126 else
4127 return Ref_Related;
4128}
4129
4130/// \brief Look for a user-defined conversion to an value reference-compatible
4131/// with DeclType. Return true if something definite is found.
4132static bool
4133FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4134 QualType DeclType, SourceLocation DeclLoc,
4135 Expr *Init, QualType T2, bool AllowRvalues,
4136 bool AllowExplicit) {
4137 assert(T2->isRecordType() && "Can only find conversions of record types.")((T2->isRecordType() && "Can only find conversions of record types."
) ? static_cast<void> (0) : __assert_fail ("T2->isRecordType() && \"Can only find conversions of record types.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4137, __PRETTY_FUNCTION__))
;
4138 CXXRecordDecl *T2RecordDecl
4139 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4140
4141 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4142 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4143 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4144 NamedDecl *D = *I;
4145 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4146 if (isa<UsingShadowDecl>(D))
4147 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4148
4149 FunctionTemplateDecl *ConvTemplate
4150 = dyn_cast<FunctionTemplateDecl>(D);
4151 CXXConversionDecl *Conv;
4152 if (ConvTemplate)
4153 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4154 else
4155 Conv = cast<CXXConversionDecl>(D);
4156
4157 // If this is an explicit conversion, and we're not allowed to consider
4158 // explicit conversions, skip it.
4159 if (!AllowExplicit && Conv->isExplicit())
4160 continue;
4161
4162 if (AllowRvalues) {
4163 bool DerivedToBase = false;
4164 bool ObjCConversion = false;
4165 bool ObjCLifetimeConversion = false;
4166
4167 // If we are initializing an rvalue reference, don't permit conversion
4168 // functions that return lvalues.
4169 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4170 const ReferenceType *RefType
4171 = Conv->getConversionType()->getAs<LValueReferenceType>();
4172 if (RefType && !RefType->getPointeeType()->isFunctionType())
4173 continue;
4174 }
4175
4176 if (!ConvTemplate &&
4177 S.CompareReferenceRelationship(
4178 DeclLoc,
4179 Conv->getConversionType().getNonReferenceType()
4180 .getUnqualifiedType(),
4181 DeclType.getNonReferenceType().getUnqualifiedType(),
4182 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4183 Sema::Ref_Incompatible)
4184 continue;
4185 } else {
4186 // If the conversion function doesn't return a reference type,
4187 // it can't be considered for this conversion. An rvalue reference
4188 // is only acceptable if its referencee is a function type.
4189
4190 const ReferenceType *RefType =
4191 Conv->getConversionType()->getAs<ReferenceType>();
4192 if (!RefType ||
4193 (!RefType->isLValueReferenceType() &&
4194 !RefType->getPointeeType()->isFunctionType()))
4195 continue;
4196 }
4197
4198 if (ConvTemplate)
4199 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4200 Init, DeclType, CandidateSet,
4201 /*AllowObjCConversionOnExplicit=*/false);
4202 else
4203 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4204 DeclType, CandidateSet,
4205 /*AllowObjCConversionOnExplicit=*/false);
4206 }
4207
4208 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4209
4210 OverloadCandidateSet::iterator Best;
4211 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4212 case OR_Success:
4213 // C++ [over.ics.ref]p1:
4214 //
4215 // [...] If the parameter binds directly to the result of
4216 // applying a conversion function to the argument
4217 // expression, the implicit conversion sequence is a
4218 // user-defined conversion sequence (13.3.3.1.2), with the
4219 // second standard conversion sequence either an identity
4220 // conversion or, if the conversion function returns an
4221 // entity of a type that is a derived class of the parameter
4222 // type, a derived-to-base Conversion.
4223 if (!Best->FinalConversion.DirectBinding)
4224 return false;
4225
4226 ICS.setUserDefined();
4227 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4228 ICS.UserDefined.After = Best->FinalConversion;
4229 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4230 ICS.UserDefined.ConversionFunction = Best->Function;
4231 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4232 ICS.UserDefined.EllipsisConversion = false;
4233 assert(ICS.UserDefined.After.ReferenceBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4235, __PRETTY_FUNCTION__))
4234 ICS.UserDefined.After.DirectBinding &&((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4235, __PRETTY_FUNCTION__))
4235 "Expected a direct reference binding!")((ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined
.After.DirectBinding && "Expected a direct reference binding!"
) ? static_cast<void> (0) : __assert_fail ("ICS.UserDefined.After.ReferenceBinding && ICS.UserDefined.After.DirectBinding && \"Expected a direct reference binding!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4235, __PRETTY_FUNCTION__))
;
4236 return true;
4237
4238 case OR_Ambiguous:
4239 ICS.setAmbiguous();
4240 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4241 Cand != CandidateSet.end(); ++Cand)
4242 if (Cand->Viable)
4243 ICS.Ambiguous.addConversion(Cand->Function);
4244 return true;
4245
4246 case OR_No_Viable_Function:
4247 case OR_Deleted:
4248 // There was no suitable conversion, or we found a deleted
4249 // conversion; continue with other checks.
4250 return false;
4251 }
4252
4253 llvm_unreachable("Invalid OverloadResult!")::llvm::llvm_unreachable_internal("Invalid OverloadResult!", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4253)
;
4254}
4255
4256/// \brief Compute an implicit conversion sequence for reference
4257/// initialization.
4258static ImplicitConversionSequence
4259TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4260 SourceLocation DeclLoc,
4261 bool SuppressUserConversions,
4262 bool AllowExplicit) {
4263 assert(DeclType->isReferenceType() && "Reference init needs a reference")((DeclType->isReferenceType() && "Reference init needs a reference"
) ? static_cast<void> (0) : __assert_fail ("DeclType->isReferenceType() && \"Reference init needs a reference\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4263, __PRETTY_FUNCTION__))
;
4264
4265 // Most paths end in a failed conversion.
4266 ImplicitConversionSequence ICS;
4267 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4268
4269 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4270 QualType T2 = Init->getType();
4271
4272 // If the initializer is the address of an overloaded function, try
4273 // to resolve the overloaded function. If all goes well, T2 is the
4274 // type of the resulting function.
4275 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4276 DeclAccessPair Found;
4277 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4278 false, Found))
4279 T2 = Fn->getType();
4280 }
4281
4282 // Compute some basic properties of the types and the initializer.
4283 bool isRValRef = DeclType->isRValueReferenceType();
4284 bool DerivedToBase = false;
4285 bool ObjCConversion = false;
4286 bool ObjCLifetimeConversion = false;
4287 Expr::Classification InitCategory = Init->Classify(S.Context);
4288 Sema::ReferenceCompareResult RefRelationship
4289 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4290 ObjCConversion, ObjCLifetimeConversion);
4291
4292
4293 // C++0x [dcl.init.ref]p5:
4294 // A reference to type "cv1 T1" is initialized by an expression
4295 // of type "cv2 T2" as follows:
4296
4297 // -- If reference is an lvalue reference and the initializer expression
4298 if (!isRValRef) {
4299 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4300 // reference-compatible with "cv2 T2," or
4301 //
4302 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4303 if (InitCategory.isLValue() &&
4304 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4305 // C++ [over.ics.ref]p1:
4306 // When a parameter of reference type binds directly (8.5.3)
4307 // to an argument expression, the implicit conversion sequence
4308 // is the identity conversion, unless the argument expression
4309 // has a type that is a derived class of the parameter type,
4310 // in which case the implicit conversion sequence is a
4311 // derived-to-base Conversion (13.3.3.1).
4312 ICS.setStandard();
4313 ICS.Standard.First = ICK_Identity;
4314 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4315 : ObjCConversion? ICK_Compatible_Conversion
4316 : ICK_Identity;
4317 ICS.Standard.Third = ICK_Identity;
4318 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4319 ICS.Standard.setToType(0, T2);
4320 ICS.Standard.setToType(1, T1);
4321 ICS.Standard.setToType(2, T1);
4322 ICS.Standard.ReferenceBinding = true;
4323 ICS.Standard.DirectBinding = true;
4324 ICS.Standard.IsLvalueReference = !isRValRef;
4325 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4326 ICS.Standard.BindsToRvalue = false;
4327 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4328 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4329 ICS.Standard.CopyConstructor = nullptr;
4330 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4331
4332 // Nothing more to do: the inaccessibility/ambiguity check for
4333 // derived-to-base conversions is suppressed when we're
4334 // computing the implicit conversion sequence (C++
4335 // [over.best.ics]p2).
4336 return ICS;
4337 }
4338
4339 // -- has a class type (i.e., T2 is a class type), where T1 is
4340 // not reference-related to T2, and can be implicitly
4341 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4342 // is reference-compatible with "cv3 T3" 92) (this
4343 // conversion is selected by enumerating the applicable
4344 // conversion functions (13.3.1.6) and choosing the best
4345 // one through overload resolution (13.3)),
4346 if (!SuppressUserConversions && T2->isRecordType() &&
4347 S.isCompleteType(DeclLoc, T2) &&
4348 RefRelationship == Sema::Ref_Incompatible) {
4349 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4350 Init, T2, /*AllowRvalues=*/false,
4351 AllowExplicit))
4352 return ICS;
4353 }
4354 }
4355
4356 // -- Otherwise, the reference shall be an lvalue reference to a
4357 // non-volatile const type (i.e., cv1 shall be const), or the reference
4358 // shall be an rvalue reference.
4359 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4360 return ICS;
4361
4362 // -- If the initializer expression
4363 //
4364 // -- is an xvalue, class prvalue, array prvalue or function
4365 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4366 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4367 (InitCategory.isXValue() ||
4368 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4369 (InitCategory.isLValue() && T2->isFunctionType()))) {
4370 ICS.setStandard();
4371 ICS.Standard.First = ICK_Identity;
4372 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4373 : ObjCConversion? ICK_Compatible_Conversion
4374 : ICK_Identity;
4375 ICS.Standard.Third = ICK_Identity;
4376 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4377 ICS.Standard.setToType(0, T2);
4378 ICS.Standard.setToType(1, T1);
4379 ICS.Standard.setToType(2, T1);
4380 ICS.Standard.ReferenceBinding = true;
4381 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4382 // binding unless we're binding to a class prvalue.
4383 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4384 // allow the use of rvalue references in C++98/03 for the benefit of
4385 // standard library implementors; therefore, we need the xvalue check here.
4386 ICS.Standard.DirectBinding =
4387 S.getLangOpts().CPlusPlus11 ||
4388 !(InitCategory.isPRValue() || T2->isRecordType());
4389 ICS.Standard.IsLvalueReference = !isRValRef;
4390 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4391 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4392 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4393 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4394 ICS.Standard.CopyConstructor = nullptr;
4395 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4396 return ICS;
4397 }
4398
4399 // -- has a class type (i.e., T2 is a class type), where T1 is not
4400 // reference-related to T2, and can be implicitly converted to
4401 // an xvalue, class prvalue, or function lvalue of type
4402 // "cv3 T3", where "cv1 T1" is reference-compatible with
4403 // "cv3 T3",
4404 //
4405 // then the reference is bound to the value of the initializer
4406 // expression in the first case and to the result of the conversion
4407 // in the second case (or, in either case, to an appropriate base
4408 // class subobject).
4409 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4410 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4411 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4412 Init, T2, /*AllowRvalues=*/true,
4413 AllowExplicit)) {
4414 // In the second case, if the reference is an rvalue reference
4415 // and the second standard conversion sequence of the
4416 // user-defined conversion sequence includes an lvalue-to-rvalue
4417 // conversion, the program is ill-formed.
4418 if (ICS.isUserDefined() && isRValRef &&
4419 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4420 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4421
4422 return ICS;
4423 }
4424
4425 // A temporary of function type cannot be created; don't even try.
4426 if (T1->isFunctionType())
4427 return ICS;
4428
4429 // -- Otherwise, a temporary of type "cv1 T1" is created and
4430 // initialized from the initializer expression using the
4431 // rules for a non-reference copy initialization (8.5). The
4432 // reference is then bound to the temporary. If T1 is
4433 // reference-related to T2, cv1 must be the same
4434 // cv-qualification as, or greater cv-qualification than,
4435 // cv2; otherwise, the program is ill-formed.
4436 if (RefRelationship == Sema::Ref_Related) {
4437 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4438 // we would be reference-compatible or reference-compatible with
4439 // added qualification. But that wasn't the case, so the reference
4440 // initialization fails.
4441 //
4442 // Note that we only want to check address spaces and cvr-qualifiers here.
4443 // ObjC GC and lifetime qualifiers aren't important.
4444 Qualifiers T1Quals = T1.getQualifiers();
4445 Qualifiers T2Quals = T2.getQualifiers();
4446 T1Quals.removeObjCGCAttr();
4447 T1Quals.removeObjCLifetime();
4448 T2Quals.removeObjCGCAttr();
4449 T2Quals.removeObjCLifetime();
4450 if (!T1Quals.compatiblyIncludes(T2Quals))
4451 return ICS;
4452 }
4453
4454 // If at least one of the types is a class type, the types are not
4455 // related, and we aren't allowed any user conversions, the
4456 // reference binding fails. This case is important for breaking
4457 // recursion, since TryImplicitConversion below will attempt to
4458 // create a temporary through the use of a copy constructor.
4459 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4460 (T1->isRecordType() || T2->isRecordType()))
4461 return ICS;
4462
4463 // If T1 is reference-related to T2 and the reference is an rvalue
4464 // reference, the initializer expression shall not be an lvalue.
4465 if (RefRelationship >= Sema::Ref_Related &&
4466 isRValRef && Init->Classify(S.Context).isLValue())
4467 return ICS;
4468
4469 // C++ [over.ics.ref]p2:
4470 // When a parameter of reference type is not bound directly to
4471 // an argument expression, the conversion sequence is the one
4472 // required to convert the argument expression to the
4473 // underlying type of the reference according to
4474 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4475 // to copy-initializing a temporary of the underlying type with
4476 // the argument expression. Any difference in top-level
4477 // cv-qualification is subsumed by the initialization itself
4478 // and does not constitute a conversion.
4479 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4480 /*AllowExplicit=*/false,
4481 /*InOverloadResolution=*/false,
4482 /*CStyle=*/false,
4483 /*AllowObjCWritebackConversion=*/false,
4484 /*AllowObjCConversionOnExplicit=*/false);
4485
4486 // Of course, that's still a reference binding.
4487 if (ICS.isStandard()) {
4488 ICS.Standard.ReferenceBinding = true;
4489 ICS.Standard.IsLvalueReference = !isRValRef;
4490 ICS.Standard.BindsToFunctionLvalue = false;
4491 ICS.Standard.BindsToRvalue = true;
4492 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4493 ICS.Standard.ObjCLifetimeConversionBinding = false;
4494 } else if (ICS.isUserDefined()) {
4495 const ReferenceType *LValRefType =
4496 ICS.UserDefined.ConversionFunction->getReturnType()
4497 ->getAs<LValueReferenceType>();
4498
4499 // C++ [over.ics.ref]p3:
4500 // Except for an implicit object parameter, for which see 13.3.1, a
4501 // standard conversion sequence cannot be formed if it requires [...]
4502 // binding an rvalue reference to an lvalue other than a function
4503 // lvalue.
4504 // Note that the function case is not possible here.
4505 if (DeclType->isRValueReferenceType() && LValRefType) {
4506 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4507 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4508 // reference to an rvalue!
4509 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4510 return ICS;
4511 }
4512
4513 ICS.UserDefined.Before.setAsIdentityConversion();
4514 ICS.UserDefined.After.ReferenceBinding = true;
4515 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4516 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4517 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4518 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4519 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4520 }
4521
4522 return ICS;
4523}
4524
4525static ImplicitConversionSequence
4526TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4527 bool SuppressUserConversions,
4528 bool InOverloadResolution,
4529 bool AllowObjCWritebackConversion,
4530 bool AllowExplicit = false);
4531
4532/// TryListConversion - Try to copy-initialize a value of type ToType from the
4533/// initializer list From.
4534static ImplicitConversionSequence
4535TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4536 bool SuppressUserConversions,
4537 bool InOverloadResolution,
4538 bool AllowObjCWritebackConversion) {
4539 // C++11 [over.ics.list]p1:
4540 // When an argument is an initializer list, it is not an expression and
4541 // special rules apply for converting it to a parameter type.
4542
4543 ImplicitConversionSequence Result;
4544 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4545
4546 // We need a complete type for what follows. Incomplete types can never be
4547 // initialized from init lists.
4548 if (!S.isCompleteType(From->getLocStart(), ToType))
4549 return Result;
4550
4551 // Per DR1467:
4552 // If the parameter type is a class X and the initializer list has a single
4553 // element of type cv U, where U is X or a class derived from X, the
4554 // implicit conversion sequence is the one required to convert the element
4555 // to the parameter type.
4556 //
4557 // Otherwise, if the parameter type is a character array [... ]
4558 // and the initializer list has a single element that is an
4559 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4560 // implicit conversion sequence is the identity conversion.
4561 if (From->getNumInits() == 1) {
4562 if (ToType->isRecordType()) {
4563 QualType InitType = From->getInit(0)->getType();
4564 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4565 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4566 return TryCopyInitialization(S, From->getInit(0), ToType,
4567 SuppressUserConversions,
4568 InOverloadResolution,
4569 AllowObjCWritebackConversion);
4570 }
4571 // FIXME: Check the other conditions here: array of character type,
4572 // initializer is a string literal.
4573 if (ToType->isArrayType()) {
4574 InitializedEntity Entity =
4575 InitializedEntity::InitializeParameter(S.Context, ToType,
4576 /*Consumed=*/false);
4577 if (S.CanPerformCopyInitialization(Entity, From)) {
4578 Result.setStandard();
4579 Result.Standard.setAsIdentityConversion();
4580 Result.Standard.setFromType(ToType);
4581 Result.Standard.setAllToTypes(ToType);
4582 return Result;
4583 }
4584 }
4585 }
4586
4587 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4588 // C++11 [over.ics.list]p2:
4589 // If the parameter type is std::initializer_list<X> or "array of X" and
4590 // all the elements can be implicitly converted to X, the implicit
4591 // conversion sequence is the worst conversion necessary to convert an
4592 // element of the list to X.
4593 //
4594 // C++14 [over.ics.list]p3:
4595 // Otherwise, if the parameter type is "array of N X", if the initializer
4596 // list has exactly N elements or if it has fewer than N elements and X is
4597 // default-constructible, and if all the elements of the initializer list
4598 // can be implicitly converted to X, the implicit conversion sequence is
4599 // the worst conversion necessary to convert an element of the list to X.
4600 //
4601 // FIXME: We're missing a lot of these checks.
4602 bool toStdInitializerList = false;
4603 QualType X;
4604 if (ToType->isArrayType())
4605 X = S.Context.getAsArrayType(ToType)->getElementType();
4606 else
4607 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4608 if (!X.isNull()) {
4609 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4610 Expr *Init = From->getInit(i);
4611 ImplicitConversionSequence ICS =
4612 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4613 InOverloadResolution,
4614 AllowObjCWritebackConversion);
4615 // If a single element isn't convertible, fail.
4616 if (ICS.isBad()) {
4617 Result = ICS;
4618 break;
4619 }
4620 // Otherwise, look for the worst conversion.
4621 if (Result.isBad() ||
4622 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4623 Result) ==
4624 ImplicitConversionSequence::Worse)
4625 Result = ICS;
4626 }
4627
4628 // For an empty list, we won't have computed any conversion sequence.
4629 // Introduce the identity conversion sequence.
4630 if (From->getNumInits() == 0) {
4631 Result.setStandard();
4632 Result.Standard.setAsIdentityConversion();
4633 Result.Standard.setFromType(ToType);
4634 Result.Standard.setAllToTypes(ToType);
4635 }
4636
4637 Result.setStdInitializerListElement(toStdInitializerList);
4638 return Result;
4639 }
4640
4641 // C++14 [over.ics.list]p4:
4642 // C++11 [over.ics.list]p3:
4643 // Otherwise, if the parameter is a non-aggregate class X and overload
4644 // resolution chooses a single best constructor [...] the implicit
4645 // conversion sequence is a user-defined conversion sequence. If multiple
4646 // constructors are viable but none is better than the others, the
4647 // implicit conversion sequence is a user-defined conversion sequence.
4648 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4649 // This function can deal with initializer lists.
4650 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4651 /*AllowExplicit=*/false,
4652 InOverloadResolution, /*CStyle=*/false,
4653 AllowObjCWritebackConversion,
4654 /*AllowObjCConversionOnExplicit=*/false);
4655 }
4656
4657 // C++14 [over.ics.list]p5:
4658 // C++11 [over.ics.list]p4:
4659 // Otherwise, if the parameter has an aggregate type which can be
4660 // initialized from the initializer list [...] the implicit conversion
4661 // sequence is a user-defined conversion sequence.
4662 if (ToType->isAggregateType()) {
4663 // Type is an aggregate, argument is an init list. At this point it comes
4664 // down to checking whether the initialization works.
4665 // FIXME: Find out whether this parameter is consumed or not.
4666 InitializedEntity Entity =
4667 InitializedEntity::InitializeParameter(S.Context, ToType,
4668 /*Consumed=*/false);
4669 if (S.CanPerformCopyInitialization(Entity, From)) {
4670 Result.setUserDefined();
4671 Result.UserDefined.Before.setAsIdentityConversion();
4672 // Initializer lists don't have a type.
4673 Result.UserDefined.Before.setFromType(QualType());
4674 Result.UserDefined.Before.setAllToTypes(QualType());
4675
4676 Result.UserDefined.After.setAsIdentityConversion();
4677 Result.UserDefined.After.setFromType(ToType);
4678 Result.UserDefined.After.setAllToTypes(ToType);
4679 Result.UserDefined.ConversionFunction = nullptr;
4680 }
4681 return Result;
4682 }
4683
4684 // C++14 [over.ics.list]p6:
4685 // C++11 [over.ics.list]p5:
4686 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4687 if (ToType->isReferenceType()) {
4688 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4689 // mention initializer lists in any way. So we go by what list-
4690 // initialization would do and try to extrapolate from that.
4691
4692 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4693
4694 // If the initializer list has a single element that is reference-related
4695 // to the parameter type, we initialize the reference from that.
4696 if (From->getNumInits() == 1) {
4697 Expr *Init = From->getInit(0);
4698
4699 QualType T2 = Init->getType();
4700
4701 // If the initializer is the address of an overloaded function, try
4702 // to resolve the overloaded function. If all goes well, T2 is the
4703 // type of the resulting function.
4704 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4705 DeclAccessPair Found;
4706 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4707 Init, ToType, false, Found))
4708 T2 = Fn->getType();
4709 }
4710
4711 // Compute some basic properties of the types and the initializer.
4712 bool dummy1 = false;
4713 bool dummy2 = false;
4714 bool dummy3 = false;
4715 Sema::ReferenceCompareResult RefRelationship
4716 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4717 dummy2, dummy3);
4718
4719 if (RefRelationship >= Sema::Ref_Related) {
4720 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4721 SuppressUserConversions,
4722 /*AllowExplicit=*/false);
4723 }
4724 }
4725
4726 // Otherwise, we bind the reference to a temporary created from the
4727 // initializer list.
4728 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4729 InOverloadResolution,
4730 AllowObjCWritebackConversion);
4731 if (Result.isFailure())
4732 return Result;
4733 assert(!Result.isEllipsis() &&((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4734, __PRETTY_FUNCTION__))
4734 "Sub-initialization cannot result in ellipsis conversion.")((!Result.isEllipsis() && "Sub-initialization cannot result in ellipsis conversion."
) ? static_cast<void> (0) : __assert_fail ("!Result.isEllipsis() && \"Sub-initialization cannot result in ellipsis conversion.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4734, __PRETTY_FUNCTION__))
;
4735
4736 // Can we even bind to a temporary?
4737 if (ToType->isRValueReferenceType() ||
4738 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4739 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4740 Result.UserDefined.After;
4741 SCS.ReferenceBinding = true;
4742 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4743 SCS.BindsToRvalue = true;
4744 SCS.BindsToFunctionLvalue = false;
4745 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4746 SCS.ObjCLifetimeConversionBinding = false;
4747 } else
4748 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4749 From, ToType);
4750 return Result;
4751 }
4752
4753 // C++14 [over.ics.list]p7:
4754 // C++11 [over.ics.list]p6:
4755 // Otherwise, if the parameter type is not a class:
4756 if (!ToType->isRecordType()) {
4757 // - if the initializer list has one element that is not itself an
4758 // initializer list, the implicit conversion sequence is the one
4759 // required to convert the element to the parameter type.
4760 unsigned NumInits = From->getNumInits();
4761 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4762 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4763 SuppressUserConversions,
4764 InOverloadResolution,
4765 AllowObjCWritebackConversion);
4766 // - if the initializer list has no elements, the implicit conversion
4767 // sequence is the identity conversion.
4768 else if (NumInits == 0) {
4769 Result.setStandard();
4770 Result.Standard.setAsIdentityConversion();
4771 Result.Standard.setFromType(ToType);
4772 Result.Standard.setAllToTypes(ToType);
4773 }
4774 return Result;
4775 }
4776
4777 // C++14 [over.ics.list]p8:
4778 // C++11 [over.ics.list]p7:
4779 // In all cases other than those enumerated above, no conversion is possible
4780 return Result;
4781}
4782
4783/// TryCopyInitialization - Try to copy-initialize a value of type
4784/// ToType from the expression From. Return the implicit conversion
4785/// sequence required to pass this argument, which may be a bad
4786/// conversion sequence (meaning that the argument cannot be passed to
4787/// a parameter of this type). If @p SuppressUserConversions, then we
4788/// do not permit any user-defined conversion sequences.
4789static ImplicitConversionSequence
4790TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4791 bool SuppressUserConversions,
4792 bool InOverloadResolution,
4793 bool AllowObjCWritebackConversion,
4794 bool AllowExplicit) {
4795 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4796 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4797 InOverloadResolution,AllowObjCWritebackConversion);
4798
4799 if (ToType->isReferenceType())
4800 return TryReferenceInit(S, From, ToType,
4801 /*FIXME:*/From->getLocStart(),
4802 SuppressUserConversions,
4803 AllowExplicit);
4804
4805 return TryImplicitConversion(S, From, ToType,
4806 SuppressUserConversions,
4807 /*AllowExplicit=*/false,
4808 InOverloadResolution,
4809 /*CStyle=*/false,
4810 AllowObjCWritebackConversion,
4811 /*AllowObjCConversionOnExplicit=*/false);
4812}
4813
4814static bool TryCopyInitialization(const CanQualType FromQTy,
4815 const CanQualType ToQTy,
4816 Sema &S,
4817 SourceLocation Loc,
4818 ExprValueKind FromVK) {
4819 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4820 ImplicitConversionSequence ICS =
4821 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4822
4823 return !ICS.isBad();
4824}
4825
4826/// TryObjectArgumentInitialization - Try to initialize the object
4827/// parameter of the given member function (@c Method) from the
4828/// expression @p From.
4829static ImplicitConversionSequence
4830TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4831 Expr::Classification FromClassification,
4832 CXXMethodDecl *Method,
4833 CXXRecordDecl *ActingContext) {
4834 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4835 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4836 // const volatile object.
4837 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4838 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4839 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4840
4841 // Set up the conversion sequence as a "bad" conversion, to allow us
4842 // to exit early.
4843 ImplicitConversionSequence ICS;
4844
4845 // We need to have an object of class type.
4846 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4847 FromType = PT->getPointeeType();
4848
4849 // When we had a pointer, it's implicitly dereferenced, so we
4850 // better have an lvalue.
4851 assert(FromClassification.isLValue())((FromClassification.isLValue()) ? static_cast<void> (0
) : __assert_fail ("FromClassification.isLValue()", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4851, __PRETTY_FUNCTION__))
;
4852 }
4853
4854 assert(FromType->isRecordType())((FromType->isRecordType()) ? static_cast<void> (0) :
__assert_fail ("FromType->isRecordType()", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 4854, __PRETTY_FUNCTION__))
;
4855
4856 // C++0x [over.match.funcs]p4:
4857 // For non-static member functions, the type of the implicit object
4858 // parameter is
4859 //
4860 // - "lvalue reference to cv X" for functions declared without a
4861 // ref-qualifier or with the & ref-qualifier
4862 // - "rvalue reference to cv X" for functions declared with the &&
4863 // ref-qualifier
4864 //
4865 // where X is the class of which the function is a member and cv is the
4866 // cv-qualification on the member function declaration.
4867 //
4868 // However, when finding an implicit conversion sequence for the argument, we
4869 // are not allowed to create temporaries or perform user-defined conversions
4870 // (C++ [over.match.funcs]p5). We perform a simplified version of
4871 // reference binding here, that allows class rvalues to bind to
4872 // non-constant references.
4873
4874 // First check the qualifiers.
4875 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4876 if (ImplicitParamType.getCVRQualifiers()
4877 != FromTypeCanon.getLocalCVRQualifiers() &&
4878 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4879 ICS.setBad(BadConversionSequence::bad_qualifiers,
4880 FromType, ImplicitParamType);
4881 return ICS;
4882 }
4883
4884 // Check that we have either the same type or a derived type. It
4885 // affects the conversion rank.
4886 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4887 ImplicitConversionKind SecondKind;
4888 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4889 SecondKind = ICK_Identity;
4890 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
4891 SecondKind = ICK_Derived_To_Base;
4892 else {
4893 ICS.setBad(BadConversionSequence::unrelated_class,
4894 FromType, ImplicitParamType);
4895 return ICS;
4896 }
4897
4898 // Check the ref-qualifier.
4899 switch (Method->getRefQualifier()) {
4900 case RQ_None:
4901 // Do nothing; we don't care about lvalueness or rvalueness.
4902 break;
4903
4904 case RQ_LValue:
4905 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4906 // non-const lvalue reference cannot bind to an rvalue
4907 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4908 ImplicitParamType);
4909 return ICS;
4910 }
4911 break;
4912
4913 case RQ_RValue:
4914 if (!FromClassification.isRValue()) {
4915 // rvalue reference cannot bind to an lvalue
4916 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4917 ImplicitParamType);
4918 return ICS;
4919 }
4920 break;
4921 }
4922
4923 // Success. Mark this as a reference binding.
4924 ICS.setStandard();
4925 ICS.Standard.setAsIdentityConversion();
4926 ICS.Standard.Second = SecondKind;
4927 ICS.Standard.setFromType(FromType);
4928 ICS.Standard.setAllToTypes(ImplicitParamType);
4929 ICS.Standard.ReferenceBinding = true;
4930 ICS.Standard.DirectBinding = true;
4931 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4932 ICS.Standard.BindsToFunctionLvalue = false;
4933 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4934 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4935 = (Method->getRefQualifier() == RQ_None);
4936 return ICS;
4937}
4938
4939/// PerformObjectArgumentInitialization - Perform initialization of
4940/// the implicit object parameter for the given Method with the given
4941/// expression.
4942ExprResult
4943Sema::PerformObjectArgumentInitialization(Expr *From,
4944 NestedNameSpecifier *Qualifier,
4945 NamedDecl *FoundDecl,
4946 CXXMethodDecl *Method) {
4947 QualType FromRecordType, DestType;
4948 QualType ImplicitParamRecordType =
4949 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4950
4951 Expr::Classification FromClassification;
4952 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4953 FromRecordType = PT->getPointeeType();
4954 DestType = Method->getThisType(Context);
4955 FromClassification = Expr::Classification::makeSimpleLValue();
4956 } else {
4957 FromRecordType = From->getType();
4958 DestType = ImplicitParamRecordType;
4959 FromClassification = From->Classify(Context);
4960 }
4961
4962 // Note that we always use the true parent context when performing
4963 // the actual argument initialization.
4964 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4965 *this, From->getLocStart(), From->getType(), FromClassification, Method,
4966 Method->getParent());
4967 if (ICS.isBad()) {
4968 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4969 Qualifiers FromQs = FromRecordType.getQualifiers();
4970 Qualifiers ToQs = DestType.getQualifiers();
4971 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4972 if (CVR) {
4973 Diag(From->getLocStart(),
4974 diag::err_member_function_call_bad_cvr)
4975 << Method->getDeclName() << FromRecordType << (CVR - 1)
4976 << From->getSourceRange();
4977 Diag(Method->getLocation(), diag::note_previous_decl)
4978 << Method->getDeclName();
4979 return ExprError();
4980 }
4981 }
4982
4983 return Diag(From->getLocStart(),
4984 diag::err_implicit_object_parameter_init)
4985 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4986 }
4987
4988 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4989 ExprResult FromRes =
4990 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4991 if (FromRes.isInvalid())
4992 return ExprError();
4993 From = FromRes.get();
4994 }
4995
4996 if (!Context.hasSameType(From->getType(), DestType))
4997 From = ImpCastExprToType(From, DestType, CK_NoOp,
4998 From->getValueKind()).get();
4999 return From;
5000}
5001
5002/// TryContextuallyConvertToBool - Attempt to contextually convert the
5003/// expression From to bool (C++0x [conv]p3).
5004static ImplicitConversionSequence
5005TryContextuallyConvertToBool(Sema &S, Expr *From) {
5006 return TryImplicitConversion(S, From, S.Context.BoolTy,
5007 /*SuppressUserConversions=*/false,
5008 /*AllowExplicit=*/true,
5009 /*InOverloadResolution=*/false,
5010 /*CStyle=*/false,
5011 /*AllowObjCWritebackConversion=*/false,
5012 /*AllowObjCConversionOnExplicit=*/false);
5013}
5014
5015/// PerformContextuallyConvertToBool - Perform a contextual conversion
5016/// of the expression From to bool (C++0x [conv]p3).
5017ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5018 if (checkPlaceholderForOverload(*this, From))
5019 return ExprError();
5020
5021 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5022 if (!ICS.isBad())
5023 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5024
5025 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5026 return Diag(From->getLocStart(),
5027 diag::err_typecheck_bool_condition)
5028 << From->getType() << From->getSourceRange();
5029 return ExprError();
5030}
5031
5032/// Check that the specified conversion is permitted in a converted constant
5033/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5034/// is acceptable.
5035static bool CheckConvertedConstantConversions(Sema &S,
5036 StandardConversionSequence &SCS) {
5037 // Since we know that the target type is an integral or unscoped enumeration
5038 // type, most conversion kinds are impossible. All possible First and Third
5039 // conversions are fine.
5040 switch (SCS.Second) {
5041 case ICK_Identity:
5042 case ICK_NoReturn_Adjustment:
5043 case ICK_Integral_Promotion:
5044 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5045 return true;
5046
5047 case ICK_Boolean_Conversion:
5048 // Conversion from an integral or unscoped enumeration type to bool is
5049 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5050 // conversion, so we allow it in a converted constant expression.
5051 //
5052 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5053 // a lot of popular code. We should at least add a warning for this
5054 // (non-conforming) extension.
5055 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5056 SCS.getToType(2)->isBooleanType();
5057
5058 case ICK_Pointer_Conversion:
5059 case ICK_Pointer_Member:
5060 // C++1z: null pointer conversions and null member pointer conversions are
5061 // only permitted if the source type is std::nullptr_t.
5062 return SCS.getFromType()->isNullPtrType();
5063
5064 case ICK_Floating_Promotion:
5065 case ICK_Complex_Promotion:
5066 case ICK_Floating_Conversion:
5067 case ICK_Complex_Conversion:
5068 case ICK_Floating_Integral:
5069 case ICK_Compatible_Conversion:
5070 case ICK_Derived_To_Base:
5071 case ICK_Vector_Conversion:
5072 case ICK_Vector_Splat:
5073 case ICK_Complex_Real:
5074 case ICK_Block_Pointer_Conversion:
5075 case ICK_TransparentUnionConversion:
5076 case ICK_Writeback_Conversion:
5077 case ICK_Zero_Event_Conversion:
5078 case ICK_C_Only_Conversion:
5079 return false;
5080
5081 case ICK_Lvalue_To_Rvalue:
5082 case ICK_Array_To_Pointer:
5083 case ICK_Function_To_Pointer:
5084 llvm_unreachable("found a first conversion kind in Second")::llvm::llvm_unreachable_internal("found a first conversion kind in Second"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5084)
;
5085
5086 case ICK_Qualification:
5087 llvm_unreachable("found a third conversion kind in Second")::llvm::llvm_unreachable_internal("found a third conversion kind in Second"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5087)
;
5088
5089 case ICK_Num_Conversion_Kinds:
5090 break;
5091 }
5092
5093 llvm_unreachable("unknown conversion kind")::llvm::llvm_unreachable_internal("unknown conversion kind", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5093)
;
5094}
5095
5096/// CheckConvertedConstantExpression - Check that the expression From is a
5097/// converted constant expression of type T, perform the conversion and produce
5098/// the converted expression, per C++11 [expr.const]p3.
5099static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5100 QualType T, APValue &Value,
5101 Sema::CCEKind CCE,
5102 bool RequireInt) {
5103 assert(S.getLangOpts().CPlusPlus11 &&((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5104, __PRETTY_FUNCTION__))
5104 "converted constant expression outside C++11")((S.getLangOpts().CPlusPlus11 && "converted constant expression outside C++11"
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus11 && \"converted constant expression outside C++11\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5104, __PRETTY_FUNCTION__))
;
5105
5106 if (checkPlaceholderForOverload(S, From))
5107 return ExprError();
5108
5109 // C++1z [expr.const]p3:
5110 // A converted constant expression of type T is an expression,
5111 // implicitly converted to type T, where the converted
5112 // expression is a constant expression and the implicit conversion
5113 // sequence contains only [... list of conversions ...].
5114 ImplicitConversionSequence ICS =
5115 TryCopyInitialization(S, From, T,
5116 /*SuppressUserConversions=*/false,
5117 /*InOverloadResolution=*/false,
5118 /*AllowObjcWritebackConversion=*/false,
5119 /*AllowExplicit=*/false);
5120 StandardConversionSequence *SCS = nullptr;
5121 switch (ICS.getKind()) {
5122 case ImplicitConversionSequence::StandardConversion:
5123 SCS = &ICS.Standard;
5124 break;
5125 case ImplicitConversionSequence::UserDefinedConversion:
5126 // We are converting to a non-class type, so the Before sequence
5127 // must be trivial.
5128 SCS = &ICS.UserDefined.After;
5129 break;
5130 case ImplicitConversionSequence::AmbiguousConversion:
5131 case ImplicitConversionSequence::BadConversion:
5132 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5133 return S.Diag(From->getLocStart(),
5134 diag::err_typecheck_converted_constant_expression)
5135 << From->getType() << From->getSourceRange() << T;
5136 return ExprError();
5137
5138 case ImplicitConversionSequence::EllipsisConversion:
5139 llvm_unreachable("ellipsis conversion in converted constant expression")::llvm::llvm_unreachable_internal("ellipsis conversion in converted constant expression"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5139)
;
5140 }
5141
5142 // Check that we would only use permitted conversions.
5143 if (!CheckConvertedConstantConversions(S, *SCS)) {
5144 return S.Diag(From->getLocStart(),
5145 diag::err_typecheck_converted_constant_expression_disallowed)
5146 << From->getType() << From->getSourceRange() << T;
5147 }
5148 // [...] and where the reference binding (if any) binds directly.
5149 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5150 return S.Diag(From->getLocStart(),
5151 diag::err_typecheck_converted_constant_expression_indirect)
5152 << From->getType() << From->getSourceRange() << T;
5153 }
5154
5155 ExprResult Result =
5156 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5157 if (Result.isInvalid())
5158 return Result;
5159
5160 // Check for a narrowing implicit conversion.
5161 APValue PreNarrowingValue;
5162 QualType PreNarrowingType;
5163 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5164 PreNarrowingType)) {
5165 case NK_Variable_Narrowing:
5166 // Implicit conversion to a narrower type, and the value is not a constant
5167 // expression. We'll diagnose this in a moment.
5168 case NK_Not_Narrowing:
5169 break;
5170
5171 case NK_Constant_Narrowing:
5172 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5173 << CCE << /*Constant*/1
5174 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5175 break;
5176
5177 case NK_Type_Narrowing:
5178 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5179 << CCE << /*Constant*/0 << From->getType() << T;
5180 break;
5181 }
5182
5183 // Check the expression is a constant expression.
5184 SmallVector<PartialDiagnosticAt, 8> Notes;
5185 Expr::EvalResult Eval;
5186 Eval.Diag = &Notes;
5187
5188 if ((T->isReferenceType()
5189 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5190 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5191 (RequireInt && !Eval.Val.isInt())) {
5192 // The expression can't be folded, so we can't keep it at this position in
5193 // the AST.
5194 Result = ExprError();
5195 } else {
5196 Value = Eval.Val;
5197
5198 if (Notes.empty()) {
5199 // It's a constant expression.
5200 return Result;
5201 }
5202 }
5203
5204 // It's not a constant expression. Produce an appropriate diagnostic.
5205 if (Notes.size() == 1 &&
5206 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5207 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5208 else {
5209 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5210 << CCE << From->getSourceRange();
5211 for (unsigned I = 0; I < Notes.size(); ++I)
5212 S.Diag(Notes[I].first, Notes[I].second);
5213 }
5214 return ExprError();
5215}
5216
5217ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5218 APValue &Value, CCEKind CCE) {
5219 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5220}
5221
5222ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5223 llvm::APSInt &Value,
5224 CCEKind CCE) {
5225 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type")((T->isIntegralOrEnumerationType() && "unexpected converted const type"
) ? static_cast<void> (0) : __assert_fail ("T->isIntegralOrEnumerationType() && \"unexpected converted const type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5225, __PRETTY_FUNCTION__))
;
5226
5227 APValue V;
5228 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5229 if (!R.isInvalid())
5230 Value = V.getInt();
5231 return R;
5232}
5233
5234
5235/// dropPointerConversions - If the given standard conversion sequence
5236/// involves any pointer conversions, remove them. This may change
5237/// the result type of the conversion sequence.
5238static void dropPointerConversion(StandardConversionSequence &SCS) {
5239 if (SCS.Second == ICK_Pointer_Conversion) {
5240 SCS.Second = ICK_Identity;
5241 SCS.Third = ICK_Identity;
5242 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5243 }
5244}
5245
5246/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5247/// convert the expression From to an Objective-C pointer type.
5248static ImplicitConversionSequence
5249TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5250 // Do an implicit conversion to 'id'.
5251 QualType Ty = S.Context.getObjCIdType();
5252 ImplicitConversionSequence ICS
5253 = TryImplicitConversion(S, From, Ty,
5254 // FIXME: Are these flags correct?
5255 /*SuppressUserConversions=*/false,
5256 /*AllowExplicit=*/true,
5257 /*InOverloadResolution=*/false,
5258 /*CStyle=*/false,
5259 /*AllowObjCWritebackConversion=*/false,
5260 /*AllowObjCConversionOnExplicit=*/true);
5261
5262 // Strip off any final conversions to 'id'.
5263 switch (ICS.getKind()) {
5264 case ImplicitConversionSequence::BadConversion:
5265 case ImplicitConversionSequence::AmbiguousConversion:
5266 case ImplicitConversionSequence::EllipsisConversion:
5267 break;
5268
5269 case ImplicitConversionSequence::UserDefinedConversion:
5270 dropPointerConversion(ICS.UserDefined.After);
5271 break;
5272
5273 case ImplicitConversionSequence::StandardConversion:
5274 dropPointerConversion(ICS.Standard);
5275 break;
5276 }
5277
5278 return ICS;
5279}
5280
5281/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5282/// conversion of the expression From to an Objective-C pointer type.
5283ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5284 if (checkPlaceholderForOverload(*this, From))
5285 return ExprError();
5286
5287 QualType Ty = Context.getObjCIdType();
5288 ImplicitConversionSequence ICS =
5289 TryContextuallyConvertToObjCPointer(*this, From);
5290 if (!ICS.isBad())
5291 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5292 return ExprError();
5293}
5294
5295/// Determine whether the provided type is an integral type, or an enumeration
5296/// type of a permitted flavor.
5297bool Sema::ICEConvertDiagnoser::match(QualType T) {
5298 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5299 : T->isIntegralOrUnscopedEnumerationType();
5300}
5301
5302static ExprResult
5303diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5304 Sema::ContextualImplicitConverter &Converter,
5305 QualType T, UnresolvedSetImpl &ViableConversions) {
5306
5307 if (Converter.Suppress)
5308 return ExprError();
5309
5310 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5311 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5312 CXXConversionDecl *Conv =
5313 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5314 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5315 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5316 }
5317 return From;
5318}
5319
5320static bool
5321diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5322 Sema::ContextualImplicitConverter &Converter,
5323 QualType T, bool HadMultipleCandidates,
5324 UnresolvedSetImpl &ExplicitConversions) {
5325 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5326 DeclAccessPair Found = ExplicitConversions[0];
5327 CXXConversionDecl *Conversion =
5328 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5329
5330 // The user probably meant to invoke the given explicit
5331 // conversion; use it.
5332 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5333 std::string TypeStr;
5334 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5335
5336 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5337 << FixItHint::CreateInsertion(From->getLocStart(),
5338 "static_cast<" + TypeStr + ">(")
5339 << FixItHint::CreateInsertion(
5340 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5341 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5342
5343 // If we aren't in a SFINAE context, build a call to the
5344 // explicit conversion function.
5345 if (SemaRef.isSFINAEContext())
5346 return true;
5347
5348 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5349 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5350 HadMultipleCandidates);
5351 if (Result.isInvalid())
5352 return true;
5353 // Record usage of conversion in an implicit cast.
5354 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5355 CK_UserDefinedConversion, Result.get(),
5356 nullptr, Result.get()->getValueKind());
5357 }
5358 return false;
5359}
5360
5361static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5362 Sema::ContextualImplicitConverter &Converter,
5363 QualType T, bool HadMultipleCandidates,
5364 DeclAccessPair &Found) {
5365 CXXConversionDecl *Conversion =
5366 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5367 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5368
5369 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5370 if (!Converter.SuppressConversion) {
5371 if (SemaRef.isSFINAEContext())
5372 return true;
5373
5374 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5375 << From->getSourceRange();
5376 }
5377
5378 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5379 HadMultipleCandidates);
5380 if (Result.isInvalid())
5381 return true;
5382 // Record usage of conversion in an implicit cast.
5383 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5384 CK_UserDefinedConversion, Result.get(),
5385 nullptr, Result.get()->getValueKind());
5386 return false;
5387}
5388
5389static ExprResult finishContextualImplicitConversion(
5390 Sema &SemaRef, SourceLocation Loc, Expr *From,
5391 Sema::ContextualImplicitConverter &Converter) {
5392 if (!Converter.match(From->getType()) && !Converter.Suppress)
5393 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5394 << From->getSourceRange();
5395
5396 return SemaRef.DefaultLvalueConversion(From);
5397}
5398
5399static void
5400collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5401 UnresolvedSetImpl &ViableConversions,
5402 OverloadCandidateSet &CandidateSet) {
5403 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5404 DeclAccessPair FoundDecl = ViableConversions[I];
5405 NamedDecl *D = FoundDecl.getDecl();
5406 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5407 if (isa<UsingShadowDecl>(D))
5408 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5409
5410 CXXConversionDecl *Conv;
5411 FunctionTemplateDecl *ConvTemplate;
5412 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5413 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5414 else
5415 Conv = cast<CXXConversionDecl>(D);
5416
5417 if (ConvTemplate)
5418 SemaRef.AddTemplateConversionCandidate(
5419 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5420 /*AllowObjCConversionOnExplicit=*/false);
5421 else
5422 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5423 ToType, CandidateSet,
5424 /*AllowObjCConversionOnExplicit=*/false);
5425 }
5426}
5427
5428/// \brief Attempt to convert the given expression to a type which is accepted
5429/// by the given converter.
5430///
5431/// This routine will attempt to convert an expression of class type to a
5432/// type accepted by the specified converter. In C++11 and before, the class
5433/// must have a single non-explicit conversion function converting to a matching
5434/// type. In C++1y, there can be multiple such conversion functions, but only
5435/// one target type.
5436///
5437/// \param Loc The source location of the construct that requires the
5438/// conversion.
5439///
5440/// \param From The expression we're converting from.
5441///
5442/// \param Converter Used to control and diagnose the conversion process.
5443///
5444/// \returns The expression, converted to an integral or enumeration type if
5445/// successful.
5446ExprResult Sema::PerformContextualImplicitConversion(
5447 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5448 // We can't perform any more checking for type-dependent expressions.
5449 if (From->isTypeDependent())
5450 return From;
5451
5452 // Process placeholders immediately.
5453 if (From->hasPlaceholderType()) {
5454 ExprResult result = CheckPlaceholderExpr(From);
5455 if (result.isInvalid())
5456 return result;
5457 From = result.get();
5458 }
5459
5460 // If the expression already has a matching type, we're golden.
5461 QualType T = From->getType();
5462 if (Converter.match(T))
5463 return DefaultLvalueConversion(From);
5464
5465 // FIXME: Check for missing '()' if T is a function type?
5466
5467 // We can only perform contextual implicit conversions on objects of class
5468 // type.
5469 const RecordType *RecordTy = T->getAs<RecordType>();
5470 if (!RecordTy || !getLangOpts().CPlusPlus) {
5471 if (!Converter.Suppress)
5472 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5473 return From;
5474 }
5475
5476 // We must have a complete class type.
5477 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5478 ContextualImplicitConverter &Converter;
5479 Expr *From;
5480
5481 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5482 : Converter(Converter), From(From) {}
5483
5484 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5485 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5486 }
5487 } IncompleteDiagnoser(Converter, From);
5488
5489 if (Converter.Suppress ? !isCompleteType(Loc, T)
5490 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5491 return From;
5492
5493 // Look for a conversion to an integral or enumeration type.
5494 UnresolvedSet<4>
5495 ViableConversions; // These are *potentially* viable in C++1y.
5496 UnresolvedSet<4> ExplicitConversions;
5497 const auto &Conversions =
5498 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5499
5500 bool HadMultipleCandidates =
5501 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5502
5503 // To check that there is only one target type, in C++1y:
5504 QualType ToType;
5505 bool HasUniqueTargetType = true;
5506
5507 // Collect explicit or viable (potentially in C++1y) conversions.
5508 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5509 NamedDecl *D = (*I)->getUnderlyingDecl();
5510 CXXConversionDecl *Conversion;
5511 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5512 if (ConvTemplate) {
5513 if (getLangOpts().CPlusPlus14)
5514 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5515 else
5516 continue; // C++11 does not consider conversion operator templates(?).
5517 } else
5518 Conversion = cast<CXXConversionDecl>(D);
5519
5520 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5522, __PRETTY_FUNCTION__))
5521 "Conversion operator templates are considered potentially "(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5522, __PRETTY_FUNCTION__))
5522 "viable in C++1y")(((!ConvTemplate || getLangOpts().CPlusPlus14) && "Conversion operator templates are considered potentially "
"viable in C++1y") ? static_cast<void> (0) : __assert_fail
("(!ConvTemplate || getLangOpts().CPlusPlus14) && \"Conversion operator templates are considered potentially \" \"viable in C++1y\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5522, __PRETTY_FUNCTION__))
;
5523
5524 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5525 if (Converter.match(CurToType) || ConvTemplate) {
5526
5527 if (Conversion->isExplicit()) {
5528 // FIXME: For C++1y, do we need this restriction?
5529 // cf. diagnoseNoViableConversion()
5530 if (!ConvTemplate)
5531 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5532 } else {
5533 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5534 if (ToType.isNull())
5535 ToType = CurToType.getUnqualifiedType();
5536 else if (HasUniqueTargetType &&
5537 (CurToType.getUnqualifiedType() != ToType))
5538 HasUniqueTargetType = false;
5539 }
5540 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5541 }
5542 }
5543 }
5544
5545 if (getLangOpts().CPlusPlus14) {
5546 // C++1y [conv]p6:
5547 // ... An expression e of class type E appearing in such a context
5548 // is said to be contextually implicitly converted to a specified
5549 // type T and is well-formed if and only if e can be implicitly
5550 // converted to a type T that is determined as follows: E is searched
5551 // for conversion functions whose return type is cv T or reference to
5552 // cv T such that T is allowed by the context. There shall be
5553 // exactly one such T.
5554
5555 // If no unique T is found:
5556 if (ToType.isNull()) {
5557 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5558 HadMultipleCandidates,
5559 ExplicitConversions))
5560 return ExprError();
5561 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5562 }
5563
5564 // If more than one unique Ts are found:
5565 if (!HasUniqueTargetType)
5566 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5567 ViableConversions);
5568
5569 // If one unique T is found:
5570 // First, build a candidate set from the previously recorded
5571 // potentially viable conversions.
5572 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5573 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5574 CandidateSet);
5575
5576 // Then, perform overload resolution over the candidate set.
5577 OverloadCandidateSet::iterator Best;
5578 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5579 case OR_Success: {
5580 // Apply this conversion.
5581 DeclAccessPair Found =
5582 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5583 if (recordConversion(*this, Loc, From, Converter, T,
5584 HadMultipleCandidates, Found))
5585 return ExprError();
5586 break;
5587 }
5588 case OR_Ambiguous:
5589 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5590 ViableConversions);
5591 case OR_No_Viable_Function:
5592 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5593 HadMultipleCandidates,
5594 ExplicitConversions))
5595 return ExprError();
5596 // fall through 'OR_Deleted' case.
5597 case OR_Deleted:
5598 // We'll complain below about a non-integral condition type.
5599 break;
5600 }
5601 } else {
5602 switch (ViableConversions.size()) {
5603 case 0: {
5604 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5605 HadMultipleCandidates,
5606 ExplicitConversions))
5607 return ExprError();
5608
5609 // We'll complain below about a non-integral condition type.
5610 break;
5611 }
5612 case 1: {
5613 // Apply this conversion.
5614 DeclAccessPair Found = ViableConversions[0];
5615 if (recordConversion(*this, Loc, From, Converter, T,
5616 HadMultipleCandidates, Found))
5617 return ExprError();
5618 break;
5619 }
5620 default:
5621 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5622 ViableConversions);
5623 }
5624 }
5625
5626 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5627}
5628
5629/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5630/// an acceptable non-member overloaded operator for a call whose
5631/// arguments have types T1 (and, if non-empty, T2). This routine
5632/// implements the check in C++ [over.match.oper]p3b2 concerning
5633/// enumeration types.
5634static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5635 FunctionDecl *Fn,
5636 ArrayRef<Expr *> Args) {
5637 QualType T1 = Args[0]->getType();
5638 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5639
5640 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5641 return true;
5642
5643 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5644 return true;
5645
5646 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5647 if (Proto->getNumParams() < 1)
5648 return false;
5649
5650 if (T1->isEnumeralType()) {
5651 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5652 if (Context.hasSameUnqualifiedType(T1, ArgType))
5653 return true;
5654 }
5655
5656 if (Proto->getNumParams() < 2)
5657 return false;
5658
5659 if (!T2.isNull() && T2->isEnumeralType()) {
5660 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5661 if (Context.hasSameUnqualifiedType(T2, ArgType))
5662 return true;
5663 }
5664
5665 return false;
5666}
5667
5668/// AddOverloadCandidate - Adds the given function to the set of
5669/// candidate functions, using the given function call arguments. If
5670/// @p SuppressUserConversions, then don't allow user-defined
5671/// conversions via constructors or conversion operators.
5672///
5673/// \param PartialOverloading true if we are performing "partial" overloading
5674/// based on an incomplete set of function arguments. This feature is used by
5675/// code completion.
5676void
5677Sema::AddOverloadCandidate(FunctionDecl *Function,
5678 DeclAccessPair FoundDecl,
5679 ArrayRef<Expr *> Args,
5680 OverloadCandidateSet &CandidateSet,
5681 bool SuppressUserConversions,
5682 bool PartialOverloading,
5683 bool AllowExplicit) {
5684 const FunctionProtoType *Proto
5685 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5686 assert(Proto && "Functions without a prototype cannot be overloaded")((Proto && "Functions without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Functions without a prototype cannot be overloaded\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5686, __PRETTY_FUNCTION__))
;
5687 assert(!Function->getDescribedFunctionTemplate() &&((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5688, __PRETTY_FUNCTION__))
5688 "Use AddTemplateOverloadCandidate for function templates")((!Function->getDescribedFunctionTemplate() && "Use AddTemplateOverloadCandidate for function templates"
) ? static_cast<void> (0) : __assert_fail ("!Function->getDescribedFunctionTemplate() && \"Use AddTemplateOverloadCandidate for function templates\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5688, __PRETTY_FUNCTION__))
;
5689
5690 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5691 if (!isa<CXXConstructorDecl>(Method)) {
5692 // If we get here, it's because we're calling a member function
5693 // that is named without a member access expression (e.g.,
5694 // "this->f") that was either written explicitly or created
5695 // implicitly. This can happen with a qualified call to a member
5696 // function, e.g., X::f(). We use an empty type for the implied
5697 // object argument (C++ [over.call.func]p3), and the acting context
5698 // is irrelevant.
5699 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5700 QualType(), Expr::Classification::makeSimpleLValue(),
5701 Args, CandidateSet, SuppressUserConversions,
5702 PartialOverloading);
5703 return;
5704 }
5705 // We treat a constructor like a non-member function, since its object
5706 // argument doesn't participate in overload resolution.
5707 }
5708
5709 if (!CandidateSet.isNewCandidate(Function))
5710 return;
5711
5712 // C++ [over.match.oper]p3:
5713 // if no operand has a class type, only those non-member functions in the
5714 // lookup set that have a first parameter of type T1 or "reference to
5715 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5716 // is a right operand) a second parameter of type T2 or "reference to
5717 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5718 // candidate functions.
5719 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5720 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5721 return;
5722
5723 // C++11 [class.copy]p11: [DR1402]
5724 // A defaulted move constructor that is defined as deleted is ignored by
5725 // overload resolution.
5726 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5727 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5728 Constructor->isMoveConstructor())
5729 return;
5730
5731 // Overload resolution is always an unevaluated context.
5732 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5733
5734 // Add this candidate
5735 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5736 Candidate.FoundDecl = FoundDecl;
5737 Candidate.Function = Function;
5738 Candidate.Viable = true;
5739 Candidate.IsSurrogate = false;
5740 Candidate.IgnoreObjectArgument = false;
5741 Candidate.ExplicitCallArguments = Args.size();
5742
5743 if (Constructor) {
5744 // C++ [class.copy]p3:
5745 // A member function template is never instantiated to perform the copy
5746 // of a class object to an object of its class type.
5747 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5748 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5749 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5750 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5751 ClassType))) {
5752 Candidate.Viable = false;
5753 Candidate.FailureKind = ovl_fail_illegal_constructor;
5754 return;
5755 }
5756 }
5757
5758 unsigned NumParams = Proto->getNumParams();
5759
5760 // (C++ 13.3.2p2): A candidate function having fewer than m
5761 // parameters is viable only if it has an ellipsis in its parameter
5762 // list (8.3.5).
5763 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5764 !Proto->isVariadic()) {
5765 Candidate.Viable = false;
5766 Candidate.FailureKind = ovl_fail_too_many_arguments;
5767 return;
5768 }
5769
5770 // (C++ 13.3.2p2): A candidate function having more than m parameters
5771 // is viable only if the (m+1)st parameter has a default argument
5772 // (8.3.6). For the purposes of overload resolution, the
5773 // parameter list is truncated on the right, so that there are
5774 // exactly m parameters.
5775 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5776 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5777 // Not enough arguments.
5778 Candidate.Viable = false;
5779 Candidate.FailureKind = ovl_fail_too_few_arguments;
5780 return;
5781 }
5782
5783 // (CUDA B.1): Check for invalid calls between targets.
5784 if (getLangOpts().CUDA)
5785 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5786 // Skip the check for callers that are implicit members, because in this
5787 // case we may not yet know what the member's target is; the target is
5788 // inferred for the member automatically, based on the bases and fields of
5789 // the class.
5790 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
5791 Candidate.Viable = false;
5792 Candidate.FailureKind = ovl_fail_bad_target;
5793 return;
5794 }
5795
5796 // Determine the implicit conversion sequences for each of the
5797 // arguments.
5798 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5799 if (ArgIdx < NumParams) {
5800 // (C++ 13.3.2p3): for F to be a viable function, there shall
5801 // exist for each argument an implicit conversion sequence
5802 // (13.3.3.1) that converts that argument to the corresponding
5803 // parameter of F.
5804 QualType ParamType = Proto->getParamType(ArgIdx);
5805 Candidate.Conversions[ArgIdx]
5806 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5807 SuppressUserConversions,
5808 /*InOverloadResolution=*/true,
5809 /*AllowObjCWritebackConversion=*/
5810 getLangOpts().ObjCAutoRefCount,
5811 AllowExplicit);
5812 if (Candidate.Conversions[ArgIdx].isBad()) {
5813 Candidate.Viable = false;
5814 Candidate.FailureKind = ovl_fail_bad_conversion;
5815 return;
5816 }
5817 } else {
5818 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5819 // argument for which there is no corresponding parameter is
5820 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5821 Candidate.Conversions[ArgIdx].setEllipsis();
5822 }
5823 }
5824
5825 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5826 Candidate.Viable = false;
5827 Candidate.FailureKind = ovl_fail_enable_if;
5828 Candidate.DeductionFailure.Data = FailedAttr;
5829 return;
5830 }
5831}
5832
5833ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
5834 bool IsInstance) {
5835 SmallVector<ObjCMethodDecl*, 4> Methods;
5836 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5837 return nullptr;
5838
5839 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5840 bool Match = true;
5841 ObjCMethodDecl *Method = Methods[b];
5842 unsigned NumNamedArgs = Sel.getNumArgs();
5843 // Method might have more arguments than selector indicates. This is due
5844 // to addition of c-style arguments in method.
5845 if (Method->param_size() > NumNamedArgs)
5846 NumNamedArgs = Method->param_size();
5847 if (Args.size() < NumNamedArgs)
5848 continue;
5849
5850 for (unsigned i = 0; i < NumNamedArgs; i++) {
5851 // We can't do any type-checking on a type-dependent argument.
5852 if (Args[i]->isTypeDependent()) {
5853 Match = false;
5854 break;
5855 }
5856
5857 ParmVarDecl *param = Method->parameters()[i];
5858 Expr *argExpr = Args[i];
5859 assert(argExpr && "SelectBestMethod(): missing expression")((argExpr && "SelectBestMethod(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("argExpr && \"SelectBestMethod(): missing expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 5859, __PRETTY_FUNCTION__))
;
5860
5861 // Strip the unbridged-cast placeholder expression off unless it's
5862 // a consumed argument.
5863 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5864 !param->hasAttr<CFConsumedAttr>())
5865 argExpr = stripARCUnbridgedCast(argExpr);
5866
5867 // If the parameter is __unknown_anytype, move on to the next method.
5868 if (param->getType() == Context.UnknownAnyTy) {
5869 Match = false;
5870 break;
5871 }
5872
5873 ImplicitConversionSequence ConversionState
5874 = TryCopyInitialization(*this, argExpr, param->getType(),
5875 /*SuppressUserConversions*/false,
5876 /*InOverloadResolution=*/true,
5877 /*AllowObjCWritebackConversion=*/
5878 getLangOpts().ObjCAutoRefCount,
5879 /*AllowExplicit*/false);
5880 if (ConversionState.isBad()) {
5881 Match = false;
5882 break;
5883 }
5884 }
5885 // Promote additional arguments to variadic methods.
5886 if (Match && Method->isVariadic()) {
5887 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5888 if (Args[i]->isTypeDependent()) {
5889 Match = false;
5890 break;
5891 }
5892 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5893 nullptr);
5894 if (Arg.isInvalid()) {
5895 Match = false;
5896 break;
5897 }
5898 }
5899 } else {
5900 // Check for extra arguments to non-variadic methods.
5901 if (Args.size() != NumNamedArgs)
5902 Match = false;
5903 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5904 // Special case when selectors have no argument. In this case, select
5905 // one with the most general result type of 'id'.
5906 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5907 QualType ReturnT = Methods[b]->getReturnType();
5908 if (ReturnT->isObjCIdType())
5909 return Methods[b];
5910 }
5911 }
5912 }
5913
5914 if (Match)
5915 return Method;
5916 }
5917 return nullptr;
5918}
5919
5920// specific_attr_iterator iterates over enable_if attributes in reverse, and
5921// enable_if is order-sensitive. As a result, we need to reverse things
5922// sometimes. Size of 4 elements is arbitrary.
5923static SmallVector<EnableIfAttr *, 4>
5924getOrderedEnableIfAttrs(const FunctionDecl *Function) {
5925 SmallVector<EnableIfAttr *, 4> Result;
5926 if (!Function->hasAttrs())
5927 return Result;
5928
5929 const auto &FuncAttrs = Function->getAttrs();
5930 for (Attr *Attr : FuncAttrs)
5931 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
5932 Result.push_back(EnableIf);
5933
5934 std::reverse(Result.begin(), Result.end());
5935 return Result;
5936}
5937
5938EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5939 bool MissingImplicitThis) {
5940 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
5941 if (EnableIfAttrs.empty())
5942 return nullptr;
5943
5944 SFINAETrap Trap(*this);
5945 SmallVector<Expr *, 16> ConvertedArgs;
5946 bool InitializationFailed = false;
5947 bool ContainsValueDependentExpr = false;
5948
5949 // Convert the arguments.
5950 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5951 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5952 !cast<CXXMethodDecl>(Function)->isStatic() &&
5953 !isa<CXXConstructorDecl>(Function)) {
5954 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5955 ExprResult R =
5956 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5957 Method, Method);
5958 if (R.isInvalid()) {
5959 InitializationFailed = true;
5960 break;
5961 }
5962 ContainsValueDependentExpr |= R.get()->isValueDependent();
5963 ConvertedArgs.push_back(R.get());
5964 } else {
5965 ExprResult R =
5966 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5967 Context,
5968 Function->getParamDecl(i)),
5969 SourceLocation(),
5970 Args[i]);
5971 if (R.isInvalid()) {
5972 InitializationFailed = true;
5973 break;
5974 }
5975 ContainsValueDependentExpr |= R.get()->isValueDependent();
5976 ConvertedArgs.push_back(R.get());
5977 }
5978 }
5979
5980 if (InitializationFailed || Trap.hasErrorOccurred())
5981 return EnableIfAttrs[0];
5982
5983 // Push default arguments if needed.
5984 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5985 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5986 ParmVarDecl *P = Function->getParamDecl(i);
5987 ExprResult R = PerformCopyInitialization(
5988 InitializedEntity::InitializeParameter(Context,
5989 Function->getParamDecl(i)),
5990 SourceLocation(),
5991 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5992 : P->getDefaultArg());
5993 if (R.isInvalid()) {
5994 InitializationFailed = true;
5995 break;
5996 }
5997 ContainsValueDependentExpr |= R.get()->isValueDependent();
5998 ConvertedArgs.push_back(R.get());
5999 }
6000
6001 if (InitializationFailed || Trap.hasErrorOccurred())
6002 return EnableIfAttrs[0];
6003 }
6004
6005 for (auto *EIA : EnableIfAttrs) {
6006 APValue Result;
6007 if (EIA->getCond()->isValueDependent()) {
6008 // Don't even try now, we'll examine it after instantiation.
6009 continue;
6010 }
6011
6012 if (!EIA->getCond()->EvaluateWithSubstitution(
6013 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
6014 if (!ContainsValueDependentExpr)
6015 return EIA;
6016 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
6017 return EIA;
6018 }
6019 }
6020 return nullptr;
6021}
6022
6023/// \brief Add all of the function declarations in the given function set to
6024/// the overload candidate set.
6025void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6026 ArrayRef<Expr *> Args,
6027 OverloadCandidateSet& CandidateSet,
6028 TemplateArgumentListInfo *ExplicitTemplateArgs,
6029 bool SuppressUserConversions,
6030 bool PartialOverloading) {
6031 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6032 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6033 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6034 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6035 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6036 cast<CXXMethodDecl>(FD)->getParent(),
6037 Args[0]->getType(), Args[0]->Classify(Context),
6038 Args.slice(1), CandidateSet,
6039 SuppressUserConversions, PartialOverloading);
6040 else
6041 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6042 SuppressUserConversions, PartialOverloading);
6043 } else {
6044 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6045 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6046 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6047 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6048 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6049 ExplicitTemplateArgs,
6050 Args[0]->getType(),
6051 Args[0]->Classify(Context), Args.slice(1),
6052 CandidateSet, SuppressUserConversions,
6053 PartialOverloading);
6054 else
6055 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6056 ExplicitTemplateArgs, Args,
6057 CandidateSet, SuppressUserConversions,
6058 PartialOverloading);
6059 }
6060 }
6061}
6062
6063/// AddMethodCandidate - Adds a named decl (which is some kind of
6064/// method) as a method candidate to the given overload set.
6065void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6066 QualType ObjectType,
6067 Expr::Classification ObjectClassification,
6068 ArrayRef<Expr *> Args,
6069 OverloadCandidateSet& CandidateSet,
6070 bool SuppressUserConversions) {
6071 NamedDecl *Decl = FoundDecl.getDecl();
6072 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6073
6074 if (isa<UsingShadowDecl>(Decl))
6075 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6076
6077 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6078 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6079, __PRETTY_FUNCTION__))
6079 "Expected a member function template")((isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
"Expected a member function template") ? static_cast<void
> (0) : __assert_fail ("isa<CXXMethodDecl>(TD->getTemplatedDecl()) && \"Expected a member function template\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6079, __PRETTY_FUNCTION__))
;
6080 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6081 /*ExplicitArgs*/ nullptr,
6082 ObjectType, ObjectClassification,
6083 Args, CandidateSet,
6084 SuppressUserConversions);
6085 } else {
6086 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6087 ObjectType, ObjectClassification,
6088 Args,
6089 CandidateSet, SuppressUserConversions);
6090 }
6091}
6092
6093/// AddMethodCandidate - Adds the given C++ member function to the set
6094/// of candidate functions, using the given function call arguments
6095/// and the object argument (@c Object). For example, in a call
6096/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6097/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6098/// allow user-defined conversions via constructors or conversion
6099/// operators.
6100void
6101Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6102 CXXRecordDecl *ActingContext, QualType ObjectType,
6103 Expr::Classification ObjectClassification,
6104 ArrayRef<Expr *> Args,
6105 OverloadCandidateSet &CandidateSet,
6106 bool SuppressUserConversions,
6107 bool PartialOverloading) {
6108 const FunctionProtoType *Proto
6109 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6110 assert(Proto && "Methods without a prototype cannot be overloaded")((Proto && "Methods without a prototype cannot be overloaded"
) ? static_cast<void> (0) : __assert_fail ("Proto && \"Methods without a prototype cannot be overloaded\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6110, __PRETTY_FUNCTION__))
;
6111 assert(!isa<CXXConstructorDecl>(Method) &&((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6112, __PRETTY_FUNCTION__))
6112 "Use AddOverloadCandidate for constructors")((!isa<CXXConstructorDecl>(Method) && "Use AddOverloadCandidate for constructors"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXConstructorDecl>(Method) && \"Use AddOverloadCandidate for constructors\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6112, __PRETTY_FUNCTION__))
;
6113
6114 if (!CandidateSet.isNewCandidate(Method))
6115 return;
6116
6117 // C++11 [class.copy]p23: [DR1402]
6118 // A defaulted move assignment operator that is defined as deleted is
6119 // ignored by overload resolution.
6120 if (Method->isDefaulted() && Method->isDeleted() &&
6121 Method->isMoveAssignmentOperator())
6122 return;
6123
6124 // Overload resolution is always an unevaluated context.
6125 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6126
6127 // Add this candidate
6128 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6129 Candidate.FoundDecl = FoundDecl;
6130 Candidate.Function = Method;
6131 Candidate.IsSurrogate = false;
6132 Candidate.IgnoreObjectArgument = false;
6133 Candidate.ExplicitCallArguments = Args.size();
6134
6135 unsigned NumParams = Proto->getNumParams();
6136
6137 // (C++ 13.3.2p2): A candidate function having fewer than m
6138 // parameters is viable only if it has an ellipsis in its parameter
6139 // list (8.3.5).
6140 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6141 !Proto->isVariadic()) {
6142 Candidate.Viable = false;
6143 Candidate.FailureKind = ovl_fail_too_many_arguments;
6144 return;
6145 }
6146
6147 // (C++ 13.3.2p2): A candidate function having more than m parameters
6148 // is viable only if the (m+1)st parameter has a default argument
6149 // (8.3.6). For the purposes of overload resolution, the
6150 // parameter list is truncated on the right, so that there are
6151 // exactly m parameters.
6152 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6153 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6154 // Not enough arguments.
6155 Candidate.Viable = false;
6156 Candidate.FailureKind = ovl_fail_too_few_arguments;
6157 return;
6158 }
6159
6160 Candidate.Viable = true;
6161
6162 if (Method->isStatic() || ObjectType.isNull())
6163 // The implicit object argument is ignored.
6164 Candidate.IgnoreObjectArgument = true;
6165 else {
6166 // Determine the implicit conversion sequence for the object
6167 // parameter.
6168 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6169 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6170 Method, ActingContext);
6171 if (Candidate.Conversions[0].isBad()) {
6172 Candidate.Viable = false;
6173 Candidate.FailureKind = ovl_fail_bad_conversion;
6174 return;
6175 }
6176 }
6177
6178 // (CUDA B.1): Check for invalid calls between targets.
6179 if (getLangOpts().CUDA)
6180 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6181 if (CheckCUDATarget(Caller, Method)) {
6182 Candidate.Viable = false;
6183 Candidate.FailureKind = ovl_fail_bad_target;
6184 return;
6185 }
6186
6187 // Determine the implicit conversion sequences for each of the
6188 // arguments.
6189 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6190 if (ArgIdx < NumParams) {
6191 // (C++ 13.3.2p3): for F to be a viable function, there shall
6192 // exist for each argument an implicit conversion sequence
6193 // (13.3.3.1) that converts that argument to the corresponding
6194 // parameter of F.
6195 QualType ParamType = Proto->getParamType(ArgIdx);
6196 Candidate.Conversions[ArgIdx + 1]
6197 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6198 SuppressUserConversions,
6199 /*InOverloadResolution=*/true,
6200 /*AllowObjCWritebackConversion=*/
6201 getLangOpts().ObjCAutoRefCount);
6202 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6203 Candidate.Viable = false;
6204 Candidate.FailureKind = ovl_fail_bad_conversion;
6205 return;
6206 }
6207 } else {
6208 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6209 // argument for which there is no corresponding parameter is
6210 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6211 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6212 }
6213 }
6214
6215 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6216 Candidate.Viable = false;
6217 Candidate.FailureKind = ovl_fail_enable_if;
6218 Candidate.DeductionFailure.Data = FailedAttr;
6219 return;
6220 }
6221}
6222
6223/// \brief Add a C++ member function template as a candidate to the candidate
6224/// set, using template argument deduction to produce an appropriate member
6225/// function template specialization.
6226void
6227Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6228 DeclAccessPair FoundDecl,
6229 CXXRecordDecl *ActingContext,
6230 TemplateArgumentListInfo *ExplicitTemplateArgs,
6231 QualType ObjectType,
6232 Expr::Classification ObjectClassification,
6233 ArrayRef<Expr *> Args,
6234 OverloadCandidateSet& CandidateSet,
6235 bool SuppressUserConversions,
6236 bool PartialOverloading) {
6237 if (!CandidateSet.isNewCandidate(MethodTmpl))
6238 return;
6239
6240 // C++ [over.match.funcs]p7:
6241 // In each case where a candidate is a function template, candidate
6242 // function template specializations are generated using template argument
6243 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6244 // candidate functions in the usual way.113) A given name can refer to one
6245 // or more function templates and also to a set of overloaded non-template
6246 // functions. In such a case, the candidate functions generated from each
6247 // function template are combined with the set of non-template candidate
6248 // functions.
6249 TemplateDeductionInfo Info(CandidateSet.getLocation());
6250 FunctionDecl *Specialization = nullptr;
6251 if (TemplateDeductionResult Result
6252 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6253 Specialization, Info, PartialOverloading)) {
6254 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6255 Candidate.FoundDecl = FoundDecl;
6256 Candidate.Function = MethodTmpl->getTemplatedDecl();
6257 Candidate.Viable = false;
6258 Candidate.FailureKind = ovl_fail_bad_deduction;
6259 Candidate.IsSurrogate = false;
6260 Candidate.IgnoreObjectArgument = false;
6261 Candidate.ExplicitCallArguments = Args.size();
6262 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6263 Info);
6264 return;
6265 }
6266
6267 // Add the function template specialization produced by template argument
6268 // deduction as a candidate.
6269 assert(Specialization && "Missing member function template specialization?")((Specialization && "Missing member function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing member function template specialization?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6269, __PRETTY_FUNCTION__))
;
6270 assert(isa<CXXMethodDecl>(Specialization) &&((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6271, __PRETTY_FUNCTION__))
6271 "Specialization is not a member function?")((isa<CXXMethodDecl>(Specialization) && "Specialization is not a member function?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXMethodDecl>(Specialization) && \"Specialization is not a member function?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6271, __PRETTY_FUNCTION__))
;
6272 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6273 ActingContext, ObjectType, ObjectClassification, Args,
6274 CandidateSet, SuppressUserConversions, PartialOverloading);
6275}
6276
6277/// \brief Add a C++ function template specialization as a candidate
6278/// in the candidate set, using template argument deduction to produce
6279/// an appropriate function template specialization.
6280void
6281Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6282 DeclAccessPair FoundDecl,
6283 TemplateArgumentListInfo *ExplicitTemplateArgs,
6284 ArrayRef<Expr *> Args,
6285 OverloadCandidateSet& CandidateSet,
6286 bool SuppressUserConversions,
6287 bool PartialOverloading) {
6288 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6289 return;
6290
6291 // C++ [over.match.funcs]p7:
6292 // In each case where a candidate is a function template, candidate
6293 // function template specializations are generated using template argument
6294 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6295 // candidate functions in the usual way.113) A given name can refer to one
6296 // or more function templates and also to a set of overloaded non-template
6297 // functions. In such a case, the candidate functions generated from each
6298 // function template are combined with the set of non-template candidate
6299 // functions.
6300 TemplateDeductionInfo Info(CandidateSet.getLocation());
6301 FunctionDecl *Specialization = nullptr;
6302 if (TemplateDeductionResult Result
6303 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6304 Specialization, Info, PartialOverloading)) {
6305 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6306 Candidate.FoundDecl = FoundDecl;
6307 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6308 Candidate.Viable = false;
6309 Candidate.FailureKind = ovl_fail_bad_deduction;
6310 Candidate.IsSurrogate = false;
6311 Candidate.IgnoreObjectArgument = false;
6312 Candidate.ExplicitCallArguments = Args.size();
6313 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6314 Info);
6315 return;
6316 }
6317
6318 // Add the function template specialization produced by template argument
6319 // deduction as a candidate.
6320 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6320, __PRETTY_FUNCTION__))
;
6321 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6322 SuppressUserConversions, PartialOverloading);
6323}
6324
6325/// Determine whether this is an allowable conversion from the result
6326/// of an explicit conversion operator to the expected type, per C++
6327/// [over.match.conv]p1 and [over.match.ref]p1.
6328///
6329/// \param ConvType The return type of the conversion function.
6330///
6331/// \param ToType The type we are converting to.
6332///
6333/// \param AllowObjCPointerConversion Allow a conversion from one
6334/// Objective-C pointer to another.
6335///
6336/// \returns true if the conversion is allowable, false otherwise.
6337static bool isAllowableExplicitConversion(Sema &S,
6338 QualType ConvType, QualType ToType,
6339 bool AllowObjCPointerConversion) {
6340 QualType ToNonRefType = ToType.getNonReferenceType();
6341
6342 // Easy case: the types are the same.
6343 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6344 return true;
6345
6346 // Allow qualification conversions.
6347 bool ObjCLifetimeConversion;
6348 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6349 ObjCLifetimeConversion))
6350 return true;
6351
6352 // If we're not allowed to consider Objective-C pointer conversions,
6353 // we're done.
6354 if (!AllowObjCPointerConversion)
6355 return false;
6356
6357 // Is this an Objective-C pointer conversion?
6358 bool IncompatibleObjC = false;
6359 QualType ConvertedType;
6360 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6361 IncompatibleObjC);
6362}
6363
6364/// AddConversionCandidate - Add a C++ conversion function as a
6365/// candidate in the candidate set (C++ [over.match.conv],
6366/// C++ [over.match.copy]). From is the expression we're converting from,
6367/// and ToType is the type that we're eventually trying to convert to
6368/// (which may or may not be the same type as the type that the
6369/// conversion function produces).
6370void
6371Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6372 DeclAccessPair FoundDecl,
6373 CXXRecordDecl *ActingContext,
6374 Expr *From, QualType ToType,
6375 OverloadCandidateSet& CandidateSet,
6376 bool AllowObjCConversionOnExplicit) {
6377 assert(!Conversion->getDescribedFunctionTemplate() &&((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6378, __PRETTY_FUNCTION__))
6378 "Conversion function templates use AddTemplateConversionCandidate")((!Conversion->getDescribedFunctionTemplate() && "Conversion function templates use AddTemplateConversionCandidate"
) ? static_cast<void> (0) : __assert_fail ("!Conversion->getDescribedFunctionTemplate() && \"Conversion function templates use AddTemplateConversionCandidate\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6378, __PRETTY_FUNCTION__))
;
6379 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6380 if (!CandidateSet.isNewCandidate(Conversion))
6381 return;
6382
6383 // If the conversion function has an undeduced return type, trigger its
6384 // deduction now.
6385 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6386 if (DeduceReturnType(Conversion, From->getExprLoc()))
6387 return;
6388 ConvType = Conversion->getConversionType().getNonReferenceType();
6389 }
6390
6391 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6392 // operator is only a candidate if its return type is the target type or
6393 // can be converted to the target type with a qualification conversion.
6394 if (Conversion->isExplicit() &&
6395 !isAllowableExplicitConversion(*this, ConvType, ToType,
6396 AllowObjCConversionOnExplicit))
6397 return;
6398
6399 // Overload resolution is always an unevaluated context.
6400 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6401
6402 // Add this candidate
6403 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6404 Candidate.FoundDecl = FoundDecl;
6405 Candidate.Function = Conversion;
6406 Candidate.IsSurrogate = false;
6407 Candidate.IgnoreObjectArgument = false;
6408 Candidate.FinalConversion.setAsIdentityConversion();
6409 Candidate.FinalConversion.setFromType(ConvType);
6410 Candidate.FinalConversion.setAllToTypes(ToType);
6411 Candidate.Viable = true;
6412 Candidate.ExplicitCallArguments = 1;
6413
6414 // C++ [over.match.funcs]p4:
6415 // For conversion functions, the function is considered to be a member of
6416 // the class of the implicit implied object argument for the purpose of
6417 // defining the type of the implicit object parameter.
6418 //
6419 // Determine the implicit conversion sequence for the implicit
6420 // object parameter.
6421 QualType ImplicitParamType = From->getType();
6422 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6423 ImplicitParamType = FromPtrType->getPointeeType();
6424 CXXRecordDecl *ConversionContext
6425 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6426
6427 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6428 *this, CandidateSet.getLocation(), From->getType(),
6429 From->Classify(Context), Conversion, ConversionContext);
6430
6431 if (Candidate.Conversions[0].isBad()) {
6432 Candidate.Viable = false;
6433 Candidate.FailureKind = ovl_fail_bad_conversion;
6434 return;
6435 }
6436
6437 // We won't go through a user-defined type conversion function to convert a
6438 // derived to base as such conversions are given Conversion Rank. They only
6439 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6440 QualType FromCanon
6441 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6442 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6443 if (FromCanon == ToCanon ||
6444 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6445 Candidate.Viable = false;
6446 Candidate.FailureKind = ovl_fail_trivial_conversion;
6447 return;
6448 }
6449
6450 // To determine what the conversion from the result of calling the
6451 // conversion function to the type we're eventually trying to
6452 // convert to (ToType), we need to synthesize a call to the
6453 // conversion function and attempt copy initialization from it. This
6454 // makes sure that we get the right semantics with respect to
6455 // lvalues/rvalues and the type. Fortunately, we can allocate this
6456 // call on the stack and we don't need its arguments to be
6457 // well-formed.
6458 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6459 VK_LValue, From->getLocStart());
6460 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6461 Context.getPointerType(Conversion->getType()),
6462 CK_FunctionToPointerDecay,
6463 &ConversionRef, VK_RValue);
6464
6465 QualType ConversionType = Conversion->getConversionType();
6466 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6467 Candidate.Viable = false;
6468 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6469 return;
6470 }
6471
6472 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6473
6474 // Note that it is safe to allocate CallExpr on the stack here because
6475 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6476 // allocator).
6477 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6478 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6479 From->getLocStart());
6480 ImplicitConversionSequence ICS =
6481 TryCopyInitialization(*this, &Call, ToType,
6482 /*SuppressUserConversions=*/true,
6483 /*InOverloadResolution=*/false,
6484 /*AllowObjCWritebackConversion=*/false);
6485
6486 switch (ICS.getKind()) {
6487 case ImplicitConversionSequence::StandardConversion:
6488 Candidate.FinalConversion = ICS.Standard;
6489
6490 // C++ [over.ics.user]p3:
6491 // If the user-defined conversion is specified by a specialization of a
6492 // conversion function template, the second standard conversion sequence
6493 // shall have exact match rank.
6494 if (Conversion->getPrimaryTemplate() &&
6495 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6496 Candidate.Viable = false;
6497 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6498 return;
6499 }
6500
6501 // C++0x [dcl.init.ref]p5:
6502 // In the second case, if the reference is an rvalue reference and
6503 // the second standard conversion sequence of the user-defined
6504 // conversion sequence includes an lvalue-to-rvalue conversion, the
6505 // program is ill-formed.
6506 if (ToType->isRValueReferenceType() &&
6507 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6508 Candidate.Viable = false;
6509 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6510 return;
6511 }
6512 break;
6513
6514 case ImplicitConversionSequence::BadConversion:
6515 Candidate.Viable = false;
6516 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6517 return;
6518
6519 default:
6520 llvm_unreachable(::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6521)
6521 "Can only end up with a standard conversion sequence or failure")::llvm::llvm_unreachable_internal("Can only end up with a standard conversion sequence or failure"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6521)
;
6522 }
6523
6524 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6525 Candidate.Viable = false;
6526 Candidate.FailureKind = ovl_fail_enable_if;
6527 Candidate.DeductionFailure.Data = FailedAttr;
6528 return;
6529 }
6530}
6531
6532/// \brief Adds a conversion function template specialization
6533/// candidate to the overload set, using template argument deduction
6534/// to deduce the template arguments of the conversion function
6535/// template from the type that we are converting to (C++
6536/// [temp.deduct.conv]).
6537void
6538Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6539 DeclAccessPair FoundDecl,
6540 CXXRecordDecl *ActingDC,
6541 Expr *From, QualType ToType,
6542 OverloadCandidateSet &CandidateSet,
6543 bool AllowObjCConversionOnExplicit) {
6544 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6545, __PRETTY_FUNCTION__))
6545 "Only conversion function templates permitted here")((isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl
()) && "Only conversion function templates permitted here"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && \"Only conversion function templates permitted here\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6545, __PRETTY_FUNCTION__))
;
6546
6547 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6548 return;
6549
6550 TemplateDeductionInfo Info(CandidateSet.getLocation());
6551 CXXConversionDecl *Specialization = nullptr;
6552 if (TemplateDeductionResult Result
6553 = DeduceTemplateArguments(FunctionTemplate, ToType,
6554 Specialization, Info)) {
6555 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6556 Candidate.FoundDecl = FoundDecl;
6557 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6558 Candidate.Viable = false;
6559 Candidate.FailureKind = ovl_fail_bad_deduction;
6560 Candidate.IsSurrogate = false;
6561 Candidate.IgnoreObjectArgument = false;
6562 Candidate.ExplicitCallArguments = 1;
6563 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6564 Info);
6565 return;
6566 }
6567
6568 // Add the conversion function template specialization produced by
6569 // template argument deduction as a candidate.
6570 assert(Specialization && "Missing function template specialization?")((Specialization && "Missing function template specialization?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"Missing function template specialization?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6570, __PRETTY_FUNCTION__))
;
6571 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6572 CandidateSet, AllowObjCConversionOnExplicit);
6573}
6574
6575/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6576/// converts the given @c Object to a function pointer via the
6577/// conversion function @c Conversion, and then attempts to call it
6578/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6579/// the type of function that we'll eventually be calling.
6580void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6581 DeclAccessPair FoundDecl,
6582 CXXRecordDecl *ActingContext,
6583 const FunctionProtoType *Proto,
6584 Expr *Object,
6585 ArrayRef<Expr *> Args,
6586 OverloadCandidateSet& CandidateSet) {
6587 if (!CandidateSet.isNewCandidate(Conversion))
6588 return;
6589
6590 // Overload resolution is always an unevaluated context.
6591 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6592
6593 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6594 Candidate.FoundDecl = FoundDecl;
6595 Candidate.Function = nullptr;
6596 Candidate.Surrogate = Conversion;
6597 Candidate.Viable = true;
6598 Candidate.IsSurrogate = true;
6599 Candidate.IgnoreObjectArgument = false;
6600 Candidate.ExplicitCallArguments = Args.size();
6601
6602 // Determine the implicit conversion sequence for the implicit
6603 // object parameter.
6604 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6605 *this, CandidateSet.getLocation(), Object->getType(),
6606 Object->Classify(Context), Conversion, ActingContext);
6607 if (ObjectInit.isBad()) {
6608 Candidate.Viable = false;
6609 Candidate.FailureKind = ovl_fail_bad_conversion;
6610 Candidate.Conversions[0] = ObjectInit;
6611 return;
6612 }
6613
6614 // The first conversion is actually a user-defined conversion whose
6615 // first conversion is ObjectInit's standard conversion (which is
6616 // effectively a reference binding). Record it as such.
6617 Candidate.Conversions[0].setUserDefined();
6618 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6619 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6620 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6621 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6622 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6623 Candidate.Conversions[0].UserDefined.After
6624 = Candidate.Conversions[0].UserDefined.Before;
6625 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6626
6627 // Find the
6628 unsigned NumParams = Proto->getNumParams();
6629
6630 // (C++ 13.3.2p2): A candidate function having fewer than m
6631 // parameters is viable only if it has an ellipsis in its parameter
6632 // list (8.3.5).
6633 if (Args.size() > NumParams && !Proto->isVariadic()) {
6634 Candidate.Viable = false;
6635 Candidate.FailureKind = ovl_fail_too_many_arguments;
6636 return;
6637 }
6638
6639 // Function types don't have any default arguments, so just check if
6640 // we have enough arguments.
6641 if (Args.size() < NumParams) {
6642 // Not enough arguments.
6643 Candidate.Viable = false;
6644 Candidate.FailureKind = ovl_fail_too_few_arguments;
6645 return;
6646 }
6647
6648 // Determine the implicit conversion sequences for each of the
6649 // arguments.
6650 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6651 if (ArgIdx < NumParams) {
6652 // (C++ 13.3.2p3): for F to be a viable function, there shall
6653 // exist for each argument an implicit conversion sequence
6654 // (13.3.3.1) that converts that argument to the corresponding
6655 // parameter of F.
6656 QualType ParamType = Proto->getParamType(ArgIdx);
6657 Candidate.Conversions[ArgIdx + 1]
6658 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6659 /*SuppressUserConversions=*/false,
6660 /*InOverloadResolution=*/false,
6661 /*AllowObjCWritebackConversion=*/
6662 getLangOpts().ObjCAutoRefCount);
6663 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6664 Candidate.Viable = false;
6665 Candidate.FailureKind = ovl_fail_bad_conversion;
6666 return;
6667 }
6668 } else {
6669 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6670 // argument for which there is no corresponding parameter is
6671 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6672 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6673 }
6674 }
6675
6676 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6677 Candidate.Viable = false;
6678 Candidate.FailureKind = ovl_fail_enable_if;
6679 Candidate.DeductionFailure.Data = FailedAttr;
6680 return;
6681 }
6682}
6683
6684/// \brief Add overload candidates for overloaded operators that are
6685/// member functions.
6686///
6687/// Add the overloaded operator candidates that are member functions
6688/// for the operator Op that was used in an operator expression such
6689/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6690/// CandidateSet will store the added overload candidates. (C++
6691/// [over.match.oper]).
6692void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6693 SourceLocation OpLoc,
6694 ArrayRef<Expr *> Args,
6695 OverloadCandidateSet& CandidateSet,
6696 SourceRange OpRange) {
6697 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6698
6699 // C++ [over.match.oper]p3:
6700 // For a unary operator @ with an operand of a type whose
6701 // cv-unqualified version is T1, and for a binary operator @ with
6702 // a left operand of a type whose cv-unqualified version is T1 and
6703 // a right operand of a type whose cv-unqualified version is T2,
6704 // three sets of candidate functions, designated member
6705 // candidates, non-member candidates and built-in candidates, are
6706 // constructed as follows:
6707 QualType T1 = Args[0]->getType();
6708
6709 // -- If T1 is a complete class type or a class currently being
6710 // defined, the set of member candidates is the result of the
6711 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6712 // the set of member candidates is empty.
6713 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6714 // Complete the type if it can be completed.
6715 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6716 return;
6717 // If the type is neither complete nor being defined, bail out now.
6718 if (!T1Rec->getDecl()->getDefinition())
6719 return;
6720
6721 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6722 LookupQualifiedName(Operators, T1Rec->getDecl());
6723 Operators.suppressDiagnostics();
6724
6725 for (LookupResult::iterator Oper = Operators.begin(),
6726 OperEnd = Operators.end();
6727 Oper != OperEnd;
6728 ++Oper)
6729 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6730 Args[0]->Classify(Context),
6731 Args.slice(1),
6732 CandidateSet,
6733 /* SuppressUserConversions = */ false);
6734 }
6735}
6736
6737/// AddBuiltinCandidate - Add a candidate for a built-in
6738/// operator. ResultTy and ParamTys are the result and parameter types
6739/// of the built-in candidate, respectively. Args and NumArgs are the
6740/// arguments being passed to the candidate. IsAssignmentOperator
6741/// should be true when this built-in candidate is an assignment
6742/// operator. NumContextualBoolArguments is the number of arguments
6743/// (at the beginning of the argument list) that will be contextually
6744/// converted to bool.
6745void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6746 ArrayRef<Expr *> Args,
6747 OverloadCandidateSet& CandidateSet,
6748 bool IsAssignmentOperator,
6749 unsigned NumContextualBoolArguments) {
6750 // Overload resolution is always an unevaluated context.
6751 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6752
6753 // Add this candidate
6754 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6755 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6756 Candidate.Function = nullptr;
6757 Candidate.IsSurrogate = false;
6758 Candidate.IgnoreObjectArgument = false;
6759 Candidate.BuiltinTypes.ResultTy = ResultTy;
6760 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6761 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6762
6763 // Determine the implicit conversion sequences for each of the
6764 // arguments.
6765 Candidate.Viable = true;
6766 Candidate.ExplicitCallArguments = Args.size();
6767 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6768 // C++ [over.match.oper]p4:
6769 // For the built-in assignment operators, conversions of the
6770 // left operand are restricted as follows:
6771 // -- no temporaries are introduced to hold the left operand, and
6772 // -- no user-defined conversions are applied to the left
6773 // operand to achieve a type match with the left-most
6774 // parameter of a built-in candidate.
6775 //
6776 // We block these conversions by turning off user-defined
6777 // conversions, since that is the only way that initialization of
6778 // a reference to a non-class type can occur from something that
6779 // is not of the same type.
6780 if (ArgIdx < NumContextualBoolArguments) {
6781 assert(ParamTys[ArgIdx] == Context.BoolTy &&((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6782, __PRETTY_FUNCTION__))
6782 "Contextual conversion to bool requires bool type")((ParamTys[ArgIdx] == Context.BoolTy && "Contextual conversion to bool requires bool type"
) ? static_cast<void> (0) : __assert_fail ("ParamTys[ArgIdx] == Context.BoolTy && \"Contextual conversion to bool requires bool type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6782, __PRETTY_FUNCTION__))
;
6783 Candidate.Conversions[ArgIdx]
6784 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6785 } else {
6786 Candidate.Conversions[ArgIdx]
6787 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6788 ArgIdx == 0 && IsAssignmentOperator,
6789 /*InOverloadResolution=*/false,
6790 /*AllowObjCWritebackConversion=*/
6791 getLangOpts().ObjCAutoRefCount);
6792 }
6793 if (Candidate.Conversions[ArgIdx].isBad()) {
6794 Candidate.Viable = false;
6795 Candidate.FailureKind = ovl_fail_bad_conversion;
6796 break;
6797 }
6798 }
6799}
6800
6801namespace {
6802
6803/// BuiltinCandidateTypeSet - A set of types that will be used for the
6804/// candidate operator functions for built-in operators (C++
6805/// [over.built]). The types are separated into pointer types and
6806/// enumeration types.
6807class BuiltinCandidateTypeSet {
6808 /// TypeSet - A set of types.
6809 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6810
6811 /// PointerTypes - The set of pointer types that will be used in the
6812 /// built-in candidates.
6813 TypeSet PointerTypes;
6814
6815 /// MemberPointerTypes - The set of member pointer types that will be
6816 /// used in the built-in candidates.
6817 TypeSet MemberPointerTypes;
6818
6819 /// EnumerationTypes - The set of enumeration types that will be
6820 /// used in the built-in candidates.
6821 TypeSet EnumerationTypes;
6822
6823 /// \brief The set of vector types that will be used in the built-in
6824 /// candidates.
6825 TypeSet VectorTypes;
6826
6827 /// \brief A flag indicating non-record types are viable candidates
6828 bool HasNonRecordTypes;
6829
6830 /// \brief A flag indicating whether either arithmetic or enumeration types
6831 /// were present in the candidate set.
6832 bool HasArithmeticOrEnumeralTypes;
6833
6834 /// \brief A flag indicating whether the nullptr type was present in the
6835 /// candidate set.
6836 bool HasNullPtrType;
6837
6838 /// Sema - The semantic analysis instance where we are building the
6839 /// candidate type set.
6840 Sema &SemaRef;
6841
6842 /// Context - The AST context in which we will build the type sets.
6843 ASTContext &Context;
6844
6845 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6846 const Qualifiers &VisibleQuals);
6847 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6848
6849public:
6850 /// iterator - Iterates through the types that are part of the set.
6851 typedef TypeSet::iterator iterator;
6852
6853 BuiltinCandidateTypeSet(Sema &SemaRef)
6854 : HasNonRecordTypes(false),
6855 HasArithmeticOrEnumeralTypes(false),
6856 HasNullPtrType(false),
6857 SemaRef(SemaRef),
6858 Context(SemaRef.Context) { }
6859
6860 void AddTypesConvertedFrom(QualType Ty,
6861 SourceLocation Loc,
6862 bool AllowUserConversions,
6863 bool AllowExplicitConversions,
6864 const Qualifiers &VisibleTypeConversionsQuals);
6865
6866 /// pointer_begin - First pointer type found;
6867 iterator pointer_begin() { return PointerTypes.begin(); }
6868
6869 /// pointer_end - Past the last pointer type found;
6870 iterator pointer_end() { return PointerTypes.end(); }
6871
6872 /// member_pointer_begin - First member pointer type found;
6873 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6874
6875 /// member_pointer_end - Past the last member pointer type found;
6876 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6877
6878 /// enumeration_begin - First enumeration type found;
6879 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6880
6881 /// enumeration_end - Past the last enumeration type found;
6882 iterator enumeration_end() { return EnumerationTypes.end(); }
6883
6884 iterator vector_begin() { return VectorTypes.begin(); }
6885 iterator vector_end() { return VectorTypes.end(); }
6886
6887 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6888 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6889 bool hasNullPtrType() const { return HasNullPtrType; }
6890};
6891
6892} // end anonymous namespace
6893
6894/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6895/// the set of pointer types along with any more-qualified variants of
6896/// that type. For example, if @p Ty is "int const *", this routine
6897/// will add "int const *", "int const volatile *", "int const
6898/// restrict *", and "int const volatile restrict *" to the set of
6899/// pointer types. Returns true if the add of @p Ty itself succeeded,
6900/// false otherwise.
6901///
6902/// FIXME: what to do about extended qualifiers?
6903bool
6904BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6905 const Qualifiers &VisibleQuals) {
6906
6907 // Insert this type.
6908 if (!PointerTypes.insert(Ty).second)
6909 return false;
6910
6911 QualType PointeeTy;
6912 const PointerType *PointerTy = Ty->getAs<PointerType>();
6913 bool buildObjCPtr = false;
6914 if (!PointerTy) {
6915 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6916 PointeeTy = PTy->getPointeeType();
6917 buildObjCPtr = true;
6918 } else {
6919 PointeeTy = PointerTy->getPointeeType();
6920 }
6921
6922 // Don't add qualified variants of arrays. For one, they're not allowed
6923 // (the qualifier would sink to the element type), and for another, the
6924 // only overload situation where it matters is subscript or pointer +- int,
6925 // and those shouldn't have qualifier variants anyway.
6926 if (PointeeTy->isArrayType())
6927 return true;
6928
6929 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6930 bool hasVolatile = VisibleQuals.hasVolatile();
6931 bool hasRestrict = VisibleQuals.hasRestrict();
6932
6933 // Iterate through all strict supersets of BaseCVR.
6934 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6935 if ((CVR | BaseCVR) != CVR) continue;
6936 // Skip over volatile if no volatile found anywhere in the types.
6937 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6938
6939 // Skip over restrict if no restrict found anywhere in the types, or if
6940 // the type cannot be restrict-qualified.
6941 if ((CVR & Qualifiers::Restrict) &&
6942 (!hasRestrict ||
6943 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6944 continue;
6945
6946 // Build qualified pointee type.
6947 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6948
6949 // Build qualified pointer type.
6950 QualType QPointerTy;
6951 if (!buildObjCPtr)
6952 QPointerTy = Context.getPointerType(QPointeeTy);
6953 else
6954 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6955
6956 // Insert qualified pointer type.
6957 PointerTypes.insert(QPointerTy);
6958 }
6959
6960 return true;
6961}
6962
6963/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6964/// to the set of pointer types along with any more-qualified variants of
6965/// that type. For example, if @p Ty is "int const *", this routine
6966/// will add "int const *", "int const volatile *", "int const
6967/// restrict *", and "int const volatile restrict *" to the set of
6968/// pointer types. Returns true if the add of @p Ty itself succeeded,
6969/// false otherwise.
6970///
6971/// FIXME: what to do about extended qualifiers?
6972bool
6973BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6974 QualType Ty) {
6975 // Insert this type.
6976 if (!MemberPointerTypes.insert(Ty).second)
6977 return false;
6978
6979 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6980 assert(PointerTy && "type was not a member pointer type!")((PointerTy && "type was not a member pointer type!")
? static_cast<void> (0) : __assert_fail ("PointerTy && \"type was not a member pointer type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 6980, __PRETTY_FUNCTION__))
;
6981
6982 QualType PointeeTy = PointerTy->getPointeeType();
6983 // Don't add qualified variants of arrays. For one, they're not allowed
6984 // (the qualifier would sink to the element type), and for another, the
6985 // only overload situation where it matters is subscript or pointer +- int,
6986 // and those shouldn't have qualifier variants anyway.
6987 if (PointeeTy->isArrayType())
6988 return true;
6989 const Type *ClassTy = PointerTy->getClass();
6990
6991 // Iterate through all strict supersets of the pointee type's CVR
6992 // qualifiers.
6993 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6994 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6995 if ((CVR | BaseCVR) != CVR) continue;
6996
6997 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6998 MemberPointerTypes.insert(
6999 Context.getMemberPointerType(QPointeeTy, ClassTy));
7000 }
7001
7002 return true;
7003}
7004
7005/// AddTypesConvertedFrom - Add each of the types to which the type @p
7006/// Ty can be implicit converted to the given set of @p Types. We're
7007/// primarily interested in pointer types and enumeration types. We also
7008/// take member pointer types, for the conditional operator.
7009/// AllowUserConversions is true if we should look at the conversion
7010/// functions of a class type, and AllowExplicitConversions if we
7011/// should also include the explicit conversion functions of a class
7012/// type.
7013void
7014BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7015 SourceLocation Loc,
7016 bool AllowUserConversions,
7017 bool AllowExplicitConversions,
7018 const Qualifiers &VisibleQuals) {
7019 // Only deal with canonical types.
7020 Ty = Context.getCanonicalType(Ty);
7021
7022 // Look through reference types; they aren't part of the type of an
7023 // expression for the purposes of conversions.
7024 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7025 Ty = RefTy->getPointeeType();
7026
7027 // If we're dealing with an array type, decay to the pointer.
7028 if (Ty->isArrayType())
7029 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7030
7031 // Otherwise, we don't care about qualifiers on the type.
7032 Ty = Ty.getLocalUnqualifiedType();
7033
7034 // Flag if we ever add a non-record type.
7035 const RecordType *TyRec = Ty->getAs<RecordType>();
7036 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7037
7038 // Flag if we encounter an arithmetic type.
7039 HasArithmeticOrEnumeralTypes =
7040 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7041
7042 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7043 PointerTypes.insert(Ty);
7044 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7045 // Insert our type, and its more-qualified variants, into the set
7046 // of types.
7047 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7048 return;
7049 } else if (Ty->isMemberPointerType()) {
7050 // Member pointers are far easier, since the pointee can't be converted.
7051 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7052 return;
7053 } else if (Ty->isEnumeralType()) {
7054 HasArithmeticOrEnumeralTypes = true;
7055 EnumerationTypes.insert(Ty);
7056 } else if (Ty->isVectorType()) {
7057 // We treat vector types as arithmetic types in many contexts as an
7058 // extension.
7059 HasArithmeticOrEnumeralTypes = true;
7060 VectorTypes.insert(Ty);
7061 } else if (Ty->isNullPtrType()) {
7062 HasNullPtrType = true;
7063 } else if (AllowUserConversions && TyRec) {
7064 // No conversion functions in incomplete types.
7065 if (!SemaRef.isCompleteType(Loc, Ty))
7066 return;
7067
7068 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7069 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7070 if (isa<UsingShadowDecl>(D))
7071 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7072
7073 // Skip conversion function templates; they don't tell us anything
7074 // about which builtin types we can convert to.
7075 if (isa<FunctionTemplateDecl>(D))
7076 continue;
7077
7078 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7079 if (AllowExplicitConversions || !Conv->isExplicit()) {
7080 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7081 VisibleQuals);
7082 }
7083 }
7084 }
7085}
7086
7087/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7088/// the volatile- and non-volatile-qualified assignment operators for the
7089/// given type to the candidate set.
7090static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7091 QualType T,
7092 ArrayRef<Expr *> Args,
7093 OverloadCandidateSet &CandidateSet) {
7094 QualType ParamTypes[2];
7095
7096 // T& operator=(T&, T)
7097 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7098 ParamTypes[1] = T;
7099 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7100 /*IsAssignmentOperator=*/true);
7101
7102 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7103 // volatile T& operator=(volatile T&, T)
7104 ParamTypes[0]
7105 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7106 ParamTypes[1] = T;
7107 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7108 /*IsAssignmentOperator=*/true);
7109 }
7110}
7111
7112/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7113/// if any, found in visible type conversion functions found in ArgExpr's type.
7114static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7115 Qualifiers VRQuals;
7116 const RecordType *TyRec;
7117 if (const MemberPointerType *RHSMPType =
7118 ArgExpr->getType()->getAs<MemberPointerType>())
7119 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7120 else
7121 TyRec = ArgExpr->getType()->getAs<RecordType>();
7122 if (!TyRec) {
7123 // Just to be safe, assume the worst case.
7124 VRQuals.addVolatile();
7125 VRQuals.addRestrict();
7126 return VRQuals;
7127 }
7128
7129 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7130 if (!ClassDecl->hasDefinition())
7131 return VRQuals;
7132
7133 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7134 if (isa<UsingShadowDecl>(D))
7135 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7136 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7137 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7138 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7139 CanTy = ResTypeRef->getPointeeType();
7140 // Need to go down the pointer/mempointer chain and add qualifiers
7141 // as see them.
7142 bool done = false;
7143 while (!done) {
7144 if (CanTy.isRestrictQualified())
7145 VRQuals.addRestrict();
7146 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7147 CanTy = ResTypePtr->getPointeeType();
7148 else if (const MemberPointerType *ResTypeMPtr =
7149 CanTy->getAs<MemberPointerType>())
7150 CanTy = ResTypeMPtr->getPointeeType();
7151 else
7152 done = true;
7153 if (CanTy.isVolatileQualified())
7154 VRQuals.addVolatile();
7155 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7156 return VRQuals;
7157 }
7158 }
7159 }
7160 return VRQuals;
7161}
7162
7163namespace {
7164
7165/// \brief Helper class to manage the addition of builtin operator overload
7166/// candidates. It provides shared state and utility methods used throughout
7167/// the process, as well as a helper method to add each group of builtin
7168/// operator overloads from the standard to a candidate set.
7169class BuiltinOperatorOverloadBuilder {
7170 // Common instance state available to all overload candidate addition methods.
7171 Sema &S;
7172 ArrayRef<Expr *> Args;
7173 Qualifiers VisibleTypeConversionsQuals;
7174 bool HasArithmeticOrEnumeralCandidateType;
7175 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7176 OverloadCandidateSet &CandidateSet;
7177
7178 // Define some constants used to index and iterate over the arithemetic types
7179 // provided via the getArithmeticType() method below.
7180 // The "promoted arithmetic types" are the arithmetic
7181 // types are that preserved by promotion (C++ [over.built]p2).
7182 static const unsigned FirstIntegralType = 3;
7183 static const unsigned LastIntegralType = 20;
7184 static const unsigned FirstPromotedIntegralType = 3,
7185 LastPromotedIntegralType = 11;
7186 static const unsigned FirstPromotedArithmeticType = 0,
7187 LastPromotedArithmeticType = 11;
7188 static const unsigned NumArithmeticTypes = 20;
7189
7190 /// \brief Get the canonical type for a given arithmetic type index.
7191 CanQualType getArithmeticType(unsigned index) {
7192 assert(index < NumArithmeticTypes)((index < NumArithmeticTypes) ? static_cast<void> (0
) : __assert_fail ("index < NumArithmeticTypes", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7192, __PRETTY_FUNCTION__))
;
7193 static CanQualType ASTContext::* const
7194 ArithmeticTypes[NumArithmeticTypes] = {
7195 // Start of promoted types.
7196 &ASTContext::FloatTy,
7197 &ASTContext::DoubleTy,
7198 &ASTContext::LongDoubleTy,
7199
7200 // Start of integral types.
7201 &ASTContext::IntTy,
7202 &ASTContext::LongTy,
7203 &ASTContext::LongLongTy,
7204 &ASTContext::Int128Ty,
7205 &ASTContext::UnsignedIntTy,
7206 &ASTContext::UnsignedLongTy,
7207 &ASTContext::UnsignedLongLongTy,
7208 &ASTContext::UnsignedInt128Ty,
7209 // End of promoted types.
7210
7211 &ASTContext::BoolTy,
7212 &ASTContext::CharTy,
7213 &ASTContext::WCharTy,
7214 &ASTContext::Char16Ty,
7215 &ASTContext::Char32Ty,
7216 &ASTContext::SignedCharTy,
7217 &ASTContext::ShortTy,
7218 &ASTContext::UnsignedCharTy,
7219 &ASTContext::UnsignedShortTy,
7220 // End of integral types.
7221 // FIXME: What about complex? What about half?
7222 };
7223 return S.Context.*ArithmeticTypes[index];
7224 }
7225
7226 /// \brief Gets the canonical type resulting from the usual arithemetic
7227 /// converions for the given arithmetic types.
7228 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7229 // Accelerator table for performing the usual arithmetic conversions.
7230 // The rules are basically:
7231 // - if either is floating-point, use the wider floating-point
7232 // - if same signedness, use the higher rank
7233 // - if same size, use unsigned of the higher rank
7234 // - use the larger type
7235 // These rules, together with the axiom that higher ranks are
7236 // never smaller, are sufficient to precompute all of these results
7237 // *except* when dealing with signed types of higher rank.
7238 // (we could precompute SLL x UI for all known platforms, but it's
7239 // better not to make any assumptions).
7240 // We assume that int128 has a higher rank than long long on all platforms.
7241 enum PromotedType {
7242 Dep=-1,
7243 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
7244 };
7245 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7246 [LastPromotedArithmeticType] = {
7247/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7248/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7249/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7250/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7251/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7252/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7253/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7254/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7255/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7256/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7257/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7258 };
7259
7260 assert(L < LastPromotedArithmeticType)((L < LastPromotedArithmeticType) ? static_cast<void>
(0) : __assert_fail ("L < LastPromotedArithmeticType", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7260, __PRETTY_FUNCTION__))
;
7261 assert(R < LastPromotedArithmeticType)((R < LastPromotedArithmeticType) ? static_cast<void>
(0) : __assert_fail ("R < LastPromotedArithmeticType", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7261, __PRETTY_FUNCTION__))
;
7262 int Idx = ConversionsTable[L][R];
7263
7264 // Fast path: the table gives us a concrete answer.
7265 if (Idx != Dep) return getArithmeticType(Idx);
7266
7267 // Slow path: we need to compare widths.
7268 // An invariant is that the signed type has higher rank.
7269 CanQualType LT = getArithmeticType(L),
7270 RT = getArithmeticType(R);
7271 unsigned LW = S.Context.getIntWidth(LT),
7272 RW = S.Context.getIntWidth(RT);
7273
7274 // If they're different widths, use the signed type.
7275 if (LW > RW) return LT;
7276 else if (LW < RW) return RT;
7277
7278 // Otherwise, use the unsigned type of the signed type's rank.
7279 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7280 assert(L == SLL || R == SLL)((L == SLL || R == SLL) ? static_cast<void> (0) : __assert_fail
("L == SLL || R == SLL", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7280, __PRETTY_FUNCTION__))
;
7281 return S.Context.UnsignedLongLongTy;
7282 }
7283
7284 /// \brief Helper method to factor out the common pattern of adding overloads
7285 /// for '++' and '--' builtin operators.
7286 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7287 bool HasVolatile,
7288 bool HasRestrict) {
7289 QualType ParamTypes[2] = {
7290 S.Context.getLValueReferenceType(CandidateTy),
7291 S.Context.IntTy
7292 };
7293
7294 // Non-volatile version.
7295 if (Args.size() == 1)
7296 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7297 else
7298 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7299
7300 // Use a heuristic to reduce number of builtin candidates in the set:
7301 // add volatile version only if there are conversions to a volatile type.
7302 if (HasVolatile) {
7303 ParamTypes[0] =
7304 S.Context.getLValueReferenceType(
7305 S.Context.getVolatileType(CandidateTy));
7306 if (Args.size() == 1)
7307 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7308 else
7309 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7310 }
7311
7312 // Add restrict version only if there are conversions to a restrict type
7313 // and our candidate type is a non-restrict-qualified pointer.
7314 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7315 !CandidateTy.isRestrictQualified()) {
7316 ParamTypes[0]
7317 = S.Context.getLValueReferenceType(
7318 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7319 if (Args.size() == 1)
7320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7321 else
7322 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7323
7324 if (HasVolatile) {
7325 ParamTypes[0]
7326 = S.Context.getLValueReferenceType(
7327 S.Context.getCVRQualifiedType(CandidateTy,
7328 (Qualifiers::Volatile |
7329 Qualifiers::Restrict)));
7330 if (Args.size() == 1)
7331 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7332 else
7333 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7334 }
7335 }
7336
7337 }
7338
7339public:
7340 BuiltinOperatorOverloadBuilder(
7341 Sema &S, ArrayRef<Expr *> Args,
7342 Qualifiers VisibleTypeConversionsQuals,
7343 bool HasArithmeticOrEnumeralCandidateType,
7344 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7345 OverloadCandidateSet &CandidateSet)
7346 : S(S), Args(Args),
7347 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7348 HasArithmeticOrEnumeralCandidateType(
7349 HasArithmeticOrEnumeralCandidateType),
7350 CandidateTypes(CandidateTypes),
7351 CandidateSet(CandidateSet) {
7352 // Validate some of our static helper constants in debug builds.
7353 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&((getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy
&& "Invalid first promoted integral type") ? static_cast
<void> (0) : __assert_fail ("getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && \"Invalid first promoted integral type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7354, __PRETTY_FUNCTION__))
7354 "Invalid first promoted integral type")((getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy
&& "Invalid first promoted integral type") ? static_cast
<void> (0) : __assert_fail ("getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && \"Invalid first promoted integral type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7354, __PRETTY_FUNCTION__))
;
7355 assert(getArithmeticType(LastPromotedIntegralType - 1)((getArithmeticType(LastPromotedIntegralType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted integral type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedIntegralType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted integral type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7357, __PRETTY_FUNCTION__))
7356 == S.Context.UnsignedInt128Ty &&((getArithmeticType(LastPromotedIntegralType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted integral type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedIntegralType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted integral type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7357, __PRETTY_FUNCTION__))
7357 "Invalid last promoted integral type")((getArithmeticType(LastPromotedIntegralType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted integral type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedIntegralType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted integral type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7357, __PRETTY_FUNCTION__))
;
7358 assert(getArithmeticType(FirstPromotedArithmeticType)((getArithmeticType(FirstPromotedArithmeticType) == S.Context
.FloatTy && "Invalid first promoted arithmetic type")
? static_cast<void> (0) : __assert_fail ("getArithmeticType(FirstPromotedArithmeticType) == S.Context.FloatTy && \"Invalid first promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7360, __PRETTY_FUNCTION__))
7359 == S.Context.FloatTy &&((getArithmeticType(FirstPromotedArithmeticType) == S.Context
.FloatTy && "Invalid first promoted arithmetic type")
? static_cast<void> (0) : __assert_fail ("getArithmeticType(FirstPromotedArithmeticType) == S.Context.FloatTy && \"Invalid first promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7360, __PRETTY_FUNCTION__))
7360 "Invalid first promoted arithmetic type")((getArithmeticType(FirstPromotedArithmeticType) == S.Context
.FloatTy && "Invalid first promoted arithmetic type")
? static_cast<void> (0) : __assert_fail ("getArithmeticType(FirstPromotedArithmeticType) == S.Context.FloatTy && \"Invalid first promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7360, __PRETTY_FUNCTION__))
;
7361 assert(getArithmeticType(LastPromotedArithmeticType - 1)((getArithmeticType(LastPromotedArithmeticType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted arithmetic type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedArithmeticType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7363, __PRETTY_FUNCTION__))
7362 == S.Context.UnsignedInt128Ty &&((getArithmeticType(LastPromotedArithmeticType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted arithmetic type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedArithmeticType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7363, __PRETTY_FUNCTION__))
7363 "Invalid last promoted arithmetic type")((getArithmeticType(LastPromotedArithmeticType - 1) == S.Context
.UnsignedInt128Ty && "Invalid last promoted arithmetic type"
) ? static_cast<void> (0) : __assert_fail ("getArithmeticType(LastPromotedArithmeticType - 1) == S.Context.UnsignedInt128Ty && \"Invalid last promoted arithmetic type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 7363, __PRETTY_FUNCTION__))
;
7364 }
7365
7366 // C++ [over.built]p3:
7367 //
7368 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7369 // is either volatile or empty, there exist candidate operator
7370 // functions of the form
7371 //
7372 // VQ T& operator++(VQ T&);
7373 // T operator++(VQ T&, int);
7374 //
7375 // C++ [over.built]p4:
7376 //
7377 // For every pair (T, VQ), where T is an arithmetic type other
7378 // than bool, and VQ is either volatile or empty, there exist
7379 // candidate operator functions of the form
7380 //
7381 // VQ T& operator--(VQ T&);
7382 // T operator--(VQ T&, int);
7383 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7384 if (!HasArithmeticOrEnumeralCandidateType)
7385 return;
7386
7387 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7388 Arith < NumArithmeticTypes; ++Arith) {
7389 addPlusPlusMinusMinusStyleOverloads(
7390 getArithmeticType(Arith),
7391 VisibleTypeConversionsQuals.hasVolatile(),
7392 VisibleTypeConversionsQuals.hasRestrict());
7393 }
7394 }
7395
7396 // C++ [over.built]p5:
7397 //
7398 // For every pair (T, VQ), where T is a cv-qualified or
7399 // cv-unqualified object type, and VQ is either volatile or
7400 // empty, there exist candidate operator functions of the form
7401 //
7402 // T*VQ& operator++(T*VQ&);
7403 // T*VQ& operator--(T*VQ&);
7404 // T* operator++(T*VQ&, int);
7405 // T* operator--(T*VQ&, int);
7406 void addPlusPlusMinusMinusPointerOverloads() {
7407 for (BuiltinCandidateTypeSet::iterator
7408 Ptr = CandidateTypes[0].pointer_begin(),
7409 PtrEnd = CandidateTypes[0].pointer_end();
7410 Ptr != PtrEnd; ++Ptr) {
7411 // Skip pointer types that aren't pointers to object types.
7412 if (!(*Ptr)->getPointeeType()->isObjectType())
7413 continue;
7414
7415 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7416 (!(*Ptr).isVolatileQualified() &&
7417 VisibleTypeConversionsQuals.hasVolatile()),
7418 (!(*Ptr).isRestrictQualified() &&
7419 VisibleTypeConversionsQuals.hasRestrict()));
7420 }
7421 }
7422
7423 // C++ [over.built]p6:
7424 // For every cv-qualified or cv-unqualified object type T, there
7425 // exist candidate operator functions of the form
7426 //
7427 // T& operator*(T*);
7428 //
7429 // C++ [over.built]p7:
7430 // For every function type T that does not have cv-qualifiers or a
7431 // ref-qualifier, there exist candidate operator functions of the form
7432 // T& operator*(T*);
7433 void addUnaryStarPointerOverloads() {
7434 for (BuiltinCandidateTypeSet::iterator
7435 Ptr = CandidateTypes[0].pointer_begin(),
7436 PtrEnd = CandidateTypes[0].pointer_end();
7437 Ptr != PtrEnd; ++Ptr) {
7438 QualType ParamTy = *Ptr;
7439 QualType PointeeTy = ParamTy->getPointeeType();
7440 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7441 continue;
7442
7443 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7444 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7445 continue;
7446
7447 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7448 &ParamTy, Args, CandidateSet);
7449 }
7450 }
7451
7452 // C++ [over.built]p9:
7453 // For every promoted arithmetic type T, there exist candidate
7454 // operator functions of the form
7455 //
7456 // T operator+(T);
7457 // T operator-(T);
7458 void addUnaryPlusOrMinusArithmeticOverloads() {
7459 if (!HasArithmeticOrEnumeralCandidateType)
7460 return;
7461
7462 for (unsigned Arith = FirstPromotedArithmeticType;
7463 Arith < LastPromotedArithmeticType; ++Arith) {
7464 QualType ArithTy = getArithmeticType(Arith);
7465 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7466 }
7467
7468 // Extension: We also add these operators for vector types.
7469 for (BuiltinCandidateTypeSet::iterator
7470 Vec = CandidateTypes[0].vector_begin(),
7471 VecEnd = CandidateTypes[0].vector_end();
7472 Vec != VecEnd; ++Vec) {
7473 QualType VecTy = *Vec;
7474 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7475 }
7476 }
7477
7478 // C++ [over.built]p8:
7479 // For every type T, there exist candidate operator functions of
7480 // the form
7481 //
7482 // T* operator+(T*);
7483 void addUnaryPlusPointerOverloads() {
7484 for (BuiltinCandidateTypeSet::iterator
7485 Ptr = CandidateTypes[0].pointer_begin(),
7486 PtrEnd = CandidateTypes[0].pointer_end();
7487 Ptr != PtrEnd; ++Ptr) {
7488 QualType ParamTy = *Ptr;
7489 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7490 }
7491 }
7492
7493 // C++ [over.built]p10:
7494 // For every promoted integral type T, there exist candidate
7495 // operator functions of the form
7496 //
7497 // T operator~(T);
7498 void addUnaryTildePromotedIntegralOverloads() {
7499 if (!HasArithmeticOrEnumeralCandidateType)
7500 return;
7501
7502 for (unsigned Int = FirstPromotedIntegralType;
7503 Int < LastPromotedIntegralType; ++Int) {
7504 QualType IntTy = getArithmeticType(Int);
7505 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7506 }
7507
7508 // Extension: We also add this operator for vector types.
7509 for (BuiltinCandidateTypeSet::iterator
7510 Vec = CandidateTypes[0].vector_begin(),
7511 VecEnd = CandidateTypes[0].vector_end();
7512 Vec != VecEnd; ++Vec) {
7513 QualType VecTy = *Vec;
7514 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7515 }
7516 }
7517
7518 // C++ [over.match.oper]p16:
7519 // For every pointer to member type T, there exist candidate operator
7520 // functions of the form
7521 //
7522 // bool operator==(T,T);
7523 // bool operator!=(T,T);
7524 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7525 /// Set of (canonical) types that we've already handled.
7526 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7527
7528 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7529 for (BuiltinCandidateTypeSet::iterator
7530 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7531 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7532 MemPtr != MemPtrEnd;
7533 ++MemPtr) {
7534 // Don't add the same builtin candidate twice.
7535 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7536 continue;
7537
7538 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7539 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7540 }
7541 }
7542 }
7543
7544 // C++ [over.built]p15:
7545 //
7546 // For every T, where T is an enumeration type, a pointer type, or
7547 // std::nullptr_t, there exist candidate operator functions of the form
7548 //
7549 // bool operator<(T, T);
7550 // bool operator>(T, T);
7551 // bool operator<=(T, T);
7552 // bool operator>=(T, T);
7553 // bool operator==(T, T);
7554 // bool operator!=(T, T);
7555 void addRelationalPointerOrEnumeralOverloads() {
7556 // C++ [over.match.oper]p3:
7557 // [...]the built-in candidates include all of the candidate operator
7558 // functions defined in 13.6 that, compared to the given operator, [...]
7559 // do not have the same parameter-type-list as any non-template non-member
7560 // candidate.
7561 //
7562 // Note that in practice, this only affects enumeration types because there
7563 // aren't any built-in candidates of record type, and a user-defined operator
7564 // must have an operand of record or enumeration type. Also, the only other
7565 // overloaded operator with enumeration arguments, operator=,
7566 // cannot be overloaded for enumeration types, so this is the only place
7567 // where we must suppress candidates like this.
7568 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7569 UserDefinedBinaryOperators;
7570
7571 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7572 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7573 CandidateTypes[ArgIdx].enumeration_end()) {
7574 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7575 CEnd = CandidateSet.end();
7576 C != CEnd; ++C) {
7577 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7578 continue;
7579
7580 if (C->Function->isFunctionTemplateSpecialization())
7581 continue;
7582
7583 QualType FirstParamType =
7584 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7585 QualType SecondParamType =
7586 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7587
7588 // Skip if either parameter isn't of enumeral type.
7589 if (!FirstParamType->isEnumeralType() ||
7590 !SecondParamType->isEnumeralType())
7591 continue;
7592
7593 // Add this operator to the set of known user-defined operators.
7594 UserDefinedBinaryOperators.insert(
7595 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7596 S.Context.getCanonicalType(SecondParamType)));
7597 }
7598 }
7599 }
7600
7601 /// Set of (canonical) types that we've already handled.
7602 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7603
7604 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7605 for (BuiltinCandidateTypeSet::iterator
7606 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7607 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7608 Ptr != PtrEnd; ++Ptr) {
7609 // Don't add the same builtin candidate twice.
7610 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7611 continue;
7612
7613 QualType ParamTypes[2] = { *Ptr, *Ptr };
7614 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7615 }
7616 for (BuiltinCandidateTypeSet::iterator
7617 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7618 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7619 Enum != EnumEnd; ++Enum) {
7620 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7621
7622 // Don't add the same builtin candidate twice, or if a user defined
7623 // candidate exists.
7624 if (!AddedTypes.insert(CanonType).second ||
7625 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7626 CanonType)))
7627 continue;
7628
7629 QualType ParamTypes[2] = { *Enum, *Enum };
7630 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7631 }
7632
7633 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7634 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7635 if (AddedTypes.insert(NullPtrTy).second &&
7636 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7637 NullPtrTy))) {
7638 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7639 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7640 CandidateSet);
7641 }
7642 }
7643 }
7644 }
7645
7646 // C++ [over.built]p13:
7647 //
7648 // For every cv-qualified or cv-unqualified object type T
7649 // there exist candidate operator functions of the form
7650 //
7651 // T* operator+(T*, ptrdiff_t);
7652 // T& operator[](T*, ptrdiff_t); [BELOW]
7653 // T* operator-(T*, ptrdiff_t);
7654 // T* operator+(ptrdiff_t, T*);
7655 // T& operator[](ptrdiff_t, T*); [BELOW]
7656 //
7657 // C++ [over.built]p14:
7658 //
7659 // For every T, where T is a pointer to object type, there
7660 // exist candidate operator functions of the form
7661 //
7662 // ptrdiff_t operator-(T, T);
7663 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7664 /// Set of (canonical) types that we've already handled.
7665 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7666
7667 for (int Arg = 0; Arg < 2; ++Arg) {
7668 QualType AsymmetricParamTypes[2] = {
7669 S.Context.getPointerDiffType(),
7670 S.Context.getPointerDiffType(),
7671 };
7672 for (BuiltinCandidateTypeSet::iterator
7673 Ptr = CandidateTypes[Arg].pointer_begin(),
7674 PtrEnd = CandidateTypes[Arg].pointer_end();
7675 Ptr != PtrEnd; ++Ptr) {
7676 QualType PointeeTy = (*Ptr)->getPointeeType();
7677 if (!PointeeTy->isObjectType())
7678 continue;
7679
7680 AsymmetricParamTypes[Arg] = *Ptr;
7681 if (Arg == 0 || Op == OO_Plus) {
7682 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7683 // T* operator+(ptrdiff_t, T*);
7684 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7685 }
7686 if (Op == OO_Minus) {
7687 // ptrdiff_t operator-(T, T);
7688 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7689 continue;
7690
7691 QualType ParamTypes[2] = { *Ptr, *Ptr };
7692 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7693 Args, CandidateSet);
7694 }
7695 }
7696 }
7697 }
7698
7699 // C++ [over.built]p12:
7700 //
7701 // For every pair of promoted arithmetic types L and R, there
7702 // exist candidate operator functions of the form
7703 //
7704 // LR operator*(L, R);
7705 // LR operator/(L, R);
7706 // LR operator+(L, R);
7707 // LR operator-(L, R);
7708 // bool operator<(L, R);
7709 // bool operator>(L, R);
7710 // bool operator<=(L, R);
7711 // bool operator>=(L, R);
7712 // bool operator==(L, R);
7713 // bool operator!=(L, R);
7714 //
7715 // where LR is the result of the usual arithmetic conversions
7716 // between types L and R.
7717 //
7718 // C++ [over.built]p24:
7719 //
7720 // For every pair of promoted arithmetic types L and R, there exist
7721 // candidate operator functions of the form
7722 //
7723 // LR operator?(bool, L, R);
7724 //
7725 // where LR is the result of the usual arithmetic conversions
7726 // between types L and R.
7727 // Our candidates ignore the first parameter.
7728 void addGenericBinaryArithmeticOverloads(bool isComparison) {
7729 if (!HasArithmeticOrEnumeralCandidateType)
7730 return;
7731
7732 for (unsigned Left = FirstPromotedArithmeticType;
7733 Left < LastPromotedArithmeticType; ++Left) {
7734 for (unsigned Right = FirstPromotedArithmeticType;
7735 Right < LastPromotedArithmeticType; ++Right) {
7736 QualType LandR[2] = { getArithmeticType(Left),
7737 getArithmeticType(Right) };
7738 QualType Result =
7739 isComparison ? S.Context.BoolTy
7740 : getUsualArithmeticConversions(Left, Right);
7741 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7742 }
7743 }
7744
7745 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7746 // conditional operator for vector types.
7747 for (BuiltinCandidateTypeSet::iterator
7748 Vec1 = CandidateTypes[0].vector_begin(),
7749 Vec1End = CandidateTypes[0].vector_end();
7750 Vec1 != Vec1End; ++Vec1) {
7751 for (BuiltinCandidateTypeSet::iterator
7752 Vec2 = CandidateTypes[1].vector_begin(),
7753 Vec2End = CandidateTypes[1].vector_end();
7754 Vec2 != Vec2End; ++Vec2) {
7755 QualType LandR[2] = { *Vec1, *Vec2 };
7756 QualType Result = S.Context.BoolTy;
7757 if (!isComparison) {
7758 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7759 Result = *Vec1;
7760 else
7761 Result = *Vec2;
7762 }
7763
7764 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7765 }
7766 }
7767 }
7768
7769 // C++ [over.built]p17:
7770 //
7771 // For every pair of promoted integral types L and R, there
7772 // exist candidate operator functions of the form
7773 //
7774 // LR operator%(L, R);
7775 // LR operator&(L, R);
7776 // LR operator^(L, R);
7777 // LR operator|(L, R);
7778 // L operator<<(L, R);
7779 // L operator>>(L, R);
7780 //
7781 // where LR is the result of the usual arithmetic conversions
7782 // between types L and R.
7783 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7784 if (!HasArithmeticOrEnumeralCandidateType)
7785 return;
7786
7787 for (unsigned Left = FirstPromotedIntegralType;
7788 Left < LastPromotedIntegralType; ++Left) {
7789 for (unsigned Right = FirstPromotedIntegralType;
7790 Right < LastPromotedIntegralType; ++Right) {
7791 QualType LandR[2] = { getArithmeticType(Left),
7792 getArithmeticType(Right) };
7793 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7794 ? LandR[0]
7795 : getUsualArithmeticConversions(Left, Right);
7796 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7797 }
7798 }
7799 }
7800
7801 // C++ [over.built]p20:
7802 //
7803 // For every pair (T, VQ), where T is an enumeration or
7804 // pointer to member type and VQ is either volatile or
7805 // empty, there exist candidate operator functions of the form
7806 //
7807 // VQ T& operator=(VQ T&, T);
7808 void addAssignmentMemberPointerOrEnumeralOverloads() {
7809 /// Set of (canonical) types that we've already handled.
7810 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7811
7812 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7813 for (BuiltinCandidateTypeSet::iterator
7814 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7815 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7816 Enum != EnumEnd; ++Enum) {
7817 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7818 continue;
7819
7820 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7821 }
7822
7823 for (BuiltinCandidateTypeSet::iterator
7824 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7825 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7826 MemPtr != MemPtrEnd; ++MemPtr) {
7827 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7828 continue;
7829
7830 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7831 }
7832 }
7833 }
7834
7835 // C++ [over.built]p19:
7836 //
7837 // For every pair (T, VQ), where T is any type and VQ is either
7838 // volatile or empty, there exist candidate operator functions
7839 // of the form
7840 //
7841 // T*VQ& operator=(T*VQ&, T*);
7842 //
7843 // C++ [over.built]p21:
7844 //
7845 // For every pair (T, VQ), where T is a cv-qualified or
7846 // cv-unqualified object type and VQ is either volatile or
7847 // empty, there exist candidate operator functions of the form
7848 //
7849 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7850 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7851 void addAssignmentPointerOverloads(bool isEqualOp) {
7852 /// Set of (canonical) types that we've already handled.
7853 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7854
7855 for (BuiltinCandidateTypeSet::iterator
7856 Ptr = CandidateTypes[0].pointer_begin(),
7857 PtrEnd = CandidateTypes[0].pointer_end();
7858 Ptr != PtrEnd; ++Ptr) {
7859 // If this is operator=, keep track of the builtin candidates we added.
7860 if (isEqualOp)
7861 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7862 else if (!(*Ptr)->getPointeeType()->isObjectType())
7863 continue;
7864
7865 // non-volatile version
7866 QualType ParamTypes[2] = {
7867 S.Context.getLValueReferenceType(*Ptr),
7868 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7869 };
7870 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7871 /*IsAssigmentOperator=*/ isEqualOp);
7872
7873 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7874 VisibleTypeConversionsQuals.hasVolatile();
7875 if (NeedVolatile) {
7876 // volatile version
7877 ParamTypes[0] =
7878 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7879 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7880 /*IsAssigmentOperator=*/isEqualOp);
7881 }
7882
7883 if (!(*Ptr).isRestrictQualified() &&
7884 VisibleTypeConversionsQuals.hasRestrict()) {
7885 // restrict version
7886 ParamTypes[0]
7887 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7888 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7889 /*IsAssigmentOperator=*/isEqualOp);
7890
7891 if (NeedVolatile) {
7892 // volatile restrict version
7893 ParamTypes[0]
7894 = S.Context.getLValueReferenceType(
7895 S.Context.getCVRQualifiedType(*Ptr,
7896 (Qualifiers::Volatile |
7897 Qualifiers::Restrict)));
7898 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7899 /*IsAssigmentOperator=*/isEqualOp);
7900 }
7901 }
7902 }
7903
7904 if (isEqualOp) {
7905 for (BuiltinCandidateTypeSet::iterator
7906 Ptr = CandidateTypes[1].pointer_begin(),
7907 PtrEnd = CandidateTypes[1].pointer_end();
7908 Ptr != PtrEnd; ++Ptr) {
7909 // Make sure we don't add the same candidate twice.
7910 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7911 continue;
7912
7913 QualType ParamTypes[2] = {
7914 S.Context.getLValueReferenceType(*Ptr),
7915 *Ptr,
7916 };
7917
7918 // non-volatile version
7919 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7920 /*IsAssigmentOperator=*/true);
7921
7922 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7923 VisibleTypeConversionsQuals.hasVolatile();
7924 if (NeedVolatile) {
7925 // volatile version
7926 ParamTypes[0] =
7927 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7928 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7929 /*IsAssigmentOperator=*/true);
7930 }
7931
7932 if (!(*Ptr).isRestrictQualified() &&
7933 VisibleTypeConversionsQuals.hasRestrict()) {
7934 // restrict version
7935 ParamTypes[0]
7936 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7937 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7938 /*IsAssigmentOperator=*/true);
7939
7940 if (NeedVolatile) {
7941 // volatile restrict version
7942 ParamTypes[0]
7943 = S.Context.getLValueReferenceType(
7944 S.Context.getCVRQualifiedType(*Ptr,
7945 (Qualifiers::Volatile |
7946 Qualifiers::Restrict)));
7947 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7948 /*IsAssigmentOperator=*/true);
7949 }
7950 }
7951 }
7952 }
7953 }
7954
7955 // C++ [over.built]p18:
7956 //
7957 // For every triple (L, VQ, R), where L is an arithmetic type,
7958 // VQ is either volatile or empty, and R is a promoted
7959 // arithmetic type, there exist candidate operator functions of
7960 // the form
7961 //
7962 // VQ L& operator=(VQ L&, R);
7963 // VQ L& operator*=(VQ L&, R);
7964 // VQ L& operator/=(VQ L&, R);
7965 // VQ L& operator+=(VQ L&, R);
7966 // VQ L& operator-=(VQ L&, R);
7967 void addAssignmentArithmeticOverloads(bool isEqualOp) {
7968 if (!HasArithmeticOrEnumeralCandidateType)
7969 return;
7970
7971 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7972 for (unsigned Right = FirstPromotedArithmeticType;
7973 Right < LastPromotedArithmeticType; ++Right) {
7974 QualType ParamTypes[2];
7975 ParamTypes[1] = getArithmeticType(Right);
7976
7977 // Add this built-in operator as a candidate (VQ is empty).
7978 ParamTypes[0] =
7979 S.Context.getLValueReferenceType(getArithmeticType(Left));
7980 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7981 /*IsAssigmentOperator=*/isEqualOp);
7982
7983 // Add this built-in operator as a candidate (VQ is 'volatile').
7984 if (VisibleTypeConversionsQuals.hasVolatile()) {
7985 ParamTypes[0] =
7986 S.Context.getVolatileType(getArithmeticType(Left));
7987 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7988 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7989 /*IsAssigmentOperator=*/isEqualOp);
7990 }
7991 }
7992 }
7993
7994 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7995 for (BuiltinCandidateTypeSet::iterator
7996 Vec1 = CandidateTypes[0].vector_begin(),
7997 Vec1End = CandidateTypes[0].vector_end();
7998 Vec1 != Vec1End; ++Vec1) {
7999 for (BuiltinCandidateTypeSet::iterator
8000 Vec2 = CandidateTypes[1].vector_begin(),
8001 Vec2End = CandidateTypes[1].vector_end();
8002 Vec2 != Vec2End; ++Vec2) {
8003 QualType ParamTypes[2];
8004 ParamTypes[1] = *Vec2;
8005 // Add this built-in operator as a candidate (VQ is empty).
8006 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8007 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8008 /*IsAssigmentOperator=*/isEqualOp);
8009
8010 // Add this built-in operator as a candidate (VQ is 'volatile').
8011 if (VisibleTypeConversionsQuals.hasVolatile()) {
8012 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8013 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8014 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8015 /*IsAssigmentOperator=*/isEqualOp);
8016 }
8017 }
8018 }
8019 }
8020
8021 // C++ [over.built]p22:
8022 //
8023 // For every triple (L, VQ, R), where L is an integral type, VQ
8024 // is either volatile or empty, and R is a promoted integral
8025 // type, there exist candidate operator functions of the form
8026 //
8027 // VQ L& operator%=(VQ L&, R);
8028 // VQ L& operator<<=(VQ L&, R);
8029 // VQ L& operator>>=(VQ L&, R);
8030 // VQ L& operator&=(VQ L&, R);
8031 // VQ L& operator^=(VQ L&, R);
8032 // VQ L& operator|=(VQ L&, R);
8033 void addAssignmentIntegralOverloads() {
8034 if (!HasArithmeticOrEnumeralCandidateType)
8035 return;
8036
8037 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8038 for (unsigned Right = FirstPromotedIntegralType;
8039 Right < LastPromotedIntegralType; ++Right) {
8040 QualType ParamTypes[2];
8041 ParamTypes[1] = getArithmeticType(Right);
8042
8043 // Add this built-in operator as a candidate (VQ is empty).
8044 ParamTypes[0] =
8045 S.Context.getLValueReferenceType(getArithmeticType(Left));
8046 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8047 if (VisibleTypeConversionsQuals.hasVolatile()) {
8048 // Add this built-in operator as a candidate (VQ is 'volatile').
8049 ParamTypes[0] = getArithmeticType(Left);
8050 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8051 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8052 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8053 }
8054 }
8055 }
8056 }
8057
8058 // C++ [over.operator]p23:
8059 //
8060 // There also exist candidate operator functions of the form
8061 //
8062 // bool operator!(bool);
8063 // bool operator&&(bool, bool);
8064 // bool operator||(bool, bool);
8065 void addExclaimOverload() {
8066 QualType ParamTy = S.Context.BoolTy;
8067 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8068 /*IsAssignmentOperator=*/false,
8069 /*NumContextualBoolArguments=*/1);
8070 }
8071 void addAmpAmpOrPipePipeOverload() {
8072 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8073 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8074 /*IsAssignmentOperator=*/false,
8075 /*NumContextualBoolArguments=*/2);
8076 }
8077
8078 // C++ [over.built]p13:
8079 //
8080 // For every cv-qualified or cv-unqualified object type T there
8081 // exist candidate operator functions of the form
8082 //
8083 // T* operator+(T*, ptrdiff_t); [ABOVE]
8084 // T& operator[](T*, ptrdiff_t);
8085 // T* operator-(T*, ptrdiff_t); [ABOVE]
8086 // T* operator+(ptrdiff_t, T*); [ABOVE]
8087 // T& operator[](ptrdiff_t, T*);
8088 void addSubscriptOverloads() {
8089 for (BuiltinCandidateTypeSet::iterator
8090 Ptr = CandidateTypes[0].pointer_begin(),
8091 PtrEnd = CandidateTypes[0].pointer_end();
8092 Ptr != PtrEnd; ++Ptr) {
8093 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8094 QualType PointeeType = (*Ptr)->getPointeeType();
8095 if (!PointeeType->isObjectType())
8096 continue;
8097
8098 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8099
8100 // T& operator[](T*, ptrdiff_t)
8101 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8102 }
8103
8104 for (BuiltinCandidateTypeSet::iterator
8105 Ptr = CandidateTypes[1].pointer_begin(),
8106 PtrEnd = CandidateTypes[1].pointer_end();
8107 Ptr != PtrEnd; ++Ptr) {
8108 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8109 QualType PointeeType = (*Ptr)->getPointeeType();
8110 if (!PointeeType->isObjectType())
8111 continue;
8112
8113 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8114
8115 // T& operator[](ptrdiff_t, T*)
8116 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8117 }
8118 }
8119
8120 // C++ [over.built]p11:
8121 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8122 // C1 is the same type as C2 or is a derived class of C2, T is an object
8123 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8124 // there exist candidate operator functions of the form
8125 //
8126 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8127 //
8128 // where CV12 is the union of CV1 and CV2.
8129 void addArrowStarOverloads() {
8130 for (BuiltinCandidateTypeSet::iterator
8131 Ptr = CandidateTypes[0].pointer_begin(),
8132 PtrEnd = CandidateTypes[0].pointer_end();
8133 Ptr != PtrEnd; ++Ptr) {
8134 QualType C1Ty = (*Ptr);
8135 QualType C1;
8136 QualifierCollector Q1;
8137 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8138 if (!isa<RecordType>(C1))
8139 continue;
8140 // heuristic to reduce number of builtin candidates in the set.
8141 // Add volatile/restrict version only if there are conversions to a
8142 // volatile/restrict type.
8143 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8144 continue;
8145 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8146 continue;
8147 for (BuiltinCandidateTypeSet::iterator
8148 MemPtr = CandidateTypes[1].member_pointer_begin(),
8149 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8150 MemPtr != MemPtrEnd; ++MemPtr) {
8151 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8152 QualType C2 = QualType(mptr->getClass(), 0);
8153 C2 = C2.getUnqualifiedType();
8154 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8155 break;
8156 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8157 // build CV12 T&
8158 QualType T = mptr->getPointeeType();
8159 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8160 T.isVolatileQualified())
8161 continue;
8162 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8163 T.isRestrictQualified())
8164 continue;
8165 T = Q1.apply(S.Context, T);
8166 QualType ResultTy = S.Context.getLValueReferenceType(T);
8167 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8168 }
8169 }
8170 }
8171
8172 // Note that we don't consider the first argument, since it has been
8173 // contextually converted to bool long ago. The candidates below are
8174 // therefore added as binary.
8175 //
8176 // C++ [over.built]p25:
8177 // For every type T, where T is a pointer, pointer-to-member, or scoped
8178 // enumeration type, there exist candidate operator functions of the form
8179 //
8180 // T operator?(bool, T, T);
8181 //
8182 void addConditionalOperatorOverloads() {
8183 /// Set of (canonical) types that we've already handled.
8184 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8185
8186 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8187 for (BuiltinCandidateTypeSet::iterator
8188 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8189 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8190 Ptr != PtrEnd; ++Ptr) {
8191 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8192 continue;
8193
8194 QualType ParamTypes[2] = { *Ptr, *Ptr };
8195 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8196 }
8197
8198 for (BuiltinCandidateTypeSet::iterator
8199 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8200 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8201 MemPtr != MemPtrEnd; ++MemPtr) {
8202 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8203 continue;
8204
8205 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8206 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8207 }
8208
8209 if (S.getLangOpts().CPlusPlus11) {
8210 for (BuiltinCandidateTypeSet::iterator
8211 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8212 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8213 Enum != EnumEnd; ++Enum) {
8214 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8215 continue;
8216
8217 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8218 continue;
8219
8220 QualType ParamTypes[2] = { *Enum, *Enum };
8221 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8222 }
8223 }
8224 }
8225 }
8226};
8227
8228} // end anonymous namespace
8229
8230/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8231/// operator overloads to the candidate set (C++ [over.built]), based
8232/// on the operator @p Op and the arguments given. For example, if the
8233/// operator is a binary '+', this routine might add "int
8234/// operator+(int, int)" to cover integer addition.
8235void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8236 SourceLocation OpLoc,
8237 ArrayRef<Expr *> Args,
8238 OverloadCandidateSet &CandidateSet) {
8239 // Find all of the types that the arguments can convert to, but only
8240 // if the operator we're looking at has built-in operator candidates
8241 // that make use of these types. Also record whether we encounter non-record
8242 // candidate types or either arithmetic or enumeral candidate types.
8243 Qualifiers VisibleTypeConversionsQuals;
8244 VisibleTypeConversionsQuals.addConst();
8245 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8246 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8247
8248 bool HasNonRecordCandidateType = false;
8249 bool HasArithmeticOrEnumeralCandidateType = false;
8250 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8251 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8252 CandidateTypes.emplace_back(*this);
8253 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8254 OpLoc,
8255 true,
8256 (Op == OO_Exclaim ||
8257 Op == OO_AmpAmp ||
8258 Op == OO_PipePipe),
8259 VisibleTypeConversionsQuals);
8260 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8261 CandidateTypes[ArgIdx].hasNonRecordTypes();
8262 HasArithmeticOrEnumeralCandidateType =
8263 HasArithmeticOrEnumeralCandidateType ||
8264 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8265 }
8266
8267 // Exit early when no non-record types have been added to the candidate set
8268 // for any of the arguments to the operator.
8269 //
8270 // We can't exit early for !, ||, or &&, since there we have always have
8271 // 'bool' overloads.
8272 if (!HasNonRecordCandidateType &&
8273 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8274 return;
8275
8276 // Setup an object to manage the common state for building overloads.
8277 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8278 VisibleTypeConversionsQuals,
8279 HasArithmeticOrEnumeralCandidateType,
8280 CandidateTypes, CandidateSet);
8281
8282 // Dispatch over the operation to add in only those overloads which apply.
8283 switch (Op) {
8284 case OO_None:
8285 case NUM_OVERLOADED_OPERATORS:
8286 llvm_unreachable("Expected an overloaded operator")::llvm::llvm_unreachable_internal("Expected an overloaded operator"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8286)
;
8287
8288 case OO_New:
8289 case OO_Delete:
8290 case OO_Array_New:
8291 case OO_Array_Delete:
8292 case OO_Call:
8293 llvm_unreachable(::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8294)
8294 "Special operators don't use AddBuiltinOperatorCandidates")::llvm::llvm_unreachable_internal("Special operators don't use AddBuiltinOperatorCandidates"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8294)
;
8295
8296 case OO_Comma:
8297 case OO_Arrow:
8298 case OO_Coawait:
8299 // C++ [over.match.oper]p3:
8300 // -- For the operator ',', the unary operator '&', the
8301 // operator '->', or the operator 'co_await', the
8302 // built-in candidates set is empty.
8303 break;
8304
8305 case OO_Plus: // '+' is either unary or binary
8306 if (Args.size() == 1)
8307 OpBuilder.addUnaryPlusPointerOverloads();
8308 // Fall through.
8309
8310 case OO_Minus: // '-' is either unary or binary
8311 if (Args.size() == 1) {
8312 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8313 } else {
8314 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8315 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8316 }
8317 break;
8318
8319 case OO_Star: // '*' is either unary or binary
8320 if (Args.size() == 1)
8321 OpBuilder.addUnaryStarPointerOverloads();
8322 else
8323 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8324 break;
8325
8326 case OO_Slash:
8327 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8328 break;
8329
8330 case OO_PlusPlus:
8331 case OO_MinusMinus:
8332 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8333 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8334 break;
8335
8336 case OO_EqualEqual:
8337 case OO_ExclaimEqual:
8338 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8339 // Fall through.
8340
8341 case OO_Less:
8342 case OO_Greater:
8343 case OO_LessEqual:
8344 case OO_GreaterEqual:
8345 OpBuilder.addRelationalPointerOrEnumeralOverloads();
8346 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8347 break;
8348
8349 case OO_Percent:
8350 case OO_Caret:
8351 case OO_Pipe:
8352 case OO_LessLess:
8353 case OO_GreaterGreater:
8354 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8355 break;
8356
8357 case OO_Amp: // '&' is either unary or binary
8358 if (Args.size() == 1)
8359 // C++ [over.match.oper]p3:
8360 // -- For the operator ',', the unary operator '&', or the
8361 // operator '->', the built-in candidates set is empty.
8362 break;
8363
8364 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8365 break;
8366
8367 case OO_Tilde:
8368 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8369 break;
8370
8371 case OO_Equal:
8372 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8373 // Fall through.
8374
8375 case OO_PlusEqual:
8376 case OO_MinusEqual:
8377 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8378 // Fall through.
8379
8380 case OO_StarEqual:
8381 case OO_SlashEqual:
8382 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8383 break;
8384
8385 case OO_PercentEqual:
8386 case OO_LessLessEqual:
8387 case OO_GreaterGreaterEqual:
8388 case OO_AmpEqual:
8389 case OO_CaretEqual:
8390 case OO_PipeEqual:
8391 OpBuilder.addAssignmentIntegralOverloads();
8392 break;
8393
8394 case OO_Exclaim:
8395 OpBuilder.addExclaimOverload();
8396 break;
8397
8398 case OO_AmpAmp:
8399 case OO_PipePipe:
8400 OpBuilder.addAmpAmpOrPipePipeOverload();
8401 break;
8402
8403 case OO_Subscript:
8404 OpBuilder.addSubscriptOverloads();
8405 break;
8406
8407 case OO_ArrowStar:
8408 OpBuilder.addArrowStarOverloads();
8409 break;
8410
8411 case OO_Conditional:
8412 OpBuilder.addConditionalOperatorOverloads();
8413 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8414 break;
8415 }
8416}
8417
8418/// \brief Add function candidates found via argument-dependent lookup
8419/// to the set of overloading candidates.
8420///
8421/// This routine performs argument-dependent name lookup based on the
8422/// given function name (which may also be an operator name) and adds
8423/// all of the overload candidates found by ADL to the overload
8424/// candidate set (C++ [basic.lookup.argdep]).
8425void
8426Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8427 SourceLocation Loc,
8428 ArrayRef<Expr *> Args,
8429 TemplateArgumentListInfo *ExplicitTemplateArgs,
8430 OverloadCandidateSet& CandidateSet,
8431 bool PartialOverloading) {
8432 ADLResult Fns;
8433
8434 // FIXME: This approach for uniquing ADL results (and removing
8435 // redundant candidates from the set) relies on pointer-equality,
8436 // which means we need to key off the canonical decl. However,
8437 // always going back to the canonical decl might not get us the
8438 // right set of default arguments. What default arguments are
8439 // we supposed to consider on ADL candidates, anyway?
8440
8441 // FIXME: Pass in the explicit template arguments?
8442 ArgumentDependentLookup(Name, Loc, Args, Fns);
8443
8444 // Erase all of the candidates we already knew about.
8445 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8446 CandEnd = CandidateSet.end();
8447 Cand != CandEnd; ++Cand)
8448 if (Cand->Function) {
8449 Fns.erase(Cand->Function);
8450 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8451 Fns.erase(FunTmpl);
8452 }
8453
8454 // For each of the ADL candidates we found, add it to the overload
8455 // set.
8456 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8457 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8458 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8459 if (ExplicitTemplateArgs)
8460 continue;
8461
8462 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8463 PartialOverloading);
8464 } else
8465 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8466 FoundDecl, ExplicitTemplateArgs,
8467 Args, CandidateSet, PartialOverloading);
8468 }
8469}
8470
8471// Determines whether Cand1 is "better" in terms of its enable_if attrs than
8472// Cand2 for overloading. This function assumes that all of the enable_if attrs
8473// on Cand1 and Cand2 have conditions that evaluate to true.
8474//
8475// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8476// Cand1's first N enable_if attributes have precisely the same conditions as
8477// Cand2's first N enable_if attributes (where N = the number of enable_if
8478// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8479static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1,
8480 const FunctionDecl *Cand2) {
8481
8482 // FIXME: The next several lines are just
8483 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8484 // instead of reverse order which is how they're stored in the AST.
8485 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8486 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8487
8488 // Candidate 1 is better if it has strictly more attributes and
8489 // the common sequence is identical.
8490 if (Cand1Attrs.size() <= Cand2Attrs.size())
8491 return false;
8492
8493 auto Cand1I = Cand1Attrs.begin();
8494 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8495 for (auto &Cand2A : Cand2Attrs) {
8496 Cand1ID.clear();
8497 Cand2ID.clear();
8498
8499 auto &Cand1A = *Cand1I++;
8500 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8501 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8502 if (Cand1ID != Cand2ID)
8503 return false;
8504 }
8505
8506 return true;
8507}
8508
8509/// isBetterOverloadCandidate - Determines whether the first overload
8510/// candidate is a better candidate than the second (C++ 13.3.3p1).
8511bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8512 const OverloadCandidate &Cand2,
8513 SourceLocation Loc,
8514 bool UserDefinedConversion) {
8515 // Define viable functions to be better candidates than non-viable
8516 // functions.
8517 if (!Cand2.Viable)
8518 return Cand1.Viable;
8519 else if (!Cand1.Viable)
8520 return false;
8521
8522 // C++ [over.match.best]p1:
8523 //
8524 // -- if F is a static member function, ICS1(F) is defined such
8525 // that ICS1(F) is neither better nor worse than ICS1(G) for
8526 // any function G, and, symmetrically, ICS1(G) is neither
8527 // better nor worse than ICS1(F).
8528 unsigned StartArg = 0;
8529 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8530 StartArg = 1;
8531
8532 // C++ [over.match.best]p1:
8533 // A viable function F1 is defined to be a better function than another
8534 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
8535 // conversion sequence than ICSi(F2), and then...
8536 unsigned NumArgs = Cand1.NumConversions;
8537 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch")((Cand2.NumConversions == NumArgs && "Overload candidate mismatch"
) ? static_cast<void> (0) : __assert_fail ("Cand2.NumConversions == NumArgs && \"Overload candidate mismatch\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8537, __PRETTY_FUNCTION__))
;
8538 bool HasBetterConversion = false;
8539 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8540 switch (CompareImplicitConversionSequences(S, Loc,
8541 Cand1.Conversions[ArgIdx],
8542 Cand2.Conversions[ArgIdx])) {
8543 case ImplicitConversionSequence::Better:
8544 // Cand1 has a better conversion sequence.
8545 HasBetterConversion = true;
8546 break;
8547
8548 case ImplicitConversionSequence::Worse:
8549 // Cand1 can't be better than Cand2.
8550 return false;
8551
8552 case ImplicitConversionSequence::Indistinguishable:
8553 // Do nothing.
8554 break;
8555 }
8556 }
8557
8558 // -- for some argument j, ICSj(F1) is a better conversion sequence than
8559 // ICSj(F2), or, if not that,
8560 if (HasBetterConversion)
8561 return true;
8562
8563 // -- the context is an initialization by user-defined conversion
8564 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8565 // from the return type of F1 to the destination type (i.e.,
8566 // the type of the entity being initialized) is a better
8567 // conversion sequence than the standard conversion sequence
8568 // from the return type of F2 to the destination type.
8569 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8570 isa<CXXConversionDecl>(Cand1.Function) &&
8571 isa<CXXConversionDecl>(Cand2.Function)) {
8572 // First check whether we prefer one of the conversion functions over the
8573 // other. This only distinguishes the results in non-standard, extension
8574 // cases such as the conversion from a lambda closure type to a function
8575 // pointer or block.
8576 ImplicitConversionSequence::CompareKind Result =
8577 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8578 if (Result == ImplicitConversionSequence::Indistinguishable)
8579 Result = CompareStandardConversionSequences(S, Loc,
8580 Cand1.FinalConversion,
8581 Cand2.FinalConversion);
8582
8583 if (Result != ImplicitConversionSequence::Indistinguishable)
8584 return Result == ImplicitConversionSequence::Better;
8585
8586 // FIXME: Compare kind of reference binding if conversion functions
8587 // convert to a reference type used in direct reference binding, per
8588 // C++14 [over.match.best]p1 section 2 bullet 3.
8589 }
8590
8591 // -- F1 is a non-template function and F2 is a function template
8592 // specialization, or, if not that,
8593 bool Cand1IsSpecialization = Cand1.Function &&
8594 Cand1.Function->getPrimaryTemplate();
8595 bool Cand2IsSpecialization = Cand2.Function &&
8596 Cand2.Function->getPrimaryTemplate();
8597 if (Cand1IsSpecialization != Cand2IsSpecialization)
8598 return Cand2IsSpecialization;
8599
8600 // -- F1 and F2 are function template specializations, and the function
8601 // template for F1 is more specialized than the template for F2
8602 // according to the partial ordering rules described in 14.5.5.2, or,
8603 // if not that,
8604 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8605 if (FunctionTemplateDecl *BetterTemplate
8606 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8607 Cand2.Function->getPrimaryTemplate(),
8608 Loc,
8609 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8610 : TPOC_Call,
8611 Cand1.ExplicitCallArguments,
8612 Cand2.ExplicitCallArguments))
8613 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8614 }
8615
8616 // Check for enable_if value-based overload resolution.
8617 if (Cand1.Function && Cand2.Function &&
8618 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8619 Cand2.Function->hasAttr<EnableIfAttr>()))
8620 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8621
8622 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
8623 Cand1.Function && Cand2.Function) {
8624 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8625 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8626 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8627 }
8628
8629 bool HasPS1 = Cand1.Function != nullptr &&
8630 functionHasPassObjectSizeParams(Cand1.Function);
8631 bool HasPS2 = Cand2.Function != nullptr &&
8632 functionHasPassObjectSizeParams(Cand2.Function);
8633 return HasPS1 != HasPS2 && HasPS1;
8634}
8635
8636/// Determine whether two declarations are "equivalent" for the purposes of
8637/// name lookup and overload resolution. This applies when the same internal/no
8638/// linkage entity is defined by two modules (probably by textually including
8639/// the same header). In such a case, we don't consider the declarations to
8640/// declare the same entity, but we also don't want lookups with both
8641/// declarations visible to be ambiguous in some cases (this happens when using
8642/// a modularized libstdc++).
8643bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8644 const NamedDecl *B) {
8645 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8646 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8647 if (!VA || !VB)
8648 return false;
8649
8650 // The declarations must be declaring the same name as an internal linkage
8651 // entity in different modules.
8652 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8653 VB->getDeclContext()->getRedeclContext()) ||
8654 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8655 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8656 VA->isExternallyVisible() || VB->isExternallyVisible())
8657 return false;
8658
8659 // Check that the declarations appear to be equivalent.
8660 //
8661 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8662 // For constants and functions, we should check the initializer or body is
8663 // the same. For non-constant variables, we shouldn't allow it at all.
8664 if (Context.hasSameType(VA->getType(), VB->getType()))
8665 return true;
8666
8667 // Enum constants within unnamed enumerations will have different types, but
8668 // may still be similar enough to be interchangeable for our purposes.
8669 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8670 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8671 // Only handle anonymous enums. If the enumerations were named and
8672 // equivalent, they would have been merged to the same type.
8673 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8674 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8675 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8676 !Context.hasSameType(EnumA->getIntegerType(),
8677 EnumB->getIntegerType()))
8678 return false;
8679 // Allow this only if the value is the same for both enumerators.
8680 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8681 }
8682 }
8683
8684 // Nothing else is sufficiently similar.
8685 return false;
8686}
8687
8688void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8689 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8690 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8691
8692 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8693 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8694 << !M << (M ? M->getFullModuleName() : "");
8695
8696 for (auto *E : Equiv) {
8697 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8698 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8699 << !M << (M ? M->getFullModuleName() : "");
8700 }
8701}
8702
8703/// \brief Computes the best viable function (C++ 13.3.3)
8704/// within an overload candidate set.
8705///
8706/// \param Loc The location of the function name (or operator symbol) for
8707/// which overload resolution occurs.
8708///
8709/// \param Best If overload resolution was successful or found a deleted
8710/// function, \p Best points to the candidate function found.
8711///
8712/// \returns The result of overload resolution.
8713OverloadingResult
8714OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8715 iterator &Best,
8716 bool UserDefinedConversion) {
8717 // Find the best viable function.
8718 Best = end();
8719 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8720 if (Cand->Viable)
8721 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8722 UserDefinedConversion))
8723 Best = Cand;
8724 }
8725
8726 // If we didn't find any viable functions, abort.
8727 if (Best == end())
8728 return OR_No_Viable_Function;
8729
8730 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8731
8732 // Make sure that this function is better than every other viable
8733 // function. If not, we have an ambiguity.
8734 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8735 if (Cand->Viable &&
8736 Cand != Best &&
8737 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8738 UserDefinedConversion)) {
8739 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8740 Cand->Function)) {
8741 EquivalentCands.push_back(Cand->Function);
8742 continue;
8743 }
8744
8745 Best = end();
8746 return OR_Ambiguous;
8747 }
8748 }
8749
8750 // Best is the best viable function.
8751 if (Best->Function &&
8752 (Best->Function->isDeleted() ||
8753 S.isFunctionConsideredUnavailable(Best->Function)))
8754 return OR_Deleted;
8755
8756 if (!EquivalentCands.empty())
8757 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
8758 EquivalentCands);
8759
8760 return OR_Success;
8761}
8762
8763namespace {
8764
8765enum OverloadCandidateKind {
8766 oc_function,
8767 oc_method,
8768 oc_constructor,
8769 oc_function_template,
8770 oc_method_template,
8771 oc_constructor_template,
8772 oc_implicit_default_constructor,
8773 oc_implicit_copy_constructor,
8774 oc_implicit_move_constructor,
8775 oc_implicit_copy_assignment,
8776 oc_implicit_move_assignment,
8777 oc_implicit_inherited_constructor
8778};
8779
8780OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8781 FunctionDecl *Fn,
8782 std::string &Description) {
8783 bool isTemplate = false;
8784
8785 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8786 isTemplate = true;
8787 Description = S.getTemplateArgumentBindingsText(
8788 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8789 }
8790
8791 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8792 if (!Ctor->isImplicit())
8793 return isTemplate ? oc_constructor_template : oc_constructor;
8794
8795 if (Ctor->getInheritedConstructor())
8796 return oc_implicit_inherited_constructor;
8797
8798 if (Ctor->isDefaultConstructor())
8799 return oc_implicit_default_constructor;
8800
8801 if (Ctor->isMoveConstructor())
8802 return oc_implicit_move_constructor;
8803
8804 assert(Ctor->isCopyConstructor() &&((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8805, __PRETTY_FUNCTION__))
8805 "unexpected sort of implicit constructor")((Ctor->isCopyConstructor() && "unexpected sort of implicit constructor"
) ? static_cast<void> (0) : __assert_fail ("Ctor->isCopyConstructor() && \"unexpected sort of implicit constructor\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8805, __PRETTY_FUNCTION__))
;
8806 return oc_implicit_copy_constructor;
8807 }
8808
8809 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8810 // This actually gets spelled 'candidate function' for now, but
8811 // it doesn't hurt to split it out.
8812 if (!Meth->isImplicit())
8813 return isTemplate ? oc_method_template : oc_method;
8814
8815 if (Meth->isMoveAssignmentOperator())
8816 return oc_implicit_move_assignment;
8817
8818 if (Meth->isCopyAssignmentOperator())
8819 return oc_implicit_copy_assignment;
8820
8821 assert(isa<CXXConversionDecl>(Meth) && "expected conversion")((isa<CXXConversionDecl>(Meth) && "expected conversion"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXConversionDecl>(Meth) && \"expected conversion\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8821, __PRETTY_FUNCTION__))
;
8822 return oc_method;
8823 }
8824
8825 return isTemplate ? oc_function_template : oc_function;
8826}
8827
8828void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8829 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8830 if (!Ctor) return;
8831
8832 Ctor = Ctor->getInheritedConstructor();
8833 if (!Ctor) return;
8834
8835 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8836}
8837
8838} // end anonymous namespace
8839
8840static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
8841 const FunctionDecl *FD) {
8842 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
8843 bool AlwaysTrue;
8844 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
8845 return false;
8846 if (!AlwaysTrue)
8847 return false;
8848 }
8849 return true;
8850}
8851
8852/// \brief Returns true if we can take the address of the function.
8853///
8854/// \param Complain - If true, we'll emit a diagnostic
8855/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
8856/// we in overload resolution?
8857/// \param Loc - The location of the statement we're complaining about. Ignored
8858/// if we're not complaining, or if we're in overload resolution.
8859static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
8860 bool Complain,
8861 bool InOverloadResolution,
8862 SourceLocation Loc) {
8863 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
8864 if (Complain) {
8865 if (InOverloadResolution)
8866 S.Diag(FD->getLocStart(),
8867 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
8868 else
8869 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
8870 }
8871 return false;
8872 }
8873
8874 auto I = std::find_if(FD->param_begin(), FD->param_end(),
8875 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>));
8876 if (I == FD->param_end())
8877 return true;
8878
8879 if (Complain) {
8880 // Add one to ParamNo because it's user-facing
8881 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
8882 if (InOverloadResolution)
8883 S.Diag(FD->getLocation(),
8884 diag::note_ovl_candidate_has_pass_object_size_params)
8885 << ParamNo;
8886 else
8887 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
8888 << FD << ParamNo;
8889 }
8890 return false;
8891}
8892
8893static bool checkAddressOfCandidateIsAvailable(Sema &S,
8894 const FunctionDecl *FD) {
8895 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
8896 /*InOverloadResolution=*/true,
8897 /*Loc=*/SourceLocation());
8898}
8899
8900bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
8901 bool Complain,
8902 SourceLocation Loc) {
8903 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
8904 /*InOverloadResolution=*/false,
8905 Loc);
8906}
8907
8908// Notes the location of an overload candidate.
8909void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType,
8910 bool TakingAddress) {
8911 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
8912 return;
8913
8914 std::string FnDesc;
8915 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8916 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8917 << (unsigned) K << FnDesc;
8918
8919 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8920 Diag(Fn->getLocation(), PD);
8921 MaybeEmitInheritedConstructorNote(*this, Fn);
8922}
8923
8924// Notes the location of all overload candidates designated through
8925// OverloadedExpr
8926void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
8927 bool TakingAddress) {
8928 assert(OverloadedExpr->getType() == Context.OverloadTy)((OverloadedExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("OverloadedExpr->getType() == Context.OverloadTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8928, __PRETTY_FUNCTION__))
;
8929
8930 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8931 OverloadExpr *OvlExpr = Ovl.Expression;
8932
8933 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8934 IEnd = OvlExpr->decls_end();
8935 I != IEnd; ++I) {
8936 if (FunctionTemplateDecl *FunTmpl =
8937 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8938 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType,
8939 TakingAddress);
8940 } else if (FunctionDecl *Fun
8941 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8942 NoteOverloadCandidate(Fun, DestType, TakingAddress);
8943 }
8944 }
8945}
8946
8947/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8948/// "lead" diagnostic; it will be given two arguments, the source and
8949/// target types of the conversion.
8950void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8951 Sema &S,
8952 SourceLocation CaretLoc,
8953 const PartialDiagnostic &PDiag) const {
8954 S.Diag(CaretLoc, PDiag)
8955 << Ambiguous.getFromType() << Ambiguous.getToType();
8956 // FIXME: The note limiting machinery is borrowed from
8957 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8958 // refactoring here.
8959 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8960 unsigned CandsShown = 0;
8961 AmbiguousConversionSequence::const_iterator I, E;
8962 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8963 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8964 break;
8965 ++CandsShown;
8966 S.NoteOverloadCandidate(*I);
8967 }
8968 if (I != E)
8969 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8970}
8971
8972static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8973 unsigned I, bool TakingCandidateAddress) {
8974 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8975 assert(Conv.isBad())((Conv.isBad()) ? static_cast<void> (0) : __assert_fail
("Conv.isBad()", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8975, __PRETTY_FUNCTION__))
;
8976 assert(Cand->Function && "for now, candidate must be a function")((Cand->Function && "for now, candidate must be a function"
) ? static_cast<void> (0) : __assert_fail ("Cand->Function && \"for now, candidate must be a function\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8976, __PRETTY_FUNCTION__))
;
8977 FunctionDecl *Fn = Cand->Function;
8978
8979 // There's a conversion slot for the object argument if this is a
8980 // non-constructor method. Note that 'I' corresponds the
8981 // conversion-slot index.
8982 bool isObjectArgument = false;
8983 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8984 if (I == 0)
8985 isObjectArgument = true;
8986 else
8987 I--;
8988 }
8989
8990 std::string FnDesc;
8991 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8992
8993 Expr *FromExpr = Conv.Bad.FromExpr;
1
'FromExpr' initialized here
8994 QualType FromTy = Conv.Bad.getFromType();
8995 QualType ToTy = Conv.Bad.getToType();
8996
8997 if (FromTy == S.Context.OverloadTy) {
2
Taking false branch
8998 assert(FromExpr && "overload set argument came from implicit argument?")((FromExpr && "overload set argument came from implicit argument?"
) ? static_cast<void> (0) : __assert_fail ("FromExpr && \"overload set argument came from implicit argument?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 8998, __PRETTY_FUNCTION__))
;
8999 Expr *E = FromExpr->IgnoreParens();
9000 if (isa<UnaryOperator>(E))
9001 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9002 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9003
9004 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9005 << (unsigned) FnKind << FnDesc
9006 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9007 << ToTy << Name << I+1;
9008 MaybeEmitInheritedConstructorNote(S, Fn);
9009 return;
9010 }
9011
9012 // Do some hand-waving analysis to see if the non-viability is due
9013 // to a qualifier mismatch.
9014 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9015 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9016 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
3
Taking false branch
9017 CToTy = RT->getPointeeType();
9018 else {
9019 // TODO: detect and diagnose the full richness of const mismatches.
9020 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4
Taking false branch
9021 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
9022 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
9023 }
9024
9025 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9026 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9027 Qualifiers FromQs = CFromTy.getQualifiers();
9028 Qualifiers ToQs = CToTy.getQualifiers();
9029
9030 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9031 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9032 << (unsigned) FnKind << FnDesc
9033 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9034 << FromTy
9035 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9036 << (unsigned) isObjectArgument << I+1;
9037 MaybeEmitInheritedConstructorNote(S, Fn);
9038 return;
9039 }
9040
9041 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9042 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9043 << (unsigned) FnKind << FnDesc
9044 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9045 << FromTy
9046 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9047 << (unsigned) isObjectArgument << I+1;
9048 MaybeEmitInheritedConstructorNote(S, Fn);
9049 return;
9050 }
9051
9052 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9053 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9054 << (unsigned) FnKind << FnDesc
9055 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9056 << FromTy
9057 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9058 << (unsigned) isObjectArgument << I+1;
9059 MaybeEmitInheritedConstructorNote(S, Fn);
9060 return;
9061 }
9062
9063 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9064 assert(CVR && "unexpected qualifiers mismatch")((CVR && "unexpected qualifiers mismatch") ? static_cast
<void> (0) : __assert_fail ("CVR && \"unexpected qualifiers mismatch\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9064, __PRETTY_FUNCTION__))
;
9065
9066 if (isObjectArgument) {
9067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9068 << (unsigned) FnKind << FnDesc
9069 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9070 << FromTy << (CVR - 1);
9071 } else {
9072 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9073 << (unsigned) FnKind << FnDesc
9074 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9075 << FromTy << (CVR - 1) << I+1;
9076 }
9077 MaybeEmitInheritedConstructorNote(S, Fn);
9078 return;
9079 }
9080
9081 // Special diagnostic for failure to convert an initializer list, since
9082 // telling the user that it has type void is not useful.
9083 if (FromExpr && isa<InitListExpr>(FromExpr)) {
5
Assuming pointer value is null
9084 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9085 << (unsigned) FnKind << FnDesc
9086 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9087 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9088 MaybeEmitInheritedConstructorNote(S, Fn);
9089 return;
9090 }
9091
9092 // Diagnose references or pointers to incomplete types differently,
9093 // since it's far from impossible that the incompleteness triggered
9094 // the failure.
9095 QualType TempFromTy = FromTy.getNonReferenceType();
9096 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6
Assuming 'PTy' is null
7
Taking false branch
9097 TempFromTy = PTy->getPointeeType();
9098 if (TempFromTy->isIncompleteType()) {
8
Taking false branch
9099 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9100 << (unsigned) FnKind << FnDesc
9101 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9102 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9103 MaybeEmitInheritedConstructorNote(S, Fn);
9104 return;
9105 }
9106
9107 // Diagnose base -> derived pointer conversions.
9108 unsigned BaseToDerivedConversion = 0;
9109 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9
Assuming 'FromPtrTy' is null
10
Taking false branch
9110 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9111 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9112 FromPtrTy->getPointeeType()) &&
9113 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9114 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9115 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9116 FromPtrTy->getPointeeType()))
9117 BaseToDerivedConversion = 1;
9118 }
9119 } else if (const ObjCObjectPointerType *FromPtrTy
11
Assuming 'FromPtrTy' is null
12
Taking false branch
9120 = FromTy->getAs<ObjCObjectPointerType>()) {
9121 if (const ObjCObjectPointerType *ToPtrTy
9122 = ToTy->getAs<ObjCObjectPointerType>())
9123 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9124 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9125 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9126 FromPtrTy->getPointeeType()) &&
9127 FromIface->isSuperClassOf(ToIface))
9128 BaseToDerivedConversion = 2;
9129 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
13
Assuming 'ToRefTy' is non-null
14
Taking true branch
9130 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9131 !FromTy->isIncompleteType() &&
9132 !ToRefTy->getPointeeType()->isIncompleteType() &&
9133 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9134 BaseToDerivedConversion = 3;
9135 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
15
Called C++ object pointer is null
9136 ToTy.getNonReferenceType().getCanonicalType() ==
9137 FromTy.getNonReferenceType().getCanonicalType()) {
9138 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9139 << (unsigned) FnKind << FnDesc
9140 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9141 << (unsigned) isObjectArgument << I + 1;
9142 MaybeEmitInheritedConstructorNote(S, Fn);
9143 return;
9144 }
9145 }
9146
9147 if (BaseToDerivedConversion) {
9148 S.Diag(Fn->getLocation(),
9149 diag::note_ovl_candidate_bad_base_to_derived_conv)
9150 << (unsigned) FnKind << FnDesc
9151 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9152 << (BaseToDerivedConversion - 1)
9153 << FromTy << ToTy << I+1;
9154 MaybeEmitInheritedConstructorNote(S, Fn);
9155 return;
9156 }
9157
9158 if (isa<ObjCObjectPointerType>(CFromTy) &&
9159 isa<PointerType>(CToTy)) {
9160 Qualifiers FromQs = CFromTy.getQualifiers();
9161 Qualifiers ToQs = CToTy.getQualifiers();
9162 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9163 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9164 << (unsigned) FnKind << FnDesc
9165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9166 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9167 MaybeEmitInheritedConstructorNote(S, Fn);
9168 return;
9169 }
9170 }
9171
9172 if (TakingCandidateAddress &&
9173 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9174 return;
9175
9176 // Emit the generic diagnostic and, optionally, add the hints to it.
9177 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9178 FDiag << (unsigned) FnKind << FnDesc
9179 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9180 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9181 << (unsigned) (Cand->Fix.Kind);
9182
9183 // If we can fix the conversion, suggest the FixIts.
9184 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9185 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9186 FDiag << *HI;
9187 S.Diag(Fn->getLocation(), FDiag);
9188
9189 MaybeEmitInheritedConstructorNote(S, Fn);
9190}
9191
9192/// Additional arity mismatch diagnosis specific to a function overload
9193/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9194/// over a candidate in any candidate set.
9195static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9196 unsigned NumArgs) {
9197 FunctionDecl *Fn = Cand->Function;
9198 unsigned MinParams = Fn->getMinRequiredArguments();
9199
9200 // With invalid overloaded operators, it's possible that we think we
9201 // have an arity mismatch when in fact it looks like we have the
9202 // right number of arguments, because only overloaded operators have
9203 // the weird behavior of overloading member and non-member functions.
9204 // Just don't report anything.
9205 if (Fn->isInvalidDecl() &&
9206 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9207 return true;
9208
9209 if (NumArgs < MinParams) {
9210 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9212, __PRETTY_FUNCTION__))
9211 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9212, __PRETTY_FUNCTION__))
9212 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments))(((Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooFewArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_few_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9212, __PRETTY_FUNCTION__))
;
9213 } else {
9214 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9216, __PRETTY_FUNCTION__))
9215 (Cand->FailureKind == ovl_fail_bad_deduction &&(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9216, __PRETTY_FUNCTION__))
9216 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments))(((Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand
->FailureKind == ovl_fail_bad_deduction && Cand->
DeductionFailure.Result == Sema::TDK_TooManyArguments)) ? static_cast
<void> (0) : __assert_fail ("(Cand->FailureKind == ovl_fail_too_many_arguments) || (Cand->FailureKind == ovl_fail_bad_deduction && Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9216, __PRETTY_FUNCTION__))
;
9217 }
9218
9219 return false;
9220}
9221
9222/// General arity mismatch diagnosis over a candidate in a candidate set.
9223static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
9224 assert(isa<FunctionDecl>(D) &&((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9227, __PRETTY_FUNCTION__))
9225 "The templated declaration should at least be a function"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9227, __PRETTY_FUNCTION__))
9226 " when diagnosing bad template argument deduction due to too many"((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9227, __PRETTY_FUNCTION__))
9227 " or too few arguments")((isa<FunctionDecl>(D) && "The templated declaration should at least be a function"
" when diagnosing bad template argument deduction due to too many"
" or too few arguments") ? static_cast<void> (0) : __assert_fail
("isa<FunctionDecl>(D) && \"The templated declaration should at least be a function\" \" when diagnosing bad template argument deduction due to too many\" \" or too few arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9227, __PRETTY_FUNCTION__))
;
9228
9229 FunctionDecl *Fn = cast<FunctionDecl>(D);
9230
9231 // TODO: treat calls to a missing default constructor as a special case
9232 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9233 unsigned MinParams = Fn->getMinRequiredArguments();
9234
9235 // at least / at most / exactly
9236 unsigned mode, modeCount;
9237 if (NumFormalArgs < MinParams) {
9238 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9239 FnTy->isTemplateVariadic())
9240 mode = 0; // "at least"
9241 else
9242 mode = 2; // "exactly"
9243 modeCount = MinParams;
9244 } else {
9245 if (MinParams != FnTy->getNumParams())
9246 mode = 1; // "at most"
9247 else
9248 mode = 2; // "exactly"
9249 modeCount = FnTy->getNumParams();
9250 }
9251
9252 std::string Description;
9253 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
9254
9255 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9256 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9257 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9258 << mode << Fn->getParamDecl(0) << NumFormalArgs;
9259 else
9260 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9261 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9262 << mode << modeCount << NumFormalArgs;
9263 MaybeEmitInheritedConstructorNote(S, Fn);
9264}
9265
9266/// Arity mismatch diagnosis specific to a function overload candidate.
9267static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9268 unsigned NumFormalArgs) {
9269 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9270 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
9271}
9272
9273static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9274 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
9275 return FD->getDescribedFunctionTemplate();
9276 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
9277 return RD->getDescribedClassTemplate();
9278
9279 llvm_unreachable("Unsupported: Getting the described template declaration"::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9280)
9280 " for bad deduction diagnosis")::llvm::llvm_unreachable_internal("Unsupported: Getting the described template declaration"
" for bad deduction diagnosis", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9280)
;
9281}
9282
9283/// Diagnose a failed template-argument deduction.
9284static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9285 DeductionFailureInfo &DeductionFailure,
9286 unsigned NumArgs,
9287 bool TakingCandidateAddress) {
9288 TemplateParameter Param = DeductionFailure.getTemplateParameter();
9289 NamedDecl *ParamD;
9290 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9291 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9292 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9293 switch (DeductionFailure.Result) {
9294 case Sema::TDK_Success:
9295 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9295)
;
9296
9297 case Sema::TDK_Incomplete: {
9298 assert(ParamD && "no parameter found for incomplete deduction result")((ParamD && "no parameter found for incomplete deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for incomplete deduction result\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9298, __PRETTY_FUNCTION__))
;
9299 S.Diag(Templated->getLocation(),
9300 diag::note_ovl_candidate_incomplete_deduction)
9301 << ParamD->getDeclName();
9302 MaybeEmitInheritedConstructorNote(S, Templated);
9303 return;
9304 }
9305
9306 case Sema::TDK_Underqualified: {
9307 assert(ParamD && "no parameter found for bad qualifiers deduction result")((ParamD && "no parameter found for bad qualifiers deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for bad qualifiers deduction result\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9307, __PRETTY_FUNCTION__))
;
9308 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9309
9310 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9311
9312 // Param will have been canonicalized, but it should just be a
9313 // qualified version of ParamD, so move the qualifiers to that.
9314 QualifierCollector Qs;
9315 Qs.strip(Param);
9316 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9317 assert(S.Context.hasSameType(Param, NonCanonParam))((S.Context.hasSameType(Param, NonCanonParam)) ? static_cast<
void> (0) : __assert_fail ("S.Context.hasSameType(Param, NonCanonParam)"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9317, __PRETTY_FUNCTION__))
;
9318
9319 // Arg has also been canonicalized, but there's nothing we can do
9320 // about that. It also doesn't matter as much, because it won't
9321 // have any template parameters in it (because deduction isn't
9322 // done on dependent types).
9323 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9324
9325 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9326 << ParamD->getDeclName() << Arg << NonCanonParam;
9327 MaybeEmitInheritedConstructorNote(S, Templated);
9328 return;
9329 }
9330
9331 case Sema::TDK_Inconsistent: {
9332 assert(ParamD && "no parameter found for inconsistent deduction result")((ParamD && "no parameter found for inconsistent deduction result"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for inconsistent deduction result\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9332, __PRETTY_FUNCTION__))
;
9333 int which = 0;
9334 if (isa<TemplateTypeParmDecl>(ParamD))
9335 which = 0;
9336 else if (isa<NonTypeTemplateParmDecl>(ParamD))
9337 which = 1;
9338 else {
9339 which = 2;
9340 }
9341
9342 S.Diag(Templated->getLocation(),
9343 diag::note_ovl_candidate_inconsistent_deduction)
9344 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9345 << *DeductionFailure.getSecondArg();
9346 MaybeEmitInheritedConstructorNote(S, Templated);
9347 return;
9348 }
9349
9350 case Sema::TDK_InvalidExplicitArguments:
9351 assert(ParamD && "no parameter found for invalid explicit arguments")((ParamD && "no parameter found for invalid explicit arguments"
) ? static_cast<void> (0) : __assert_fail ("ParamD && \"no parameter found for invalid explicit arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9351, __PRETTY_FUNCTION__))
;
9352 if (ParamD->getDeclName())
9353 S.Diag(Templated->getLocation(),
9354 diag::note_ovl_candidate_explicit_arg_mismatch_named)
9355 << ParamD->getDeclName();
9356 else {
9357 int index = 0;
9358 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9359 index = TTP->getIndex();
9360 else if (NonTypeTemplateParmDecl *NTTP
9361 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9362 index = NTTP->getIndex();
9363 else
9364 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9365 S.Diag(Templated->getLocation(),
9366 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9367 << (index + 1);
9368 }
9369 MaybeEmitInheritedConstructorNote(S, Templated);
9370 return;
9371
9372 case Sema::TDK_TooManyArguments:
9373 case Sema::TDK_TooFewArguments:
9374 DiagnoseArityMismatch(S, Templated, NumArgs);
9375 return;
9376
9377 case Sema::TDK_InstantiationDepth:
9378 S.Diag(Templated->getLocation(),
9379 diag::note_ovl_candidate_instantiation_depth);
9380 MaybeEmitInheritedConstructorNote(S, Templated);
9381 return;
9382
9383 case Sema::TDK_SubstitutionFailure: {
9384 // Format the template argument list into the argument string.
9385 SmallString<128> TemplateArgString;
9386 if (TemplateArgumentList *Args =
9387 DeductionFailure.getTemplateArgumentList()) {
9388 TemplateArgString = " ";
9389 TemplateArgString += S.getTemplateArgumentBindingsText(
9390 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9391 }
9392
9393 // If this candidate was disabled by enable_if, say so.
9394 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9395 if (PDiag && PDiag->second.getDiagID() ==
9396 diag::err_typename_nested_not_found_enable_if) {
9397 // FIXME: Use the source range of the condition, and the fully-qualified
9398 // name of the enable_if template. These are both present in PDiag.
9399 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9400 << "'enable_if'" << TemplateArgString;
9401 return;
9402 }
9403
9404 // Format the SFINAE diagnostic into the argument string.
9405 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9406 // formatted message in another diagnostic.
9407 SmallString<128> SFINAEArgString;
9408 SourceRange R;
9409 if (PDiag) {
9410 SFINAEArgString = ": ";
9411 R = SourceRange(PDiag->first, PDiag->first);
9412 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9413 }
9414
9415 S.Diag(Templated->getLocation(),
9416 diag::note_ovl_candidate_substitution_failure)
9417 << TemplateArgString << SFINAEArgString << R;
9418 MaybeEmitInheritedConstructorNote(S, Templated);
9419 return;
9420 }
9421
9422 case Sema::TDK_FailedOverloadResolution: {
9423 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9424 S.Diag(Templated->getLocation(),
9425 diag::note_ovl_candidate_failed_overload_resolution)
9426 << R.Expression->getName();
9427 return;
9428 }
9429
9430 case Sema::TDK_DeducedMismatch: {
9431 // Format the template argument list into the argument string.
9432 SmallString<128> TemplateArgString;
9433 if (TemplateArgumentList *Args =
9434 DeductionFailure.getTemplateArgumentList()) {
9435 TemplateArgString = " ";
9436 TemplateArgString += S.getTemplateArgumentBindingsText(
9437 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9438 }
9439
9440 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9441 << (*DeductionFailure.getCallArgIndex() + 1)
9442 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9443 << TemplateArgString;
9444 break;
9445 }
9446
9447 case Sema::TDK_NonDeducedMismatch: {
9448 // FIXME: Provide a source location to indicate what we couldn't match.
9449 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9450 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9451 if (FirstTA.getKind() == TemplateArgument::Template &&
9452 SecondTA.getKind() == TemplateArgument::Template) {
9453 TemplateName FirstTN = FirstTA.getAsTemplate();
9454 TemplateName SecondTN = SecondTA.getAsTemplate();
9455 if (FirstTN.getKind() == TemplateName::Template &&
9456 SecondTN.getKind() == TemplateName::Template) {
9457 if (FirstTN.getAsTemplateDecl()->getName() ==
9458 SecondTN.getAsTemplateDecl()->getName()) {
9459 // FIXME: This fixes a bad diagnostic where both templates are named
9460 // the same. This particular case is a bit difficult since:
9461 // 1) It is passed as a string to the diagnostic printer.
9462 // 2) The diagnostic printer only attempts to find a better
9463 // name for types, not decls.
9464 // Ideally, this should folded into the diagnostic printer.
9465 S.Diag(Templated->getLocation(),
9466 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9467 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9468 return;
9469 }
9470 }
9471 }
9472
9473 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9474 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9475 return;
9476
9477 // FIXME: For generic lambda parameters, check if the function is a lambda
9478 // call operator, and if so, emit a prettier and more informative
9479 // diagnostic that mentions 'auto' and lambda in addition to
9480 // (or instead of?) the canonical template type parameters.
9481 S.Diag(Templated->getLocation(),
9482 diag::note_ovl_candidate_non_deduced_mismatch)
9483 << FirstTA << SecondTA;
9484 return;
9485 }
9486 // TODO: diagnose these individually, then kill off
9487 // note_ovl_candidate_bad_deduction, which is uselessly vague.
9488 case Sema::TDK_MiscellaneousDeductionFailure:
9489 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9490 MaybeEmitInheritedConstructorNote(S, Templated);
9491 return;
9492 }
9493}
9494
9495/// Diagnose a failed template-argument deduction, for function calls.
9496static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9497 unsigned NumArgs,
9498 bool TakingCandidateAddress) {
9499 unsigned TDK = Cand->DeductionFailure.Result;
9500 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9501 if (CheckArityMismatch(S, Cand, NumArgs))
9502 return;
9503 }
9504 DiagnoseBadDeduction(S, Cand->Function, // pattern
9505 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9506}
9507
9508/// CUDA: diagnose an invalid call across targets.
9509static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9510 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9511 FunctionDecl *Callee = Cand->Function;
9512
9513 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9514 CalleeTarget = S.IdentifyCUDATarget(Callee);
9515
9516 std::string FnDesc;
9517 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9518
9519 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9520 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9521
9522 // This could be an implicit constructor for which we could not infer the
9523 // target due to a collsion. Diagnose that case.
9524 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9525 if (Meth != nullptr && Meth->isImplicit()) {
9526 CXXRecordDecl *ParentClass = Meth->getParent();
9527 Sema::CXXSpecialMember CSM;
9528
9529 switch (FnKind) {
9530 default:
9531 return;
9532 case oc_implicit_default_constructor:
9533 CSM = Sema::CXXDefaultConstructor;
9534 break;
9535 case oc_implicit_copy_constructor:
9536 CSM = Sema::CXXCopyConstructor;
9537 break;
9538 case oc_implicit_move_constructor:
9539 CSM = Sema::CXXMoveConstructor;
9540 break;
9541 case oc_implicit_copy_assignment:
9542 CSM = Sema::CXXCopyAssignment;
9543 break;
9544 case oc_implicit_move_assignment:
9545 CSM = Sema::CXXMoveAssignment;
9546 break;
9547 };
9548
9549 bool ConstRHS = false;
9550 if (Meth->getNumParams()) {
9551 if (const ReferenceType *RT =
9552 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9553 ConstRHS = RT->getPointeeType().isConstQualified();
9554 }
9555 }
9556
9557 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9558 /* ConstRHS */ ConstRHS,
9559 /* Diagnose */ true);
9560 }
9561}
9562
9563static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9564 FunctionDecl *Callee = Cand->Function;
9565 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9566
9567 S.Diag(Callee->getLocation(),
9568 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9569 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9570}
9571
9572/// Generates a 'note' diagnostic for an overload candidate. We've
9573/// already generated a primary error at the call site.
9574///
9575/// It really does need to be a single diagnostic with its caret
9576/// pointed at the candidate declaration. Yes, this creates some
9577/// major challenges of technical writing. Yes, this makes pointing
9578/// out problems with specific arguments quite awkward. It's still
9579/// better than generating twenty screens of text for every failed
9580/// overload.
9581///
9582/// It would be great to be able to express per-candidate problems
9583/// more richly for those diagnostic clients that cared, but we'd
9584/// still have to be just as careful with the default diagnostics.
9585static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9586 unsigned NumArgs,
9587 bool TakingCandidateAddress) {
9588 FunctionDecl *Fn = Cand->Function;
9589
9590 // Note deleted candidates, but only if they're viable.
9591 if (Cand->Viable && (Fn->isDeleted() ||
9592 S.isFunctionConsideredUnavailable(Fn))) {
9593 std::string FnDesc;
9594 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9595
9596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9597 << FnKind << FnDesc
9598 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9599 MaybeEmitInheritedConstructorNote(S, Fn);
9600 return;
9601 }
9602
9603 // We don't really have anything else to say about viable candidates.
9604 if (Cand->Viable) {
9605 S.NoteOverloadCandidate(Fn);
9606 return;
9607 }
9608
9609 switch (Cand->FailureKind) {
9610 case ovl_fail_too_many_arguments:
9611 case ovl_fail_too_few_arguments:
9612 return DiagnoseArityMismatch(S, Cand, NumArgs);
9613
9614 case ovl_fail_bad_deduction:
9615 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress);
9616
9617 case ovl_fail_illegal_constructor: {
9618 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9619 << (Fn->getPrimaryTemplate() ? 1 : 0);
9620 MaybeEmitInheritedConstructorNote(S, Fn);
9621 return;
9622 }
9623
9624 case ovl_fail_trivial_conversion:
9625 case ovl_fail_bad_final_conversion:
9626 case ovl_fail_final_conversion_not_exact:
9627 return S.NoteOverloadCandidate(Fn);
9628
9629 case ovl_fail_bad_conversion: {
9630 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9631 for (unsigned N = Cand->NumConversions; I != N; ++I)
9632 if (Cand->Conversions[I].isBad())
9633 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9634
9635 // FIXME: this currently happens when we're called from SemaInit
9636 // when user-conversion overload fails. Figure out how to handle
9637 // those conditions and diagnose them well.
9638 return S.NoteOverloadCandidate(Fn);
9639 }
9640
9641 case ovl_fail_bad_target:
9642 return DiagnoseBadTarget(S, Cand);
9643
9644 case ovl_fail_enable_if:
9645 return DiagnoseFailedEnableIfAttr(S, Cand);
9646
9647 case ovl_fail_addr_not_available: {
9648 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9649 (void)Available;
9650 assert(!Available)((!Available) ? static_cast<void> (0) : __assert_fail (
"!Available", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9650, __PRETTY_FUNCTION__))
;
9651 break;
9652 }
9653 }
9654}
9655
9656static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9657 // Desugar the type of the surrogate down to a function type,
9658 // retaining as many typedefs as possible while still showing
9659 // the function type (and, therefore, its parameter types).
9660 QualType FnType = Cand->Surrogate->getConversionType();
9661 bool isLValueReference = false;
9662 bool isRValueReference = false;
9663 bool isPointer = false;
9664 if (const LValueReferenceType *FnTypeRef =
9665 FnType->getAs<LValueReferenceType>()) {
9666 FnType = FnTypeRef->getPointeeType();
9667 isLValueReference = true;
9668 } else if (const RValueReferenceType *FnTypeRef =
9669 FnType->getAs<RValueReferenceType>()) {
9670 FnType = FnTypeRef->getPointeeType();
9671 isRValueReference = true;
9672 }
9673 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9674 FnType = FnTypePtr->getPointeeType();
9675 isPointer = true;
9676 }
9677 // Desugar down to a function type.
9678 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9679 // Reconstruct the pointer/reference as appropriate.
9680 if (isPointer) FnType = S.Context.getPointerType(FnType);
9681 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9682 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9683
9684 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9685 << FnType;
9686 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9687}
9688
9689static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9690 SourceLocation OpLoc,
9691 OverloadCandidate *Cand) {
9692 assert(Cand->NumConversions <= 2 && "builtin operator is not binary")((Cand->NumConversions <= 2 && "builtin operator is not binary"
) ? static_cast<void> (0) : __assert_fail ("Cand->NumConversions <= 2 && \"builtin operator is not binary\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9692, __PRETTY_FUNCTION__))
;
9693 std::string TypeStr("operator");
9694 TypeStr += Opc;
9695 TypeStr += "(";
9696 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9697 if (Cand->NumConversions == 1) {
9698 TypeStr += ")";
9699 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9700 } else {
9701 TypeStr += ", ";
9702 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9703 TypeStr += ")";
9704 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9705 }
9706}
9707
9708static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9709 OverloadCandidate *Cand) {
9710 unsigned NoOperands = Cand->NumConversions;
9711 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9712 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9713 if (ICS.isBad()) break; // all meaningless after first invalid
9714 if (!ICS.isAmbiguous()) continue;
9715
9716 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9717 S.PDiag(diag::note_ambiguous_type_conversion));
9718 }
9719}
9720
9721static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9722 if (Cand->Function)
9723 return Cand->Function->getLocation();
9724 if (Cand->IsSurrogate)
9725 return Cand->Surrogate->getLocation();
9726 return SourceLocation();
9727}
9728
9729static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9730 switch ((Sema::TemplateDeductionResult)DFI.Result) {
9731 case Sema::TDK_Success:
9732 llvm_unreachable("TDK_success while diagnosing bad deduction")::llvm::llvm_unreachable_internal("TDK_success while diagnosing bad deduction"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9732)
;
9733
9734 case Sema::TDK_Invalid:
9735 case Sema::TDK_Incomplete:
9736 return 1;
9737
9738 case Sema::TDK_Underqualified:
9739 case Sema::TDK_Inconsistent:
9740 return 2;
9741
9742 case Sema::TDK_SubstitutionFailure:
9743 case Sema::TDK_DeducedMismatch:
9744 case Sema::TDK_NonDeducedMismatch:
9745 case Sema::TDK_MiscellaneousDeductionFailure:
9746 return 3;
9747
9748 case Sema::TDK_InstantiationDepth:
9749 case Sema::TDK_FailedOverloadResolution:
9750 return 4;
9751
9752 case Sema::TDK_InvalidExplicitArguments:
9753 return 5;
9754
9755 case Sema::TDK_TooManyArguments:
9756 case Sema::TDK_TooFewArguments:
9757 return 6;
9758 }
9759 llvm_unreachable("Unhandled deduction result")::llvm::llvm_unreachable_internal("Unhandled deduction result"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9759)
;
9760}
9761
9762namespace {
9763struct CompareOverloadCandidatesForDisplay {
9764 Sema &S;
9765 SourceLocation Loc;
9766 size_t NumArgs;
9767
9768 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
9769 : S(S), NumArgs(nArgs) {}
9770
9771 bool operator()(const OverloadCandidate *L,
9772 const OverloadCandidate *R) {
9773 // Fast-path this check.
9774 if (L == R) return false;
9775
9776 // Order first by viability.
9777 if (L->Viable) {
9778 if (!R->Viable) return true;
9779
9780 // TODO: introduce a tri-valued comparison for overload
9781 // candidates. Would be more worthwhile if we had a sort
9782 // that could exploit it.
9783 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9784 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9785 } else if (R->Viable)
9786 return false;
9787
9788 assert(L->Viable == R->Viable)((L->Viable == R->Viable) ? static_cast<void> (0)
: __assert_fail ("L->Viable == R->Viable", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9788, __PRETTY_FUNCTION__))
;
9789
9790 // Criteria by which we can sort non-viable candidates:
9791 if (!L->Viable) {
9792 // 1. Arity mismatches come after other candidates.
9793 if (L->FailureKind == ovl_fail_too_many_arguments ||
9794 L->FailureKind == ovl_fail_too_few_arguments) {
9795 if (R->FailureKind == ovl_fail_too_many_arguments ||
9796 R->FailureKind == ovl_fail_too_few_arguments) {
9797 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9798 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9799 if (LDist == RDist) {
9800 if (L->FailureKind == R->FailureKind)
9801 // Sort non-surrogates before surrogates.
9802 return !L->IsSurrogate && R->IsSurrogate;
9803 // Sort candidates requiring fewer parameters than there were
9804 // arguments given after candidates requiring more parameters
9805 // than there were arguments given.
9806 return L->FailureKind == ovl_fail_too_many_arguments;
9807 }
9808 return LDist < RDist;
9809 }
9810 return false;
9811 }
9812 if (R->FailureKind == ovl_fail_too_many_arguments ||
9813 R->FailureKind == ovl_fail_too_few_arguments)
9814 return true;
9815
9816 // 2. Bad conversions come first and are ordered by the number
9817 // of bad conversions and quality of good conversions.
9818 if (L->FailureKind == ovl_fail_bad_conversion) {
9819 if (R->FailureKind != ovl_fail_bad_conversion)
9820 return true;
9821
9822 // The conversion that can be fixed with a smaller number of changes,
9823 // comes first.
9824 unsigned numLFixes = L->Fix.NumConversionsFixed;
9825 unsigned numRFixes = R->Fix.NumConversionsFixed;
9826 numLFixes = (numLFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numLFixes;
9827 numRFixes = (numRFixes == 0) ? UINT_MAX(2147483647 *2U +1U) : numRFixes;
9828 if (numLFixes != numRFixes) {
9829 return numLFixes < numRFixes;
9830 }
9831
9832 // If there's any ordering between the defined conversions...
9833 // FIXME: this might not be transitive.
9834 assert(L->NumConversions == R->NumConversions)((L->NumConversions == R->NumConversions) ? static_cast
<void> (0) : __assert_fail ("L->NumConversions == R->NumConversions"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9834, __PRETTY_FUNCTION__))
;
9835
9836 int leftBetter = 0;
9837 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9838 for (unsigned E = L->NumConversions; I != E; ++I) {
9839 switch (CompareImplicitConversionSequences(S, Loc,
9840 L->Conversions[I],
9841 R->Conversions[I])) {
9842 case ImplicitConversionSequence::Better:
9843 leftBetter++;
9844 break;
9845
9846 case ImplicitConversionSequence::Worse:
9847 leftBetter--;
9848 break;
9849
9850 case ImplicitConversionSequence::Indistinguishable:
9851 break;
9852 }
9853 }
9854 if (leftBetter > 0) return true;
9855 if (leftBetter < 0) return false;
9856
9857 } else if (R->FailureKind == ovl_fail_bad_conversion)
9858 return false;
9859
9860 if (L->FailureKind == ovl_fail_bad_deduction) {
9861 if (R->FailureKind != ovl_fail_bad_deduction)
9862 return true;
9863
9864 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9865 return RankDeductionFailure(L->DeductionFailure)
9866 < RankDeductionFailure(R->DeductionFailure);
9867 } else if (R->FailureKind == ovl_fail_bad_deduction)
9868 return false;
9869
9870 // TODO: others?
9871 }
9872
9873 // Sort everything else by location.
9874 SourceLocation LLoc = GetLocationForCandidate(L);
9875 SourceLocation RLoc = GetLocationForCandidate(R);
9876
9877 // Put candidates without locations (e.g. builtins) at the end.
9878 if (LLoc.isInvalid()) return false;
9879 if (RLoc.isInvalid()) return true;
9880
9881 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9882 }
9883};
9884}
9885
9886/// CompleteNonViableCandidate - Normally, overload resolution only
9887/// computes up to the first. Produces the FixIt set if possible.
9888static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9889 ArrayRef<Expr *> Args) {
9890 assert(!Cand->Viable)((!Cand->Viable) ? static_cast<void> (0) : __assert_fail
("!Cand->Viable", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9890, __PRETTY_FUNCTION__))
;
9891
9892 // Don't do anything on failures other than bad conversion.
9893 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9894
9895 // We only want the FixIts if all the arguments can be corrected.
9896 bool Unfixable = false;
9897 // Use a implicit copy initialization to check conversion fixes.
9898 Cand->Fix.setConversionChecker(TryCopyInitialization);
9899
9900 // Skip forward to the first bad conversion.
9901 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9902 unsigned ConvCount = Cand->NumConversions;
9903 while (true) {
9904 assert(ConvIdx != ConvCount && "no bad conversion in candidate")((ConvIdx != ConvCount && "no bad conversion in candidate"
) ? static_cast<void> (0) : __assert_fail ("ConvIdx != ConvCount && \"no bad conversion in candidate\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9904, __PRETTY_FUNCTION__))
;
9905 ConvIdx++;
9906 if (Cand->Conversions[ConvIdx - 1].isBad()) {
9907 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9908 break;
9909 }
9910 }
9911
9912 if (ConvIdx == ConvCount)
9913 return;
9914
9915 assert(!Cand->Conversions[ConvIdx].isInitialized() &&((!Cand->Conversions[ConvIdx].isInitialized() && "remaining conversion is initialized?"
) ? static_cast<void> (0) : __assert_fail ("!Cand->Conversions[ConvIdx].isInitialized() && \"remaining conversion is initialized?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9916, __PRETTY_FUNCTION__))
9916 "remaining conversion is initialized?")((!Cand->Conversions[ConvIdx].isInitialized() && "remaining conversion is initialized?"
) ? static_cast<void> (0) : __assert_fail ("!Cand->Conversions[ConvIdx].isInitialized() && \"remaining conversion is initialized?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9916, __PRETTY_FUNCTION__))
;
9917
9918 // FIXME: this should probably be preserved from the overload
9919 // operation somehow.
9920 bool SuppressUserConversions = false;
9921
9922 const FunctionProtoType* Proto;
9923 unsigned ArgIdx = ConvIdx;
9924
9925 if (Cand->IsSurrogate) {
9926 QualType ConvType
9927 = Cand->Surrogate->getConversionType().getNonReferenceType();
9928 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9929 ConvType = ConvPtrType->getPointeeType();
9930 Proto = ConvType->getAs<FunctionProtoType>();
9931 ArgIdx--;
9932 } else if (Cand->Function) {
9933 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9934 if (isa<CXXMethodDecl>(Cand->Function) &&
9935 !isa<CXXConstructorDecl>(Cand->Function))
9936 ArgIdx--;
9937 } else {
9938 // Builtin binary operator with a bad first conversion.
9939 assert(ConvCount <= 3)((ConvCount <= 3) ? static_cast<void> (0) : __assert_fail
("ConvCount <= 3", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 9939, __PRETTY_FUNCTION__))
;
9940 for (; ConvIdx != ConvCount; ++ConvIdx)
9941 Cand->Conversions[ConvIdx]
9942 = TryCopyInitialization(S, Args[ConvIdx],
9943 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9944 SuppressUserConversions,
9945 /*InOverloadResolution*/ true,
9946 /*AllowObjCWritebackConversion=*/
9947 S.getLangOpts().ObjCAutoRefCount);
9948 return;
9949 }
9950
9951 // Fill in the rest of the conversions.
9952 unsigned NumParams = Proto->getNumParams();
9953 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9954 if (ArgIdx < NumParams) {
9955 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9956 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9957 /*InOverloadResolution=*/true,
9958 /*AllowObjCWritebackConversion=*/
9959 S.getLangOpts().ObjCAutoRefCount);
9960 // Store the FixIt in the candidate if it exists.
9961 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9962 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9963 }
9964 else
9965 Cand->Conversions[ConvIdx].setEllipsis();
9966 }
9967}
9968
9969/// PrintOverloadCandidates - When overload resolution fails, prints
9970/// diagnostic messages containing the candidates in the candidate
9971/// set.
9972void OverloadCandidateSet::NoteCandidates(Sema &S,
9973 OverloadCandidateDisplayKind OCD,
9974 ArrayRef<Expr *> Args,
9975 StringRef Opc,
9976 SourceLocation OpLoc) {
9977 // Sort the candidates by viability and position. Sorting directly would
9978 // be prohibitive, so we make a set of pointers and sort those.
9979 SmallVector<OverloadCandidate*, 32> Cands;
9980 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9981 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9982 if (Cand->Viable)
9983 Cands.push_back(Cand);
9984 else if (OCD == OCD_AllCandidates) {
9985 CompleteNonViableCandidate(S, Cand, Args);
9986 if (Cand->Function || Cand->IsSurrogate)
9987 Cands.push_back(Cand);
9988 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9989 // want to list every possible builtin candidate.
9990 }
9991 }
9992
9993 std::sort(Cands.begin(), Cands.end(),
9994 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
9995
9996 bool ReportedAmbiguousConversions = false;
9997
9998 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9999 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10000 unsigned CandsShown = 0;
10001 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10002 OverloadCandidate *Cand = *I;
10003
10004 // Set an arbitrary limit on the number of candidate functions we'll spam
10005 // the user with. FIXME: This limit should depend on details of the
10006 // candidate list.
10007 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10008 break;
10009 }
10010 ++CandsShown;
10011
10012 if (Cand->Function)
10013 NoteFunctionCandidate(S, Cand, Args.size(),
10014 /*TakingCandidateAddress=*/false);
10015 else if (Cand->IsSurrogate)
10016 NoteSurrogateCandidate(S, Cand);
10017 else {
10018 assert(Cand->Viable &&((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10019, __PRETTY_FUNCTION__))
10019 "Non-viable built-in candidates are not added to Cands.")((Cand->Viable && "Non-viable built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Viable && \"Non-viable built-in candidates are not added to Cands.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10019, __PRETTY_FUNCTION__))
;
10020 // Generally we only see ambiguities including viable builtin
10021 // operators if overload resolution got screwed up by an
10022 // ambiguous user-defined conversion.
10023 //
10024 // FIXME: It's quite possible for different conversions to see
10025 // different ambiguities, though.
10026 if (!ReportedAmbiguousConversions) {
10027 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10028 ReportedAmbiguousConversions = true;
10029 }
10030
10031 // If this is a viable builtin, print it.
10032 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10033 }
10034 }
10035
10036 if (I != E)
10037 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10038}
10039
10040static SourceLocation
10041GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10042 return Cand->Specialization ? Cand->Specialization->getLocation()
10043 : SourceLocation();
10044}
10045
10046namespace {
10047struct CompareTemplateSpecCandidatesForDisplay {
10048 Sema &S;
10049 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10050
10051 bool operator()(const TemplateSpecCandidate *L,
10052 const TemplateSpecCandidate *R) {
10053 // Fast-path this check.
10054 if (L == R)
10055 return false;
10056
10057 // Assuming that both candidates are not matches...
10058
10059 // Sort by the ranking of deduction failures.
10060 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10061 return RankDeductionFailure(L->DeductionFailure) <
10062 RankDeductionFailure(R->DeductionFailure);
10063
10064 // Sort everything else by location.
10065 SourceLocation LLoc = GetLocationForCandidate(L);
10066 SourceLocation RLoc = GetLocationForCandidate(R);
10067
10068 // Put candidates without locations (e.g. builtins) at the end.
10069 if (LLoc.isInvalid())
10070 return false;
10071 if (RLoc.isInvalid())
10072 return true;
10073
10074 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10075 }
10076};
10077}
10078
10079/// Diagnose a template argument deduction failure.
10080/// We are treating these failures as overload failures due to bad
10081/// deductions.
10082void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10083 bool ForTakingAddress) {
10084 DiagnoseBadDeduction(S, Specialization, // pattern
10085 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10086}
10087
10088void TemplateSpecCandidateSet::destroyCandidates() {
10089 for (iterator i = begin(), e = end(); i != e; ++i) {
10090 i->DeductionFailure.Destroy();
10091 }
10092}
10093
10094void TemplateSpecCandidateSet::clear() {
10095 destroyCandidates();
10096 Candidates.clear();
10097}
10098
10099/// NoteCandidates - When no template specialization match is found, prints
10100/// diagnostic messages containing the non-matching specializations that form
10101/// the candidate set.
10102/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10103/// OCD == OCD_AllCandidates and Cand->Viable == false.
10104void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10105 // Sort the candidates by position (assuming no candidate is a match).
10106 // Sorting directly would be prohibitive, so we make a set of pointers
10107 // and sort those.
10108 SmallVector<TemplateSpecCandidate *, 32> Cands;
10109 Cands.reserve(size());
10110 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10111 if (Cand->Specialization)
10112 Cands.push_back(Cand);
10113 // Otherwise, this is a non-matching builtin candidate. We do not,
10114 // in general, want to list every possible builtin candidate.
10115 }
10116
10117 std::sort(Cands.begin(), Cands.end(),
10118 CompareTemplateSpecCandidatesForDisplay(S));
10119
10120 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10121 // for generalization purposes (?).
10122 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10123
10124 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10125 unsigned CandsShown = 0;
10126 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10127 TemplateSpecCandidate *Cand = *I;
10128
10129 // Set an arbitrary limit on the number of candidates we'll spam
10130 // the user with. FIXME: This limit should depend on details of the
10131 // candidate list.
10132 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10133 break;
10134 ++CandsShown;
10135
10136 assert(Cand->Specialization &&((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10137, __PRETTY_FUNCTION__))
10137 "Non-matching built-in candidates are not added to Cands.")((Cand->Specialization && "Non-matching built-in candidates are not added to Cands."
) ? static_cast<void> (0) : __assert_fail ("Cand->Specialization && \"Non-matching built-in candidates are not added to Cands.\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10137, __PRETTY_FUNCTION__))
;
10138 Cand->NoteDeductionFailure(S, ForTakingAddress);
10139 }
10140
10141 if (I != E)
10142 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10143}
10144
10145// [PossiblyAFunctionType] --> [Return]
10146// NonFunctionType --> NonFunctionType
10147// R (A) --> R(A)
10148// R (*)(A) --> R (A)
10149// R (&)(A) --> R (A)
10150// R (S::*)(A) --> R (A)
10151QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10152 QualType Ret = PossiblyAFunctionType;
10153 if (const PointerType *ToTypePtr =
10154 PossiblyAFunctionType->getAs<PointerType>())
10155 Ret = ToTypePtr->getPointeeType();
10156 else if (const ReferenceType *ToTypeRef =
10157 PossiblyAFunctionType->getAs<ReferenceType>())
10158 Ret = ToTypeRef->getPointeeType();
10159 else if (const MemberPointerType *MemTypePtr =
10160 PossiblyAFunctionType->getAs<MemberPointerType>())
10161 Ret = MemTypePtr->getPointeeType();
10162 Ret =
10163 Context.getCanonicalType(Ret).getUnqualifiedType();
10164 return Ret;
10165}
10166
10167namespace {
10168// A helper class to help with address of function resolution
10169// - allows us to avoid passing around all those ugly parameters
10170class AddressOfFunctionResolver {
10171 Sema& S;
10172 Expr* SourceExpr;
10173 const QualType& TargetType;
10174 QualType TargetFunctionType; // Extracted function type from target type
10175
10176 bool Complain;
10177 //DeclAccessPair& ResultFunctionAccessPair;
10178 ASTContext& Context;
10179
10180 bool TargetTypeIsNonStaticMemberFunction;
10181 bool FoundNonTemplateFunction;
10182 bool StaticMemberFunctionFromBoundPointer;
10183 bool HasComplained;
10184
10185 OverloadExpr::FindResult OvlExprInfo;
10186 OverloadExpr *OvlExpr;
10187 TemplateArgumentListInfo OvlExplicitTemplateArgs;
10188 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10189 TemplateSpecCandidateSet FailedCandidates;
10190
10191public:
10192 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10193 const QualType &TargetType, bool Complain)
10194 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10195 Complain(Complain), Context(S.getASTContext()),
10196 TargetTypeIsNonStaticMemberFunction(
10197 !!TargetType->getAs<MemberPointerType>()),
10198 FoundNonTemplateFunction(false),
10199 StaticMemberFunctionFromBoundPointer(false),
10200 HasComplained(false),
10201 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10202 OvlExpr(OvlExprInfo.Expression),
10203 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10204 ExtractUnqualifiedFunctionTypeFromTargetType();
10205
10206 if (TargetFunctionType->isFunctionType()) {
10207 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10208 if (!UME->isImplicitAccess() &&
10209 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10210 StaticMemberFunctionFromBoundPointer = true;
10211 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10212 DeclAccessPair dap;
10213 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10214 OvlExpr, false, &dap)) {
10215 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10216 if (!Method->isStatic()) {
10217 // If the target type is a non-function type and the function found
10218 // is a non-static member function, pretend as if that was the
10219 // target, it's the only possible type to end up with.
10220 TargetTypeIsNonStaticMemberFunction = true;
10221
10222 // And skip adding the function if its not in the proper form.
10223 // We'll diagnose this due to an empty set of functions.
10224 if (!OvlExprInfo.HasFormOfMemberPointer)
10225 return;
10226 }
10227
10228 Matches.push_back(std::make_pair(dap, Fn));
10229 }
10230 return;
10231 }
10232
10233 if (OvlExpr->hasExplicitTemplateArgs())
10234 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10235
10236 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10237 // C++ [over.over]p4:
10238 // If more than one function is selected, [...]
10239 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10240 if (FoundNonTemplateFunction)
10241 EliminateAllTemplateMatches();
10242 else
10243 EliminateAllExceptMostSpecializedTemplate();
10244 }
10245 }
10246
10247 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
10248 Matches.size() > 1)
10249 EliminateSuboptimalCudaMatches();
10250 }
10251
10252 bool hasComplained() const { return HasComplained; }
10253
10254private:
10255 // Is A considered a better overload candidate for the desired type than B?
10256 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10257 return hasBetterEnableIfAttrs(S, A, B);
10258 }
10259
10260 // Returns true if we've eliminated any (read: all but one) candidates, false
10261 // otherwise.
10262 bool eliminiateSuboptimalOverloadCandidates() {
10263 // Same algorithm as overload resolution -- one pass to pick the "best",
10264 // another pass to be sure that nothing is better than the best.
10265 auto Best = Matches.begin();
10266 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10267 if (isBetterCandidate(I->second, Best->second))
10268 Best = I;
10269
10270 const FunctionDecl *BestFn = Best->second;
10271 auto IsBestOrInferiorToBest = [this, BestFn](
10272 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10273 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10274 };
10275
10276 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10277 // option, so we can potentially give the user a better error
10278 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10279 return false;
10280 Matches[0] = *Best;
10281 Matches.resize(1);
10282 return true;
10283 }
10284
10285 bool isTargetTypeAFunction() const {
10286 return TargetFunctionType->isFunctionType();
10287 }
10288
10289 // [ToType] [Return]
10290
10291 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10292 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10293 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10294 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10295 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10296 }
10297
10298 // return true if any matching specializations were found
10299 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10300 const DeclAccessPair& CurAccessFunPair) {
10301 if (CXXMethodDecl *Method
10302 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10303 // Skip non-static function templates when converting to pointer, and
10304 // static when converting to member pointer.
10305 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10306 return false;
10307 }
10308 else if (TargetTypeIsNonStaticMemberFunction)
10309 return false;
10310
10311 // C++ [over.over]p2:
10312 // If the name is a function template, template argument deduction is
10313 // done (14.8.2.2), and if the argument deduction succeeds, the
10314 // resulting template argument list is used to generate a single
10315 // function template specialization, which is added to the set of
10316 // overloaded functions considered.
10317 FunctionDecl *Specialization = nullptr;
10318 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10319 if (Sema::TemplateDeductionResult Result
10320 = S.DeduceTemplateArguments(FunctionTemplate,
10321 &OvlExplicitTemplateArgs,
10322 TargetFunctionType, Specialization,
10323 Info, /*InOverloadResolution=*/true)) {
10324 // Make a note of the failed deduction for diagnostics.
10325 FailedCandidates.addCandidate()
10326 .set(FunctionTemplate->getTemplatedDecl(),
10327 MakeDeductionFailureInfo(Context, Result, Info));
10328 return false;
10329 }
10330
10331 // Template argument deduction ensures that we have an exact match or
10332 // compatible pointer-to-function arguments that would be adjusted by ICS.
10333 // This function template specicalization works.
10334 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
10335 assert(S.isSameOrCompatibleFunctionType(((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10337, __PRETTY_FUNCTION__))
10336 Context.getCanonicalType(Specialization->getType()),((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10337, __PRETTY_FUNCTION__))
10337 Context.getCanonicalType(TargetFunctionType)))((S.isSameOrCompatibleFunctionType( Context.getCanonicalType(
Specialization->getType()), Context.getCanonicalType(TargetFunctionType
))) ? static_cast<void> (0) : __assert_fail ("S.isSameOrCompatibleFunctionType( Context.getCanonicalType(Specialization->getType()), Context.getCanonicalType(TargetFunctionType))"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10337, __PRETTY_FUNCTION__))
;
10338
10339 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10340 return false;
10341
10342 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10343 return true;
10344 }
10345
10346 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10347 const DeclAccessPair& CurAccessFunPair) {
10348 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10349 // Skip non-static functions when converting to pointer, and static
10350 // when converting to member pointer.
10351 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10352 return false;
10353 }
10354 else if (TargetTypeIsNonStaticMemberFunction)
10355 return false;
10356
10357 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10358 if (S.getLangOpts().CUDA)
10359 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10360 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
10361 return false;
10362
10363 // If any candidate has a placeholder return type, trigger its deduction
10364 // now.
10365 if (S.getLangOpts().CPlusPlus14 &&
10366 FunDecl->getReturnType()->isUndeducedType() &&
10367 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) {
10368 HasComplained |= Complain;
10369 return false;
10370 }
10371
10372 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10373 return false;
10374
10375 QualType ResultTy;
10376 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10377 FunDecl->getType()) ||
10378 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10379 ResultTy) ||
10380 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) {
10381 Matches.push_back(std::make_pair(
10382 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10383 FoundNonTemplateFunction = true;
10384 return true;
10385 }
10386 }
10387
10388 return false;
10389 }
10390
10391 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10392 bool Ret = false;
10393
10394 // If the overload expression doesn't have the form of a pointer to
10395 // member, don't try to convert it to a pointer-to-member type.
10396 if (IsInvalidFormOfPointerToMemberFunction())
10397 return false;
10398
10399 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10400 E = OvlExpr->decls_end();
10401 I != E; ++I) {
10402 // Look through any using declarations to find the underlying function.
10403 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10404
10405 // C++ [over.over]p3:
10406 // Non-member functions and static member functions match
10407 // targets of type "pointer-to-function" or "reference-to-function."
10408 // Nonstatic member functions match targets of
10409 // type "pointer-to-member-function."
10410 // Note that according to DR 247, the containing class does not matter.
10411 if (FunctionTemplateDecl *FunctionTemplate
10412 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10413 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10414 Ret = true;
10415 }
10416 // If we have explicit template arguments supplied, skip non-templates.
10417 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10418 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10419 Ret = true;
10420 }
10421 assert(Ret || Matches.empty())((Ret || Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Ret || Matches.empty()", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10421, __PRETTY_FUNCTION__))
;
10422 return Ret;
10423 }
10424
10425 void EliminateAllExceptMostSpecializedTemplate() {
10426 // [...] and any given function template specialization F1 is
10427 // eliminated if the set contains a second function template
10428 // specialization whose function template is more specialized
10429 // than the function template of F1 according to the partial
10430 // ordering rules of 14.5.5.2.
10431
10432 // The algorithm specified above is quadratic. We instead use a
10433 // two-pass algorithm (similar to the one used to identify the
10434 // best viable function in an overload set) that identifies the
10435 // best function template (if it exists).
10436
10437 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10438 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10439 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10440
10441 // TODO: It looks like FailedCandidates does not serve much purpose
10442 // here, since the no_viable diagnostic has index 0.
10443 UnresolvedSetIterator Result = S.getMostSpecialized(
10444 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10445 SourceExpr->getLocStart(), S.PDiag(),
10446 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10447 .second->getDeclName(),
10448 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10449 Complain, TargetFunctionType);
10450
10451 if (Result != MatchesCopy.end()) {
10452 // Make it the first and only element
10453 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10454 Matches[0].second = cast<FunctionDecl>(*Result);
10455 Matches.resize(1);
10456 } else
10457 HasComplained |= Complain;
10458 }
10459
10460 void EliminateAllTemplateMatches() {
10461 // [...] any function template specializations in the set are
10462 // eliminated if the set also contains a non-template function, [...]
10463 for (unsigned I = 0, N = Matches.size(); I != N; ) {
10464 if (Matches[I].second->getPrimaryTemplate() == nullptr)
10465 ++I;
10466 else {
10467 Matches[I] = Matches[--N];
10468 Matches.resize(N);
10469 }
10470 }
10471 }
10472
10473 void EliminateSuboptimalCudaMatches() {
10474 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10475 }
10476
10477public:
10478 void ComplainNoMatchesFound() const {
10479 assert(Matches.empty())((Matches.empty()) ? static_cast<void> (0) : __assert_fail
("Matches.empty()", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10479, __PRETTY_FUNCTION__))
;
10480 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10481 << OvlExpr->getName() << TargetFunctionType
10482 << OvlExpr->getSourceRange();
10483 if (FailedCandidates.empty())
10484 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10485 /*TakingAddress=*/true);
10486 else {
10487 // We have some deduction failure messages. Use them to diagnose
10488 // the function templates, and diagnose the non-template candidates
10489 // normally.
10490 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10491 IEnd = OvlExpr->decls_end();
10492 I != IEnd; ++I)
10493 if (FunctionDecl *Fun =
10494 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10495 if (!functionHasPassObjectSizeParams(Fun))
10496 S.NoteOverloadCandidate(Fun, TargetFunctionType,
10497 /*TakingAddress=*/true);
10498 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10499 }
10500 }
10501
10502 bool IsInvalidFormOfPointerToMemberFunction() const {
10503 return TargetTypeIsNonStaticMemberFunction &&
10504 !OvlExprInfo.HasFormOfMemberPointer;
10505 }
10506
10507 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10508 // TODO: Should we condition this on whether any functions might
10509 // have matched, or is it more appropriate to do that in callers?
10510 // TODO: a fixit wouldn't hurt.
10511 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10512 << TargetType << OvlExpr->getSourceRange();
10513 }
10514
10515 bool IsStaticMemberFunctionFromBoundPointer() const {
10516 return StaticMemberFunctionFromBoundPointer;
10517 }
10518
10519 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10520 S.Diag(OvlExpr->getLocStart(),
10521 diag::err_invalid_form_pointer_member_function)
10522 << OvlExpr->getSourceRange();
10523 }
10524
10525 void ComplainOfInvalidConversion() const {
10526 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10527 << OvlExpr->getName() << TargetType;
10528 }
10529
10530 void ComplainMultipleMatchesFound() const {
10531 assert(Matches.size() > 1)((Matches.size() > 1) ? static_cast<void> (0) : __assert_fail
("Matches.size() > 1", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10531, __PRETTY_FUNCTION__))
;
10532 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10533 << OvlExpr->getName()
10534 << OvlExpr->getSourceRange();
10535 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10536 /*TakingAddress=*/true);
10537 }
10538
10539 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10540
10541 int getNumMatches() const { return Matches.size(); }
10542
10543 FunctionDecl* getMatchingFunctionDecl() const {
10544 if (Matches.size() != 1) return nullptr;
10545 return Matches[0].second;
10546 }
10547
10548 const DeclAccessPair* getMatchingFunctionAccessPair() const {
10549 if (Matches.size() != 1) return nullptr;
10550 return &Matches[0].first;
10551 }
10552};
10553}
10554
10555/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10556/// an overloaded function (C++ [over.over]), where @p From is an
10557/// expression with overloaded function type and @p ToType is the type
10558/// we're trying to resolve to. For example:
10559///
10560/// @code
10561/// int f(double);
10562/// int f(int);
10563///
10564/// int (*pfd)(double) = f; // selects f(double)
10565/// @endcode
10566///
10567/// This routine returns the resulting FunctionDecl if it could be
10568/// resolved, and NULL otherwise. When @p Complain is true, this
10569/// routine will emit diagnostics if there is an error.
10570FunctionDecl *
10571Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10572 QualType TargetType,
10573 bool Complain,
10574 DeclAccessPair &FoundResult,
10575 bool *pHadMultipleCandidates) {
10576 assert(AddressOfExpr->getType() == Context.OverloadTy)((AddressOfExpr->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("AddressOfExpr->getType() == Context.OverloadTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10576, __PRETTY_FUNCTION__))
;
10577
10578 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10579 Complain);
10580 int NumMatches = Resolver.getNumMatches();
10581 FunctionDecl *Fn = nullptr;
10582 bool ShouldComplain = Complain && !Resolver.hasComplained();
10583 if (NumMatches == 0 && ShouldComplain) {
10584 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10585 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10586 else
10587 Resolver.ComplainNoMatchesFound();
10588 }
10589 else if (NumMatches > 1 && ShouldComplain)
10590 Resolver.ComplainMultipleMatchesFound();
10591 else if (NumMatches == 1) {
10592 Fn = Resolver.getMatchingFunctionDecl();
10593 assert(Fn)((Fn) ? static_cast<void> (0) : __assert_fail ("Fn", "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10593, __PRETTY_FUNCTION__))
;
10594 FoundResult = *Resolver.getMatchingFunctionAccessPair();
10595 if (Complain) {
10596 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10597 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10598 else
10599 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10600 }
10601 }
10602
10603 if (pHadMultipleCandidates)
10604 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10605 return Fn;
10606}
10607
10608/// \brief Given an expression that refers to an overloaded function, try to
10609/// resolve that overloaded function expression down to a single function.
10610///
10611/// This routine can only resolve template-ids that refer to a single function
10612/// template, where that template-id refers to a single template whose template
10613/// arguments are either provided by the template-id or have defaults,
10614/// as described in C++0x [temp.arg.explicit]p3.
10615///
10616/// If no template-ids are found, no diagnostics are emitted and NULL is
10617/// returned.
10618FunctionDecl *
10619Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10620 bool Complain,
10621 DeclAccessPair *FoundResult) {
10622 // C++ [over.over]p1:
10623 // [...] [Note: any redundant set of parentheses surrounding the
10624 // overloaded function name is ignored (5.1). ]
10625 // C++ [over.over]p1:
10626 // [...] The overloaded function name can be preceded by the &
10627 // operator.
10628
10629 // If we didn't actually find any template-ids, we're done.
10630 if (!ovl->hasExplicitTemplateArgs())
10631 return nullptr;
10632
10633 TemplateArgumentListInfo ExplicitTemplateArgs;
10634 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
10635 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10636
10637 // Look through all of the overloaded functions, searching for one
10638 // whose type matches exactly.
10639 FunctionDecl *Matched = nullptr;
10640 for (UnresolvedSetIterator I = ovl->decls_begin(),
10641 E = ovl->decls_end(); I != E; ++I) {
10642 // C++0x [temp.arg.explicit]p3:
10643 // [...] In contexts where deduction is done and fails, or in contexts
10644 // where deduction is not done, if a template argument list is
10645 // specified and it, along with any default template arguments,
10646 // identifies a single function template specialization, then the
10647 // template-id is an lvalue for the function template specialization.
10648 FunctionTemplateDecl *FunctionTemplate
10649 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10650
10651 // C++ [over.over]p2:
10652 // If the name is a function template, template argument deduction is
10653 // done (14.8.2.2), and if the argument deduction succeeds, the
10654 // resulting template argument list is used to generate a single
10655 // function template specialization, which is added to the set of
10656 // overloaded functions considered.
10657 FunctionDecl *Specialization = nullptr;
10658 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10659 if (TemplateDeductionResult Result
10660 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10661 Specialization, Info,
10662 /*InOverloadResolution=*/true)) {
10663 // Make a note of the failed deduction for diagnostics.
10664 // TODO: Actually use the failed-deduction info?
10665 FailedCandidates.addCandidate()
10666 .set(FunctionTemplate->getTemplatedDecl(),
10667 MakeDeductionFailureInfo(Context, Result, Info));
10668 continue;
10669 }
10670
10671 assert(Specialization && "no specialization and no error?")((Specialization && "no specialization and no error?"
) ? static_cast<void> (0) : __assert_fail ("Specialization && \"no specialization and no error?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10671, __PRETTY_FUNCTION__))
;
10672
10673 // Multiple matches; we can't resolve to a single declaration.
10674 if (Matched) {
10675 if (Complain) {
10676 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10677 << ovl->getName();
10678 NoteAllOverloadCandidates(ovl);
10679 }
10680 return nullptr;
10681 }
10682
10683 Matched = Specialization;
10684 if (FoundResult) *FoundResult = I.getPair();
10685 }
10686
10687 if (Matched && getLangOpts().CPlusPlus14 &&
10688 Matched->getReturnType()->isUndeducedType() &&
10689 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10690 return nullptr;
10691
10692 return Matched;
10693}
10694
10695
10696
10697
10698// Resolve and fix an overloaded expression that can be resolved
10699// because it identifies a single function template specialization.
10700//
10701// Last three arguments should only be supplied if Complain = true
10702//
10703// Return true if it was logically possible to so resolve the
10704// expression, regardless of whether or not it succeeded. Always
10705// returns true if 'complain' is set.
10706bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10707 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10708 bool complain, SourceRange OpRangeForComplaining,
10709 QualType DestTypeForComplaining,
10710 unsigned DiagIDForComplaining) {
10711 assert(SrcExpr.get()->getType() == Context.OverloadTy)((SrcExpr.get()->getType() == Context.OverloadTy) ? static_cast
<void> (0) : __assert_fail ("SrcExpr.get()->getType() == Context.OverloadTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10711, __PRETTY_FUNCTION__))
;
10712
10713 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10714
10715 DeclAccessPair found;
10716 ExprResult SingleFunctionExpression;
10717 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10718 ovl.Expression, /*complain*/ false, &found)) {
10719 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10720 SrcExpr = ExprError();
10721 return true;
10722 }
10723
10724 // It is only correct to resolve to an instance method if we're
10725 // resolving a form that's permitted to be a pointer to member.
10726 // Otherwise we'll end up making a bound member expression, which
10727 // is illegal in all the contexts we resolve like this.
10728 if (!ovl.HasFormOfMemberPointer &&
10729 isa<CXXMethodDecl>(fn) &&
10730 cast<CXXMethodDecl>(fn)->isInstance()) {
10731 if (!complain) return false;
10732
10733 Diag(ovl.Expression->getExprLoc(),
10734 diag::err_bound_member_function)
10735 << 0 << ovl.Expression->getSourceRange();
10736
10737 // TODO: I believe we only end up here if there's a mix of
10738 // static and non-static candidates (otherwise the expression
10739 // would have 'bound member' type, not 'overload' type).
10740 // Ideally we would note which candidate was chosen and why
10741 // the static candidates were rejected.
10742 SrcExpr = ExprError();
10743 return true;
10744 }
10745
10746 // Fix the expression to refer to 'fn'.
10747 SingleFunctionExpression =
10748 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10749
10750 // If desired, do function-to-pointer decay.
10751 if (doFunctionPointerConverion) {
10752 SingleFunctionExpression =
10753 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10754 if (SingleFunctionExpression.isInvalid()) {
10755 SrcExpr = ExprError();
10756 return true;
10757 }
10758 }
10759 }
10760
10761 if (!SingleFunctionExpression.isUsable()) {
10762 if (complain) {
10763 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10764 << ovl.Expression->getName()
10765 << DestTypeForComplaining
10766 << OpRangeForComplaining
10767 << ovl.Expression->getQualifierLoc().getSourceRange();
10768 NoteAllOverloadCandidates(SrcExpr.get());
10769
10770 SrcExpr = ExprError();
10771 return true;
10772 }
10773
10774 return false;
10775 }
10776
10777 SrcExpr = SingleFunctionExpression;
10778 return true;
10779}
10780
10781/// \brief Add a single candidate to the overload set.
10782static void AddOverloadedCallCandidate(Sema &S,
10783 DeclAccessPair FoundDecl,
10784 TemplateArgumentListInfo *ExplicitTemplateArgs,
10785 ArrayRef<Expr *> Args,
10786 OverloadCandidateSet &CandidateSet,
10787 bool PartialOverloading,
10788 bool KnownValid) {
10789 NamedDecl *Callee = FoundDecl.getDecl();
10790 if (isa<UsingShadowDecl>(Callee))
10791 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10792
10793 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10794 if (ExplicitTemplateArgs) {
10795 assert(!KnownValid && "Explicit template arguments?")((!KnownValid && "Explicit template arguments?") ? static_cast
<void> (0) : __assert_fail ("!KnownValid && \"Explicit template arguments?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10795, __PRETTY_FUNCTION__))
;
10796 return;
10797 }
10798 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10799 /*SuppressUsedConversions=*/false,
10800 PartialOverloading);
10801 return;
10802 }
10803
10804 if (FunctionTemplateDecl *FuncTemplate
10805 = dyn_cast<FunctionTemplateDecl>(Callee)) {
10806 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10807 ExplicitTemplateArgs, Args, CandidateSet,
10808 /*SuppressUsedConversions=*/false,
10809 PartialOverloading);
10810 return;
10811 }
10812
10813 assert(!KnownValid && "unhandled case in overloaded call candidate")((!KnownValid && "unhandled case in overloaded call candidate"
) ? static_cast<void> (0) : __assert_fail ("!KnownValid && \"unhandled case in overloaded call candidate\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10813, __PRETTY_FUNCTION__))
;
10814}
10815
10816/// \brief Add the overload candidates named by callee and/or found by argument
10817/// dependent lookup to the given overload set.
10818void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10819 ArrayRef<Expr *> Args,
10820 OverloadCandidateSet &CandidateSet,
10821 bool PartialOverloading) {
10822
10823#ifndef NDEBUG
10824 // Verify that ArgumentDependentLookup is consistent with the rules
10825 // in C++0x [basic.lookup.argdep]p3:
10826 //
10827 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10828 // and let Y be the lookup set produced by argument dependent
10829 // lookup (defined as follows). If X contains
10830 //
10831 // -- a declaration of a class member, or
10832 //
10833 // -- a block-scope function declaration that is not a
10834 // using-declaration, or
10835 //
10836 // -- a declaration that is neither a function or a function
10837 // template
10838 //
10839 // then Y is empty.
10840
10841 if (ULE->requiresADL()) {
10842 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10843 E = ULE->decls_end(); I != E; ++I) {
10844 assert(!(*I)->getDeclContext()->isRecord())((!(*I)->getDeclContext()->isRecord()) ? static_cast<
void> (0) : __assert_fail ("!(*I)->getDeclContext()->isRecord()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10844, __PRETTY_FUNCTION__))
;
10845 assert(isa<UsingShadowDecl>(*I) ||((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10846, __PRETTY_FUNCTION__))
10846 !(*I)->getDeclContext()->isFunctionOrMethod())((isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext(
)->isFunctionOrMethod()) ? static_cast<void> (0) : __assert_fail
("isa<UsingShadowDecl>(*I) || !(*I)->getDeclContext()->isFunctionOrMethod()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10846, __PRETTY_FUNCTION__))
;
10847 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate())(((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate
()) ? static_cast<void> (0) : __assert_fail ("(*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 10847, __PRETTY_FUNCTION__))
;
10848 }
10849 }
10850#endif
10851
10852 // It would be nice to avoid this copy.
10853 TemplateArgumentListInfo TABuffer;
10854 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10855 if (ULE->hasExplicitTemplateArgs()) {
10856 ULE->copyTemplateArgumentsInto(TABuffer);
10857 ExplicitTemplateArgs = &TABuffer;
10858 }
10859
10860 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10861 E = ULE->decls_end(); I != E; ++I)
10862 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10863 CandidateSet, PartialOverloading,
10864 /*KnownValid*/ true);
10865
10866 if (ULE->requiresADL())
10867 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10868 Args, ExplicitTemplateArgs,
10869 CandidateSet, PartialOverloading);
10870}
10871
10872/// Determine whether a declaration with the specified name could be moved into
10873/// a different namespace.
10874static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10875 switch (Name.getCXXOverloadedOperator()) {
10876 case OO_New: case OO_Array_New:
10877 case OO_Delete: case OO_Array_Delete:
10878 return false;
10879
10880 default:
10881 return true;
10882 }
10883}
10884
10885/// Attempt to recover from an ill-formed use of a non-dependent name in a
10886/// template, where the non-dependent name was declared after the template
10887/// was defined. This is common in code written for a compilers which do not
10888/// correctly implement two-stage name lookup.
10889///
10890/// Returns true if a viable candidate was found and a diagnostic was issued.
10891static bool
10892DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10893 const CXXScopeSpec &SS, LookupResult &R,
10894 OverloadCandidateSet::CandidateSetKind CSK,
10895 TemplateArgumentListInfo *ExplicitTemplateArgs,
10896 ArrayRef<Expr *> Args,
10897 bool *DoDiagnoseEmptyLookup = nullptr) {
10898 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10899 return false;
10900
10901 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10902 if (DC->isTransparentContext())
10903 continue;
10904
10905 SemaRef.LookupQualifiedName(R, DC);
10906
10907 if (!R.empty()) {
10908 R.suppressDiagnostics();
10909
10910 if (isa<CXXRecordDecl>(DC)) {
10911 // Don't diagnose names we find in classes; we get much better
10912 // diagnostics for these from DiagnoseEmptyLookup.
10913 R.clear();
10914 if (DoDiagnoseEmptyLookup)
10915 *DoDiagnoseEmptyLookup = true;
10916 return false;
10917 }
10918
10919 OverloadCandidateSet Candidates(FnLoc, CSK);
10920 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10921 AddOverloadedCallCandidate(SemaRef, I.getPair(),
10922 ExplicitTemplateArgs, Args,
10923 Candidates, false, /*KnownValid*/ false);
10924
10925 OverloadCandidateSet::iterator Best;
10926 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10927 // No viable functions. Don't bother the user with notes for functions
10928 // which don't work and shouldn't be found anyway.
10929 R.clear();
10930 return false;
10931 }
10932
10933 // Find the namespaces where ADL would have looked, and suggest
10934 // declaring the function there instead.
10935 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10936 Sema::AssociatedClassSet AssociatedClasses;
10937 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10938 AssociatedNamespaces,
10939 AssociatedClasses);
10940 Sema::AssociatedNamespaceSet SuggestedNamespaces;
10941 if (canBeDeclaredInNamespace(R.getLookupName())) {
10942 DeclContext *Std = SemaRef.getStdNamespace();
10943 for (Sema::AssociatedNamespaceSet::iterator
10944 it = AssociatedNamespaces.begin(),
10945 end = AssociatedNamespaces.end(); it != end; ++it) {
10946 // Never suggest declaring a function within namespace 'std'.
10947 if (Std && Std->Encloses(*it))
10948 continue;
10949
10950 // Never suggest declaring a function within a namespace with a
10951 // reserved name, like __gnu_cxx.
10952 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10953 if (NS &&
10954 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10955 continue;
10956
10957 SuggestedNamespaces.insert(*it);
10958 }
10959 }
10960
10961 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10962 << R.getLookupName();
10963 if (SuggestedNamespaces.empty()) {
10964 SemaRef.Diag(Best->Function->getLocation(),
10965 diag::note_not_found_by_two_phase_lookup)
10966 << R.getLookupName() << 0;
10967 } else if (SuggestedNamespaces.size() == 1) {
10968 SemaRef.Diag(Best->Function->getLocation(),
10969 diag::note_not_found_by_two_phase_lookup)
10970 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10971 } else {
10972 // FIXME: It would be useful to list the associated namespaces here,
10973 // but the diagnostics infrastructure doesn't provide a way to produce
10974 // a localized representation of a list of items.
10975 SemaRef.Diag(Best->Function->getLocation(),
10976 diag::note_not_found_by_two_phase_lookup)
10977 << R.getLookupName() << 2;
10978 }
10979
10980 // Try to recover by calling this function.
10981 return true;
10982 }
10983
10984 R.clear();
10985 }
10986
10987 return false;
10988}
10989
10990/// Attempt to recover from ill-formed use of a non-dependent operator in a
10991/// template, where the non-dependent operator was declared after the template
10992/// was defined.
10993///
10994/// Returns true if a viable candidate was found and a diagnostic was issued.
10995static bool
10996DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10997 SourceLocation OpLoc,
10998 ArrayRef<Expr *> Args) {
10999 DeclarationName OpName =
11000 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11001 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11002 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11003 OverloadCandidateSet::CSK_Operator,
11004 /*ExplicitTemplateArgs=*/nullptr, Args);
11005}
11006
11007namespace {
11008class BuildRecoveryCallExprRAII {
11009 Sema &SemaRef;
11010public:
11011 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11012 assert(SemaRef.IsBuildingRecoveryCallExpr == false)((SemaRef.IsBuildingRecoveryCallExpr == false) ? static_cast<
void> (0) : __assert_fail ("SemaRef.IsBuildingRecoveryCallExpr == false"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11012, __PRETTY_FUNCTION__))
;
11013 SemaRef.IsBuildingRecoveryCallExpr = true;
11014 }
11015
11016 ~BuildRecoveryCallExprRAII() {
11017 SemaRef.IsBuildingRecoveryCallExpr = false;
11018 }
11019};
11020
11021}
11022
11023static std::unique_ptr<CorrectionCandidateCallback>
11024MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11025 bool HasTemplateArgs, bool AllowTypoCorrection) {
11026 if (!AllowTypoCorrection)
11027 return llvm::make_unique<NoTypoCorrectionCCC>();
11028 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11029 HasTemplateArgs, ME);
11030}
11031
11032/// Attempts to recover from a call where no functions were found.
11033///
11034/// Returns true if new candidates were found.
11035static ExprResult
11036BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11037 UnresolvedLookupExpr *ULE,
11038 SourceLocation LParenLoc,
11039 MutableArrayRef<Expr *> Args,
11040 SourceLocation RParenLoc,
11041 bool EmptyLookup, bool AllowTypoCorrection) {
11042 // Do not try to recover if it is already building a recovery call.
11043 // This stops infinite loops for template instantiations like
11044 //
11045 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11046 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11047 //
11048 if (SemaRef.IsBuildingRecoveryCallExpr)
11049 return ExprError();
11050 BuildRecoveryCallExprRAII RCE(SemaRef);
11051
11052 CXXScopeSpec SS;
11053 SS.Adopt(ULE->getQualifierLoc());
11054 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11055
11056 TemplateArgumentListInfo TABuffer;
11057 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11058 if (ULE->hasExplicitTemplateArgs()) {
11059 ULE->copyTemplateArgumentsInto(TABuffer);
11060 ExplicitTemplateArgs = &TABuffer;
11061 }
11062
11063 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11064 Sema::LookupOrdinaryName);
11065 bool DoDiagnoseEmptyLookup = EmptyLookup;
11066 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11067 OverloadCandidateSet::CSK_Normal,
11068 ExplicitTemplateArgs, Args,
11069 &DoDiagnoseEmptyLookup) &&
11070 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11071 S, SS, R,
11072 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11073 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11074 ExplicitTemplateArgs, Args)))
11075 return ExprError();
11076
11077 assert(!R.empty() && "lookup results empty despite recovery")((!R.empty() && "lookup results empty despite recovery"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"lookup results empty despite recovery\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11077, __PRETTY_FUNCTION__))
;
11078
11079 // Build an implicit member call if appropriate. Just drop the
11080 // casts and such from the call, we don't really care.
11081 ExprResult NewFn = ExprError();
11082 if ((*R.begin())->isCXXClassMember())
11083 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11084 ExplicitTemplateArgs, S);
11085 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11086 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11087 ExplicitTemplateArgs);
11088 else
11089 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11090
11091 if (NewFn.isInvalid())
11092 return ExprError();
11093
11094 // This shouldn't cause an infinite loop because we're giving it
11095 // an expression with viable lookup results, which should never
11096 // end up here.
11097 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11098 MultiExprArg(Args.data(), Args.size()),
11099 RParenLoc);
11100}
11101
11102/// \brief Constructs and populates an OverloadedCandidateSet from
11103/// the given function.
11104/// \returns true when an the ExprResult output parameter has been set.
11105bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11106 UnresolvedLookupExpr *ULE,
11107 MultiExprArg Args,
11108 SourceLocation RParenLoc,
11109 OverloadCandidateSet *CandidateSet,
11110 ExprResult *Result) {
11111#ifndef NDEBUG
11112 if (ULE->requiresADL()) {
11113 // To do ADL, we must have found an unqualified name.
11114 assert(!ULE->getQualifier() && "qualified name with ADL")((!ULE->getQualifier() && "qualified name with ADL"
) ? static_cast<void> (0) : __assert_fail ("!ULE->getQualifier() && \"qualified name with ADL\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11114, __PRETTY_FUNCTION__))
;
11115
11116 // We don't perform ADL for implicit declarations of builtins.
11117 // Verify that this was correctly set up.
11118 FunctionDecl *F;
11119 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11120 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11121 F->getBuiltinID() && F->isImplicit())
11122 llvm_unreachable("performing ADL for builtin")::llvm::llvm_unreachable_internal("performing ADL for builtin"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11122)
;
11123
11124 // We don't perform ADL in C.
11125 assert(getLangOpts().CPlusPlus && "ADL enabled in C")((getLangOpts().CPlusPlus && "ADL enabled in C") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL enabled in C\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11125, __PRETTY_FUNCTION__))
;
11126 }
11127#endif
11128
11129 UnbridgedCastsSet UnbridgedCasts;
11130 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11131 *Result = ExprError();
11132 return true;
11133 }
11134
11135 // Add the functions denoted by the callee to the set of candidate
11136 // functions, including those from argument-dependent lookup.
11137 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11138
11139 if (getLangOpts().MSVCCompat &&
11140 CurContext->isDependentContext() && !isSFINAEContext() &&
11141 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11142
11143 OverloadCandidateSet::iterator Best;
11144 if (CandidateSet->empty() ||
11145 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11146 OR_No_Viable_Function) {
11147 // In Microsoft mode, if we are inside a template class member function then
11148 // create a type dependent CallExpr. The goal is to postpone name lookup
11149 // to instantiation time to be able to search into type dependent base
11150 // classes.
11151 CallExpr *CE = new (Context) CallExpr(
11152 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11153 CE->setTypeDependent(true);
11154 CE->setValueDependent(true);
11155 CE->setInstantiationDependent(true);
11156 *Result = CE;
11157 return true;
11158 }
11159 }
11160
11161 if (CandidateSet->empty())
11162 return false;
11163
11164 UnbridgedCasts.restore();
11165 return false;
11166}
11167
11168/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11169/// the completed call expression. If overload resolution fails, emits
11170/// diagnostics and returns ExprError()
11171static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11172 UnresolvedLookupExpr *ULE,
11173 SourceLocation LParenLoc,
11174 MultiExprArg Args,
11175 SourceLocation RParenLoc,
11176 Expr *ExecConfig,
11177 OverloadCandidateSet *CandidateSet,
11178 OverloadCandidateSet::iterator *Best,
11179 OverloadingResult OverloadResult,
11180 bool AllowTypoCorrection) {
11181 if (CandidateSet->empty())
11182 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11183 RParenLoc, /*EmptyLookup=*/true,
11184 AllowTypoCorrection);
11185
11186 switch (OverloadResult) {
11187 case OR_Success: {
11188 FunctionDecl *FDecl = (*Best)->Function;
11189 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11190 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11191 return ExprError();
11192 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11193 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11194 ExecConfig);
11195 }
11196
11197 case OR_No_Viable_Function: {
11198 // Try to recover by looking for viable functions which the user might
11199 // have meant to call.
11200 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11201 Args, RParenLoc,
11202 /*EmptyLookup=*/false,
11203 AllowTypoCorrection);
11204 if (!Recovery.isInvalid())
11205 return Recovery;
11206
11207 // If the user passes in a function that we can't take the address of, we
11208 // generally end up emitting really bad error messages. Here, we attempt to
11209 // emit better ones.
11210 for (const Expr *Arg : Args) {
11211 if (!Arg->getType()->isFunctionType())
11212 continue;
11213 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11214 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11215 if (FD &&
11216 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11217 Arg->getExprLoc()))
11218 return ExprError();
11219 }
11220 }
11221
11222 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11223 << ULE->getName() << Fn->getSourceRange();
11224 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11225 break;
11226 }
11227
11228 case OR_Ambiguous:
11229 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11230 << ULE->getName() << Fn->getSourceRange();
11231 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11232 break;
11233
11234 case OR_Deleted: {
11235 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11236 << (*Best)->Function->isDeleted()
11237 << ULE->getName()
11238 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11239 << Fn->getSourceRange();
11240 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11241
11242 // We emitted an error for the unvailable/deleted function call but keep
11243 // the call in the AST.
11244 FunctionDecl *FDecl = (*Best)->Function;
11245 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11246 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11247 ExecConfig);
11248 }
11249 }
11250
11251 // Overload resolution failed.
11252 return ExprError();
11253}
11254
11255static void markUnaddressableCandidatesUnviable(Sema &S,
11256 OverloadCandidateSet &CS) {
11257 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11258 if (I->Viable &&
11259 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11260 I->Viable = false;
11261 I->FailureKind = ovl_fail_addr_not_available;
11262 }
11263 }
11264}
11265
11266/// BuildOverloadedCallExpr - Given the call expression that calls Fn
11267/// (which eventually refers to the declaration Func) and the call
11268/// arguments Args/NumArgs, attempt to resolve the function call down
11269/// to a specific function. If overload resolution succeeds, returns
11270/// the call expression produced by overload resolution.
11271/// Otherwise, emits diagnostics and returns ExprError.
11272ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11273 UnresolvedLookupExpr *ULE,
11274 SourceLocation LParenLoc,
11275 MultiExprArg Args,
11276 SourceLocation RParenLoc,
11277 Expr *ExecConfig,
11278 bool AllowTypoCorrection,
11279 bool CalleesAddressIsTaken) {
11280 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11281 OverloadCandidateSet::CSK_Normal);
11282 ExprResult result;
11283
11284 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11285 &result))
11286 return result;
11287
11288 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11289 // functions that aren't addressible are considered unviable.
11290 if (CalleesAddressIsTaken)
11291 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11292
11293 OverloadCandidateSet::iterator Best;
11294 OverloadingResult OverloadResult =
11295 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11296
11297 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11298 RParenLoc, ExecConfig, &CandidateSet,
11299 &Best, OverloadResult,
11300 AllowTypoCorrection);
11301}
11302
11303static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11304 return Functions.size() > 1 ||
11305 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11306}
11307
11308/// \brief Create a unary operation that may resolve to an overloaded
11309/// operator.
11310///
11311/// \param OpLoc The location of the operator itself (e.g., '*').
11312///
11313/// \param Opc The UnaryOperatorKind that describes this operator.
11314///
11315/// \param Fns The set of non-member functions that will be
11316/// considered by overload resolution. The caller needs to build this
11317/// set based on the context using, e.g.,
11318/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11319/// set should not contain any member functions; those will be added
11320/// by CreateOverloadedUnaryOp().
11321///
11322/// \param Input The input argument.
11323ExprResult
11324Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11325 const UnresolvedSetImpl &Fns,
11326 Expr *Input) {
11327 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11328 assert(Op != OO_None && "Invalid opcode for overloaded unary operator")((Op != OO_None && "Invalid opcode for overloaded unary operator"
) ? static_cast<void> (0) : __assert_fail ("Op != OO_None && \"Invalid opcode for overloaded unary operator\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11328, __PRETTY_FUNCTION__))
;
11329 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11330 // TODO: provide better source location info.
11331 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11332
11333 if (checkPlaceholderForOverload(*this, Input))
11334 return ExprError();
11335
11336 Expr *Args[2] = { Input, nullptr };
11337 unsigned NumArgs = 1;
11338
11339 // For post-increment and post-decrement, add the implicit '0' as
11340 // the second argument, so that we know this is a post-increment or
11341 // post-decrement.
11342 if (Opc == UO_PostInc || Opc == UO_PostDec) {
11343 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11344 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11345 SourceLocation());
11346 NumArgs = 2;
11347 }
11348
11349 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11350
11351 if (Input->isTypeDependent()) {
11352 if (Fns.empty())
11353 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11354 VK_RValue, OK_Ordinary, OpLoc);
11355
11356 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11357 UnresolvedLookupExpr *Fn
11358 = UnresolvedLookupExpr::Create(Context, NamingClass,
11359 NestedNameSpecifierLoc(), OpNameInfo,
11360 /*ADL*/ true, IsOverloaded(Fns),
11361 Fns.begin(), Fns.end());
11362 return new (Context)
11363 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11364 VK_RValue, OpLoc, false);
11365 }
11366
11367 // Build an empty overload set.
11368 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11369
11370 // Add the candidates from the given function set.
11371 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11372
11373 // Add operator candidates that are member functions.
11374 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11375
11376 // Add candidates from ADL.
11377 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11378 /*ExplicitTemplateArgs*/nullptr,
11379 CandidateSet);
11380
11381 // Add builtin operator candidates.
11382 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11383
11384 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11385
11386 // Perform overload resolution.
11387 OverloadCandidateSet::iterator Best;
11388 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11389 case OR_Success: {
11390 // We found a built-in operator or an overloaded operator.
11391 FunctionDecl *FnDecl = Best->Function;
11392
11393 if (FnDecl) {
11394 // We matched an overloaded operator. Build a call to that
11395 // operator.
11396
11397 // Convert the arguments.
11398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11399 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11400
11401 ExprResult InputRes =
11402 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11403 Best->FoundDecl, Method);
11404 if (InputRes.isInvalid())
11405 return ExprError();
11406 Input = InputRes.get();
11407 } else {
11408 // Convert the arguments.
11409 ExprResult InputInit
11410 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11411 Context,
11412 FnDecl->getParamDecl(0)),
11413 SourceLocation(),
11414 Input);
11415 if (InputInit.isInvalid())
11416 return ExprError();
11417 Input = InputInit.get();
11418 }
11419
11420 // Build the actual expression node.
11421 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11422 HadMultipleCandidates, OpLoc);
11423 if (FnExpr.isInvalid())
11424 return ExprError();
11425
11426 // Determine the result type.
11427 QualType ResultTy = FnDecl->getReturnType();
11428 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11429 ResultTy = ResultTy.getNonLValueExprType(Context);
11430
11431 Args[0] = Input;
11432 CallExpr *TheCall =
11433 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11434 ResultTy, VK, OpLoc, false);
11435
11436 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11437 return ExprError();
11438
11439 return MaybeBindToTemporary(TheCall);
11440 } else {
11441 // We matched a built-in operator. Convert the arguments, then
11442 // break out so that we will build the appropriate built-in
11443 // operator node.
11444 ExprResult InputRes =
11445 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11446 Best->Conversions[0], AA_Passing);
11447 if (InputRes.isInvalid())
11448 return ExprError();
11449 Input = InputRes.get();
11450 break;
11451 }
11452 }
11453
11454 case OR_No_Viable_Function:
11455 // This is an erroneous use of an operator which can be overloaded by
11456 // a non-member function. Check for non-member operators which were
11457 // defined too late to be candidates.
11458 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11459 // FIXME: Recover by calling the found function.
11460 return ExprError();
11461
11462 // No viable function; fall through to handling this as a
11463 // built-in operator, which will produce an error message for us.
11464 break;
11465
11466 case OR_Ambiguous:
11467 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11468 << UnaryOperator::getOpcodeStr(Opc)
11469 << Input->getType()
11470 << Input->getSourceRange();
11471 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11472 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11473 return ExprError();
11474
11475 case OR_Deleted:
11476 Diag(OpLoc, diag::err_ovl_deleted_oper)
11477 << Best->Function->isDeleted()
11478 << UnaryOperator::getOpcodeStr(Opc)
11479 << getDeletedOrUnavailableSuffix(Best->Function)
11480 << Input->getSourceRange();
11481 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11482 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11483 return ExprError();
11484 }
11485
11486 // Either we found no viable overloaded operator or we matched a
11487 // built-in operator. In either case, fall through to trying to
11488 // build a built-in operation.
11489 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11490}
11491
11492/// \brief Create a binary operation that may resolve to an overloaded
11493/// operator.
11494///
11495/// \param OpLoc The location of the operator itself (e.g., '+').
11496///
11497/// \param Opc The BinaryOperatorKind that describes this operator.
11498///
11499/// \param Fns The set of non-member functions that will be
11500/// considered by overload resolution. The caller needs to build this
11501/// set based on the context using, e.g.,
11502/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11503/// set should not contain any member functions; those will be added
11504/// by CreateOverloadedBinOp().
11505///
11506/// \param LHS Left-hand argument.
11507/// \param RHS Right-hand argument.
11508ExprResult
11509Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11510 BinaryOperatorKind Opc,
11511 const UnresolvedSetImpl &Fns,
11512 Expr *LHS, Expr *RHS) {
11513 Expr *Args[2] = { LHS, RHS };
11514 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11515
11516 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11517 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11518
11519 // If either side is type-dependent, create an appropriate dependent
11520 // expression.
11521 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11522 if (Fns.empty()) {
11523 // If there are no functions to store, just build a dependent
11524 // BinaryOperator or CompoundAssignment.
11525 if (Opc <= BO_Assign || Opc > BO_OrAssign)
11526 return new (Context) BinaryOperator(
11527 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11528 OpLoc, FPFeatures.fp_contract);
11529
11530 return new (Context) CompoundAssignOperator(
11531 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11532 Context.DependentTy, Context.DependentTy, OpLoc,
11533 FPFeatures.fp_contract);
11534 }
11535
11536 // FIXME: save results of ADL from here?
11537 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11538 // TODO: provide better source location info in DNLoc component.
11539 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11540 UnresolvedLookupExpr *Fn
11541 = UnresolvedLookupExpr::Create(Context, NamingClass,
11542 NestedNameSpecifierLoc(), OpNameInfo,
11543 /*ADL*/ true, IsOverloaded(Fns),
11544 Fns.begin(), Fns.end());
11545 return new (Context)
11546 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11547 VK_RValue, OpLoc, FPFeatures.fp_contract);
11548 }
11549
11550 // Always do placeholder-like conversions on the RHS.
11551 if (checkPlaceholderForOverload(*this, Args[1]))
11552 return ExprError();
11553
11554 // Do placeholder-like conversion on the LHS; note that we should
11555 // not get here with a PseudoObject LHS.
11556 assert(Args[0]->getObjectKind() != OK_ObjCProperty)((Args[0]->getObjectKind() != OK_ObjCProperty) ? static_cast
<void> (0) : __assert_fail ("Args[0]->getObjectKind() != OK_ObjCProperty"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11556, __PRETTY_FUNCTION__))
;
11557 if (checkPlaceholderForOverload(*this, Args[0]))
11558 return ExprError();
11559
11560 // If this is the assignment operator, we only perform overload resolution
11561 // if the left-hand side is a class or enumeration type. This is actually
11562 // a hack. The standard requires that we do overload resolution between the
11563 // various built-in candidates, but as DR507 points out, this can lead to
11564 // problems. So we do it this way, which pretty much follows what GCC does.
11565 // Note that we go the traditional code path for compound assignment forms.
11566 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11567 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11568
11569 // If this is the .* operator, which is not overloadable, just
11570 // create a built-in binary operator.
11571 if (Opc == BO_PtrMemD)
11572 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11573
11574 // Build an empty overload set.
11575 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11576
11577 // Add the candidates from the given function set.
11578 AddFunctionCandidates(Fns, Args, CandidateSet);
11579
11580 // Add operator candidates that are member functions.
11581 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11582
11583 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11584 // performed for an assignment operator (nor for operator[] nor operator->,
11585 // which don't get here).
11586 if (Opc != BO_Assign)
11587 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11588 /*ExplicitTemplateArgs*/ nullptr,
11589 CandidateSet);
11590
11591 // Add builtin operator candidates.
11592 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11593
11594 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11595
11596 // Perform overload resolution.
11597 OverloadCandidateSet::iterator Best;
11598 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11599 case OR_Success: {
11600 // We found a built-in operator or an overloaded operator.
11601 FunctionDecl *FnDecl = Best->Function;
11602
11603 if (FnDecl) {
11604 // We matched an overloaded operator. Build a call to that
11605 // operator.
11606
11607 // Convert the arguments.
11608 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11609 // Best->Access is only meaningful for class members.
11610 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
11611
11612 ExprResult Arg1 =
11613 PerformCopyInitialization(
11614 InitializedEntity::InitializeParameter(Context,
11615 FnDecl->getParamDecl(0)),
11616 SourceLocation(), Args[1]);
11617 if (Arg1.isInvalid())
11618 return ExprError();
11619
11620 ExprResult Arg0 =
11621 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11622 Best->FoundDecl, Method);
11623 if (Arg0.isInvalid())
11624 return ExprError();
11625 Args[0] = Arg0.getAs<Expr>();
11626 Args[1] = RHS = Arg1.getAs<Expr>();
11627 } else {
11628 // Convert the arguments.
11629 ExprResult Arg0 = PerformCopyInitialization(
11630 InitializedEntity::InitializeParameter(Context,
11631 FnDecl->getParamDecl(0)),
11632 SourceLocation(), Args[0]);
11633 if (Arg0.isInvalid())
11634 return ExprError();
11635
11636 ExprResult Arg1 =
11637 PerformCopyInitialization(
11638 InitializedEntity::InitializeParameter(Context,
11639 FnDecl->getParamDecl(1)),
11640 SourceLocation(), Args[1]);
11641 if (Arg1.isInvalid())
11642 return ExprError();
11643 Args[0] = LHS = Arg0.getAs<Expr>();
11644 Args[1] = RHS = Arg1.getAs<Expr>();
11645 }
11646
11647 // Build the actual expression node.
11648 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11649 Best->FoundDecl,
11650 HadMultipleCandidates, OpLoc);
11651 if (FnExpr.isInvalid())
11652 return ExprError();
11653
11654 // Determine the result type.
11655 QualType ResultTy = FnDecl->getReturnType();
11656 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11657 ResultTy = ResultTy.getNonLValueExprType(Context);
11658
11659 CXXOperatorCallExpr *TheCall =
11660 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11661 Args, ResultTy, VK, OpLoc,
11662 FPFeatures.fp_contract);
11663
11664 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11665 FnDecl))
11666 return ExprError();
11667
11668 ArrayRef<const Expr *> ArgsArray(Args, 2);
11669 // Cut off the implicit 'this'.
11670 if (isa<CXXMethodDecl>(FnDecl))
11671 ArgsArray = ArgsArray.slice(1);
11672
11673 // Check for a self move.
11674 if (Op == OO_Equal)
11675 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11676
11677 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
11678 TheCall->getSourceRange(), VariadicDoesNotApply);
11679
11680 return MaybeBindToTemporary(TheCall);
11681 } else {
11682 // We matched a built-in operator. Convert the arguments, then
11683 // break out so that we will build the appropriate built-in
11684 // operator node.
11685 ExprResult ArgsRes0 =
11686 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11687 Best->Conversions[0], AA_Passing);
11688 if (ArgsRes0.isInvalid())
11689 return ExprError();
11690 Args[0] = ArgsRes0.get();
11691
11692 ExprResult ArgsRes1 =
11693 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11694 Best->Conversions[1], AA_Passing);
11695 if (ArgsRes1.isInvalid())
11696 return ExprError();
11697 Args[1] = ArgsRes1.get();
11698 break;
11699 }
11700 }
11701
11702 case OR_No_Viable_Function: {
11703 // C++ [over.match.oper]p9:
11704 // If the operator is the operator , [...] and there are no
11705 // viable functions, then the operator is assumed to be the
11706 // built-in operator and interpreted according to clause 5.
11707 if (Opc == BO_Comma)
11708 break;
11709
11710 // For class as left operand for assignment or compound assigment
11711 // operator do not fall through to handling in built-in, but report that
11712 // no overloaded assignment operator found
11713 ExprResult Result = ExprError();
11714 if (Args[0]->getType()->isRecordType() &&
11715 Opc >= BO_Assign && Opc <= BO_OrAssign) {
11716 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11717 << BinaryOperator::getOpcodeStr(Opc)
11718 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11719 if (Args[0]->getType()->isIncompleteType()) {
11720 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11721 << Args[0]->getType()
11722 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11723 }
11724 } else {
11725 // This is an erroneous use of an operator which can be overloaded by
11726 // a non-member function. Check for non-member operators which were
11727 // defined too late to be candidates.
11728 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11729 // FIXME: Recover by calling the found function.
11730 return ExprError();
11731
11732 // No viable function; try to create a built-in operation, which will
11733 // produce an error. Then, show the non-viable candidates.
11734 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11735 }
11736 assert(Result.isInvalid() &&((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11737, __PRETTY_FUNCTION__))
11737 "C++ binary operator overloading is missing candidates!")((Result.isInvalid() && "C++ binary operator overloading is missing candidates!"
) ? static_cast<void> (0) : __assert_fail ("Result.isInvalid() && \"C++ binary operator overloading is missing candidates!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11737, __PRETTY_FUNCTION__))
;
11738 if (Result.isInvalid())
11739 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11740 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11741 return Result;
11742 }
11743
11744 case OR_Ambiguous:
11745 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
11746 << BinaryOperator::getOpcodeStr(Opc)
11747 << Args[0]->getType() << Args[1]->getType()
11748 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11749 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11750 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11751 return ExprError();
11752
11753 case OR_Deleted:
11754 if (isImplicitlyDeleted(Best->Function)) {
11755 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11756 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11757 << Context.getRecordType(Method->getParent())
11758 << getSpecialMember(Method);
11759
11760 // The user probably meant to call this special member. Just
11761 // explain why it's deleted.
11762 NoteDeletedFunction(Method);
11763 return ExprError();
11764 } else {
11765 Diag(OpLoc, diag::err_ovl_deleted_oper)
11766 << Best->Function->isDeleted()
11767 << BinaryOperator::getOpcodeStr(Opc)
11768 << getDeletedOrUnavailableSuffix(Best->Function)
11769 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11770 }
11771 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11772 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11773 return ExprError();
11774 }
11775
11776 // We matched a built-in operator; build it.
11777 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11778}
11779
11780ExprResult
11781Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11782 SourceLocation RLoc,
11783 Expr *Base, Expr *Idx) {
11784 Expr *Args[2] = { Base, Idx };
11785 DeclarationName OpName =
11786 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11787
11788 // If either side is type-dependent, create an appropriate dependent
11789 // expression.
11790 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11791
11792 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11793 // CHECKME: no 'operator' keyword?
11794 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11795 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11796 UnresolvedLookupExpr *Fn
11797 = UnresolvedLookupExpr::Create(Context, NamingClass,
11798 NestedNameSpecifierLoc(), OpNameInfo,
11799 /*ADL*/ true, /*Overloaded*/ false,
11800 UnresolvedSetIterator(),
11801 UnresolvedSetIterator());
11802 // Can't add any actual overloads yet
11803
11804 return new (Context)
11805 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11806 Context.DependentTy, VK_RValue, RLoc, false);
11807 }
11808
11809 // Handle placeholders on both operands.
11810 if (checkPlaceholderForOverload(*this, Args[0]))
11811 return ExprError();
11812 if (checkPlaceholderForOverload(*this, Args[1]))
11813 return ExprError();
11814
11815 // Build an empty overload set.
11816 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11817
11818 // Subscript can only be overloaded as a member function.
11819
11820 // Add operator candidates that are member functions.
11821 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11822
11823 // Add builtin operator candidates.
11824 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11825
11826 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11827
11828 // Perform overload resolution.
11829 OverloadCandidateSet::iterator Best;
11830 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11831 case OR_Success: {
11832 // We found a built-in operator or an overloaded operator.
11833 FunctionDecl *FnDecl = Best->Function;
11834
11835 if (FnDecl) {
11836 // We matched an overloaded operator. Build a call to that
11837 // operator.
11838
11839 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11840
11841 // Convert the arguments.
11842 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11843 ExprResult Arg0 =
11844 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11845 Best->FoundDecl, Method);
11846 if (Arg0.isInvalid())
11847 return ExprError();
11848 Args[0] = Arg0.get();
11849
11850 // Convert the arguments.
11851 ExprResult InputInit
11852 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11853 Context,
11854 FnDecl->getParamDecl(0)),
11855 SourceLocation(),
11856 Args[1]);
11857 if (InputInit.isInvalid())
11858 return ExprError();
11859
11860 Args[1] = InputInit.getAs<Expr>();
11861
11862 // Build the actual expression node.
11863 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11864 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11865 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11866 Best->FoundDecl,
11867 HadMultipleCandidates,
11868 OpLocInfo.getLoc(),
11869 OpLocInfo.getInfo());
11870 if (FnExpr.isInvalid())
11871 return ExprError();
11872
11873 // Determine the result type
11874 QualType ResultTy = FnDecl->getReturnType();
11875 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11876 ResultTy = ResultTy.getNonLValueExprType(Context);
11877
11878 CXXOperatorCallExpr *TheCall =
11879 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11880 FnExpr.get(), Args,
11881 ResultTy, VK, RLoc,
11882 false);
11883
11884 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11885 return ExprError();
11886
11887 return MaybeBindToTemporary(TheCall);
11888 } else {
11889 // We matched a built-in operator. Convert the arguments, then
11890 // break out so that we will build the appropriate built-in
11891 // operator node.
11892 ExprResult ArgsRes0 =
11893 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11894 Best->Conversions[0], AA_Passing);
11895 if (ArgsRes0.isInvalid())
11896 return ExprError();
11897 Args[0] = ArgsRes0.get();
11898
11899 ExprResult ArgsRes1 =
11900 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11901 Best->Conversions[1], AA_Passing);
11902 if (ArgsRes1.isInvalid())
11903 return ExprError();
11904 Args[1] = ArgsRes1.get();
11905
11906 break;
11907 }
11908 }
11909
11910 case OR_No_Viable_Function: {
11911 if (CandidateSet.empty())
11912 Diag(LLoc, diag::err_ovl_no_oper)
11913 << Args[0]->getType() << /*subscript*/ 0
11914 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11915 else
11916 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11917 << Args[0]->getType()
11918 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11919 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11920 "[]", LLoc);
11921 return ExprError();
11922 }
11923
11924 case OR_Ambiguous:
11925 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
11926 << "[]"
11927 << Args[0]->getType() << Args[1]->getType()
11928 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11929 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11930 "[]", LLoc);
11931 return ExprError();
11932
11933 case OR_Deleted:
11934 Diag(LLoc, diag::err_ovl_deleted_oper)
11935 << Best->Function->isDeleted() << "[]"
11936 << getDeletedOrUnavailableSuffix(Best->Function)
11937 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11938 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11939 "[]", LLoc);
11940 return ExprError();
11941 }
11942
11943 // We matched a built-in operator; build it.
11944 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11945}
11946
11947/// BuildCallToMemberFunction - Build a call to a member
11948/// function. MemExpr is the expression that refers to the member
11949/// function (and includes the object parameter), Args/NumArgs are the
11950/// arguments to the function call (not including the object
11951/// parameter). The caller needs to validate that the member
11952/// expression refers to a non-static member function or an overloaded
11953/// member function.
11954ExprResult
11955Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11956 SourceLocation LParenLoc,
11957 MultiExprArg Args,
11958 SourceLocation RParenLoc) {
11959 assert(MemExprE->getType() == Context.BoundMemberTy ||((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11960, __PRETTY_FUNCTION__))
11960 MemExprE->getType() == Context.OverloadTy)((MemExprE->getType() == Context.BoundMemberTy || MemExprE
->getType() == Context.OverloadTy) ? static_cast<void>
(0) : __assert_fail ("MemExprE->getType() == Context.BoundMemberTy || MemExprE->getType() == Context.OverloadTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11960, __PRETTY_FUNCTION__))
;
11961
11962 // Dig out the member expression. This holds both the object
11963 // argument and the member function we're referring to.
11964 Expr *NakedMemExpr = MemExprE->IgnoreParens();
11965
11966 // Determine whether this is a call to a pointer-to-member function.
11967 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11968 assert(op->getType() == Context.BoundMemberTy)((op->getType() == Context.BoundMemberTy) ? static_cast<
void> (0) : __assert_fail ("op->getType() == Context.BoundMemberTy"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11968, __PRETTY_FUNCTION__))
;
11969 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI)((op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI
) ? static_cast<void> (0) : __assert_fail ("op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 11969, __PRETTY_FUNCTION__))
;
11970
11971 QualType fnType =
11972 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11973
11974 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11975 QualType resultType = proto->getCallResultType(Context);
11976 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11977
11978 // Check that the object type isn't more qualified than the
11979 // member function we're calling.
11980 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11981
11982 QualType objectType = op->getLHS()->getType();
11983 if (op->getOpcode() == BO_PtrMemI)
11984 objectType = objectType->castAs<PointerType>()->getPointeeType();
11985 Qualifiers objectQuals = objectType.getQualifiers();
11986
11987 Qualifiers difference = objectQuals - funcQuals;
11988 difference.removeObjCGCAttr();
11989 difference.removeAddressSpace();
11990 if (difference) {
11991 std::string qualsString = difference.getAsString();
11992 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11993 << fnType.getUnqualifiedType()
11994 << qualsString
11995 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11996 }
11997
11998 CXXMemberCallExpr *call
11999 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12000 resultType, valueKind, RParenLoc);
12001
12002 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12003 call, nullptr))
12004 return ExprError();
12005
12006 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12007 return ExprError();
12008
12009 if (CheckOtherCall(call, proto))
12010 return ExprError();
12011
12012 return MaybeBindToTemporary(call);
12013 }
12014
12015 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12016 return new (Context)
12017 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12018
12019 UnbridgedCastsSet UnbridgedCasts;
12020 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12021 return ExprError();
12022
12023 MemberExpr *MemExpr;
12024 CXXMethodDecl *Method = nullptr;
12025 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12026 NestedNameSpecifier *Qualifier = nullptr;
12027 if (isa<MemberExpr>(NakedMemExpr)) {
12028 MemExpr = cast<MemberExpr>(NakedMemExpr);
12029 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12030 FoundDecl = MemExpr->getFoundDecl();
12031 Qualifier = MemExpr->getQualifier();
12032 UnbridgedCasts.restore();
12033 } else {
12034 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12035 Qualifier = UnresExpr->getQualifier();
12036
12037 QualType ObjectType = UnresExpr->getBaseType();
12038 Expr::Classification ObjectClassification
12039 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12040 : UnresExpr->getBase()->Classify(Context);
12041
12042 // Add overload candidates
12043 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12044 OverloadCandidateSet::CSK_Normal);
12045
12046 // FIXME: avoid copy.
12047 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12048 if (UnresExpr->hasExplicitTemplateArgs()) {
12049 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12050 TemplateArgs = &TemplateArgsBuffer;
12051 }
12052
12053 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12054 E = UnresExpr->decls_end(); I != E; ++I) {
12055
12056 NamedDecl *Func = *I;
12057 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12058 if (isa<UsingShadowDecl>(Func))
12059 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12060
12061
12062 // Microsoft supports direct constructor calls.
12063 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12064 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12065 Args, CandidateSet);
12066 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12067 // If explicit template arguments were provided, we can't call a
12068 // non-template member function.
12069 if (TemplateArgs)
12070 continue;
12071
12072 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12073 ObjectClassification, Args, CandidateSet,
12074 /*SuppressUserConversions=*/false);
12075 } else {
12076 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12077 I.getPair(), ActingDC, TemplateArgs,
12078 ObjectType, ObjectClassification,
12079 Args, CandidateSet,
12080 /*SuppressUsedConversions=*/false);
12081 }
12082 }
12083
12084 DeclarationName DeclName = UnresExpr->getMemberName();
12085
12086 UnbridgedCasts.restore();
12087
12088 OverloadCandidateSet::iterator Best;
12089 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12090 Best)) {
12091 case OR_Success:
12092 Method = cast<CXXMethodDecl>(Best->Function);
12093 FoundDecl = Best->FoundDecl;
12094 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12095 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12096 return ExprError();
12097 // If FoundDecl is different from Method (such as if one is a template
12098 // and the other a specialization), make sure DiagnoseUseOfDecl is
12099 // called on both.
12100 // FIXME: This would be more comprehensively addressed by modifying
12101 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12102 // being used.
12103 if (Method != FoundDecl.getDecl() &&
12104 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12105 return ExprError();
12106 break;
12107
12108 case OR_No_Viable_Function:
12109 Diag(UnresExpr->getMemberLoc(),
12110 diag::err_ovl_no_viable_member_function_in_call)
12111 << DeclName << MemExprE->getSourceRange();
12112 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12113 // FIXME: Leaking incoming expressions!
12114 return ExprError();
12115
12116 case OR_Ambiguous:
12117 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12118 << DeclName << MemExprE->getSourceRange();
12119 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12120 // FIXME: Leaking incoming expressions!
12121 return ExprError();
12122
12123 case OR_Deleted:
12124 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12125 << Best->Function->isDeleted()
12126 << DeclName
12127 << getDeletedOrUnavailableSuffix(Best->Function)
12128 << MemExprE->getSourceRange();
12129 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12130 // FIXME: Leaking incoming expressions!
12131 return ExprError();
12132 }
12133
12134 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12135
12136 // If overload resolution picked a static member, build a
12137 // non-member call based on that function.
12138 if (Method->isStatic()) {
12139 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12140 RParenLoc);
12141 }
12142
12143 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12144 }
12145
12146 QualType ResultType = Method->getReturnType();
12147 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12148 ResultType = ResultType.getNonLValueExprType(Context);
12149
12150 assert(Method && "Member call to something that isn't a method?")((Method && "Member call to something that isn't a method?"
) ? static_cast<void> (0) : __assert_fail ("Method && \"Member call to something that isn't a method?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12150, __PRETTY_FUNCTION__))
;
12151 CXXMemberCallExpr *TheCall =
12152 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12153 ResultType, VK, RParenLoc);
12154
12155 // (CUDA B.1): Check for invalid calls between targets.
12156 if (getLangOpts().CUDA) {
12157 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
12158 if (CheckCUDATarget(Caller, Method)) {
12159 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
12160 << IdentifyCUDATarget(Method) << Method->getIdentifier()
12161 << IdentifyCUDATarget(Caller);
12162 return ExprError();
12163 }
12164 }
12165 }
12166
12167 // Check for a valid return type.
12168 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12169 TheCall, Method))
12170 return ExprError();
12171
12172 // Convert the object argument (for a non-static member function call).
12173 // We only need to do this if there was actually an overload; otherwise
12174 // it was done at lookup.
12175 if (!Method->isStatic()) {
12176 ExprResult ObjectArg =
12177 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12178 FoundDecl, Method);
12179 if (ObjectArg.isInvalid())
12180 return ExprError();
12181 MemExpr->setBase(ObjectArg.get());
12182 }
12183
12184 // Convert the rest of the arguments
12185 const FunctionProtoType *Proto =
12186 Method->getType()->getAs<FunctionProtoType>();
12187 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12188 RParenLoc))
12189 return ExprError();
12190
12191 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12192
12193 if (CheckFunctionCall(Method, TheCall, Proto))
12194 return ExprError();
12195
12196 // In the case the method to call was not selected by the overloading
12197 // resolution process, we still need to handle the enable_if attribute. Do
12198 // that here, so it will not hide previous -- and more relevant -- errors
12199 if (isa<MemberExpr>(NakedMemExpr)) {
12200 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12201 Diag(MemExprE->getLocStart(),
12202 diag::err_ovl_no_viable_member_function_in_call)
12203 << Method << Method->getSourceRange();
12204 Diag(Method->getLocation(),
12205 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12206 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12207 return ExprError();
12208 }
12209 }
12210
12211 if ((isa<CXXConstructorDecl>(CurContext) ||
12212 isa<CXXDestructorDecl>(CurContext)) &&
12213 TheCall->getMethodDecl()->isPure()) {
12214 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12215
12216 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12217 MemExpr->performsVirtualDispatch(getLangOpts())) {
12218 Diag(MemExpr->getLocStart(),
12219 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12220 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12221 << MD->getParent()->getDeclName();
12222
12223 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12224 if (getLangOpts().AppleKext)
12225 Diag(MemExpr->getLocStart(),
12226 diag::note_pure_qualified_call_kext)
12227 << MD->getParent()->getDeclName()
12228 << MD->getDeclName();
12229 }
12230 }
12231 return MaybeBindToTemporary(TheCall);
12232}
12233
12234/// BuildCallToObjectOfClassType - Build a call to an object of class
12235/// type (C++ [over.call.object]), which can end up invoking an
12236/// overloaded function call operator (@c operator()) or performing a
12237/// user-defined conversion on the object argument.
12238ExprResult
12239Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12240 SourceLocation LParenLoc,
12241 MultiExprArg Args,
12242 SourceLocation RParenLoc) {
12243 if (checkPlaceholderForOverload(*this, Obj))
12244 return ExprError();
12245 ExprResult Object = Obj;
12246
12247 UnbridgedCastsSet UnbridgedCasts;
12248 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12249 return ExprError();
12250
12251 assert(Object.get()->getType()->isRecordType() &&((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12252, __PRETTY_FUNCTION__))
12252 "Requires object type argument")((Object.get()->getType()->isRecordType() && "Requires object type argument"
) ? static_cast<void> (0) : __assert_fail ("Object.get()->getType()->isRecordType() && \"Requires object type argument\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12252, __PRETTY_FUNCTION__))
;
12253 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12254
12255 // C++ [over.call.object]p1:
12256 // If the primary-expression E in the function call syntax
12257 // evaluates to a class object of type "cv T", then the set of
12258 // candidate functions includes at least the function call
12259 // operators of T. The function call operators of T are obtained by
12260 // ordinary lookup of the name operator() in the context of
12261 // (E).operator().
12262 OverloadCandidateSet CandidateSet(LParenLoc,
12263 OverloadCandidateSet::CSK_Operator);
12264 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12265
12266 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12267 diag::err_incomplete_object_call, Object.get()))
12268 return true;
12269
12270 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12271 LookupQualifiedName(R, Record->getDecl());
12272 R.suppressDiagnostics();
12273
12274 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12275 Oper != OperEnd; ++Oper) {
12276 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12277 Object.get()->Classify(Context),
12278 Args, CandidateSet,
12279 /*SuppressUserConversions=*/ false);
12280 }
12281
12282 // C++ [over.call.object]p2:
12283 // In addition, for each (non-explicit in C++0x) conversion function
12284 // declared in T of the form
12285 //
12286 // operator conversion-type-id () cv-qualifier;
12287 //
12288 // where cv-qualifier is the same cv-qualification as, or a
12289 // greater cv-qualification than, cv, and where conversion-type-id
12290 // denotes the type "pointer to function of (P1,...,Pn) returning
12291 // R", or the type "reference to pointer to function of
12292 // (P1,...,Pn) returning R", or the type "reference to function
12293 // of (P1,...,Pn) returning R", a surrogate call function [...]
12294 // is also considered as a candidate function. Similarly,
12295 // surrogate call functions are added to the set of candidate
12296 // functions for each conversion function declared in an
12297 // accessible base class provided the function is not hidden
12298 // within T by another intervening declaration.
12299 const auto &Conversions =
12300 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12301 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12302 NamedDecl *D = *I;
12303 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12304 if (isa<UsingShadowDecl>(D))
12305 D = cast<UsingShadowDecl>(D)->getTargetDecl();
12306
12307 // Skip over templated conversion functions; they aren't
12308 // surrogates.
12309 if (isa<FunctionTemplateDecl>(D))
12310 continue;
12311
12312 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12313 if (!Conv->isExplicit()) {
12314 // Strip the reference type (if any) and then the pointer type (if
12315 // any) to get down to what might be a function type.
12316 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12317 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12318 ConvType = ConvPtrType->getPointeeType();
12319
12320 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12321 {
12322 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12323 Object.get(), Args, CandidateSet);
12324 }
12325 }
12326 }
12327
12328 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12329
12330 // Perform overload resolution.
12331 OverloadCandidateSet::iterator Best;
12332 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12333 Best)) {
12334 case OR_Success:
12335 // Overload resolution succeeded; we'll build the appropriate call
12336 // below.
12337 break;
12338
12339 case OR_No_Viable_Function:
12340 if (CandidateSet.empty())
12341 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12342 << Object.get()->getType() << /*call*/ 1
12343 << Object.get()->getSourceRange();
12344 else
12345 Diag(Object.get()->getLocStart(),
12346 diag::err_ovl_no_viable_object_call)
12347 << Object.get()->getType() << Object.get()->getSourceRange();
12348 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12349 break;
12350
12351 case OR_Ambiguous:
12352 Diag(Object.get()->getLocStart(),
12353 diag::err_ovl_ambiguous_object_call)
12354 << Object.get()->getType() << Object.get()->getSourceRange();
12355 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12356 break;
12357
12358 case OR_Deleted:
12359 Diag(Object.get()->getLocStart(),
12360 diag::err_ovl_deleted_object_call)
12361 << Best->Function->isDeleted()
12362 << Object.get()->getType()
12363 << getDeletedOrUnavailableSuffix(Best->Function)
12364 << Object.get()->getSourceRange();
12365 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12366 break;
12367 }
12368
12369 if (Best == CandidateSet.end())
12370 return true;
12371
12372 UnbridgedCasts.restore();
12373
12374 if (Best->Function == nullptr) {
12375 // Since there is no function declaration, this is one of the
12376 // surrogate candidates. Dig out the conversion function.
12377 CXXConversionDecl *Conv
12378 = cast<CXXConversionDecl>(
12379 Best->Conversions[0].UserDefined.ConversionFunction);
12380
12381 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12382 Best->FoundDecl);
12383 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12384 return ExprError();
12385 assert(Conv == Best->FoundDecl.getDecl() &&((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12386, __PRETTY_FUNCTION__))
12386 "Found Decl & conversion-to-functionptr should be same, right?!")((Conv == Best->FoundDecl.getDecl() && "Found Decl & conversion-to-functionptr should be same, right?!"
) ? static_cast<void> (0) : __assert_fail ("Conv == Best->FoundDecl.getDecl() && \"Found Decl & conversion-to-functionptr should be same, right?!\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12386, __PRETTY_FUNCTION__))
;
12387 // We selected one of the surrogate functions that converts the
12388 // object parameter to a function pointer. Perform the conversion
12389 // on the object argument, then let ActOnCallExpr finish the job.
12390
12391 // Create an implicit member expr to refer to the conversion operator.
12392 // and then call it.
12393 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12394 Conv, HadMultipleCandidates);
12395 if (Call.isInvalid())
12396 return ExprError();
12397 // Record usage of conversion in an implicit cast.
12398 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12399 CK_UserDefinedConversion, Call.get(),
12400 nullptr, VK_RValue);
12401
12402 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12403 }
12404
12405 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12406
12407 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12408 // that calls this method, using Object for the implicit object
12409 // parameter and passing along the remaining arguments.
12410 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12411
12412 // An error diagnostic has already been printed when parsing the declaration.
12413 if (Method->isInvalidDecl())
12414 return ExprError();
12415
12416 const FunctionProtoType *Proto =
12417 Method->getType()->getAs<FunctionProtoType>();
12418
12419 unsigned NumParams = Proto->getNumParams();
12420
12421 DeclarationNameInfo OpLocInfo(
12422 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12423 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12424 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12425 HadMultipleCandidates,
12426 OpLocInfo.getLoc(),
12427 OpLocInfo.getInfo());
12428 if (NewFn.isInvalid())
12429 return true;
12430
12431 // Build the full argument list for the method call (the implicit object
12432 // parameter is placed at the beginning of the list).
12433 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
12434 MethodArgs[0] = Object.get();
12435 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12436
12437 // Once we've built TheCall, all of the expressions are properly
12438 // owned.
12439 QualType ResultTy = Method->getReturnType();
12440 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12441 ResultTy = ResultTy.getNonLValueExprType(Context);
12442
12443 CXXOperatorCallExpr *TheCall = new (Context)
12444 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
12445 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12446 ResultTy, VK, RParenLoc, false);
12447 MethodArgs.reset();
12448
12449 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12450 return true;
12451
12452 // We may have default arguments. If so, we need to allocate more
12453 // slots in the call for them.
12454 if (Args.size() < NumParams)
12455 TheCall->setNumArgs(Context, NumParams + 1);
12456
12457 bool IsError = false;
12458
12459 // Initialize the implicit object parameter.
12460 ExprResult ObjRes =
12461 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12462 Best->FoundDecl, Method);
12463 if (ObjRes.isInvalid())
12464 IsError = true;
12465 else
12466 Object = ObjRes;
12467 TheCall->setArg(0, Object.get());
12468
12469 // Check the argument types.
12470 for (unsigned i = 0; i != NumParams; i++) {
12471 Expr *Arg;
12472 if (i < Args.size()) {
12473 Arg = Args[i];
12474
12475 // Pass the argument.
12476
12477 ExprResult InputInit
12478 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12479 Context,
12480 Method->getParamDecl(i)),
12481 SourceLocation(), Arg);
12482
12483 IsError |= InputInit.isInvalid();
12484 Arg = InputInit.getAs<Expr>();
12485 } else {
12486 ExprResult DefArg
12487 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12488 if (DefArg.isInvalid()) {
12489 IsError = true;
12490 break;
12491 }
12492
12493 Arg = DefArg.getAs<Expr>();
12494 }
12495
12496 TheCall->setArg(i + 1, Arg);
12497 }
12498
12499 // If this is a variadic call, handle args passed through "...".
12500 if (Proto->isVariadic()) {
12501 // Promote the arguments (C99 6.5.2.2p7).
12502 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12503 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12504 nullptr);
12505 IsError |= Arg.isInvalid();
12506 TheCall->setArg(i + 1, Arg.get());
12507 }
12508 }
12509
12510 if (IsError) return true;
12511
12512 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12513
12514 if (CheckFunctionCall(Method, TheCall, Proto))
12515 return true;
12516
12517 return MaybeBindToTemporary(TheCall);
12518}
12519
12520/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12521/// (if one exists), where @c Base is an expression of class type and
12522/// @c Member is the name of the member we're trying to find.
12523ExprResult
12524Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12525 bool *NoArrowOperatorFound) {
12526 assert(Base->getType()->isRecordType() &&((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12527, __PRETTY_FUNCTION__))
12527 "left-hand side must have class type")((Base->getType()->isRecordType() && "left-hand side must have class type"
) ? static_cast<void> (0) : __assert_fail ("Base->getType()->isRecordType() && \"left-hand side must have class type\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12527, __PRETTY_FUNCTION__))
;
12528
12529 if (checkPlaceholderForOverload(*this, Base))
12530 return ExprError();
12531
12532 SourceLocation Loc = Base->getExprLoc();
12533
12534 // C++ [over.ref]p1:
12535 //
12536 // [...] An expression x->m is interpreted as (x.operator->())->m
12537 // for a class object x of type T if T::operator->() exists and if
12538 // the operator is selected as the best match function by the
12539 // overload resolution mechanism (13.3).
12540 DeclarationName OpName =
12541 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12542 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12543 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12544
12545 if (RequireCompleteType(Loc, Base->getType(),
12546 diag::err_typecheck_incomplete_tag, Base))
12547 return ExprError();
12548
12549 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12550 LookupQualifiedName(R, BaseRecord->getDecl());
12551 R.suppressDiagnostics();
12552
12553 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12554 Oper != OperEnd; ++Oper) {
12555 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12556 None, CandidateSet, /*SuppressUserConversions=*/false);
12557 }
12558
12559 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12560
12561 // Perform overload resolution.
12562 OverloadCandidateSet::iterator Best;
12563 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12564 case OR_Success:
12565 // Overload resolution succeeded; we'll build the call below.
12566 break;
12567
12568 case OR_No_Viable_Function:
12569 if (CandidateSet.empty()) {
12570 QualType BaseType = Base->getType();
12571 if (NoArrowOperatorFound) {
12572 // Report this specific error to the caller instead of emitting a
12573 // diagnostic, as requested.
12574 *NoArrowOperatorFound = true;
12575 return ExprError();
12576 }
12577 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12578 << BaseType << Base->getSourceRange();
12579 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12580 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12581 << FixItHint::CreateReplacement(OpLoc, ".");
12582 }
12583 } else
12584 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12585 << "operator->" << Base->getSourceRange();
12586 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12587 return ExprError();
12588
12589 case OR_Ambiguous:
12590 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12591 << "->" << Base->getType() << Base->getSourceRange();
12592 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12593 return ExprError();
12594
12595 case OR_Deleted:
12596 Diag(OpLoc, diag::err_ovl_deleted_oper)
12597 << Best->Function->isDeleted()
12598 << "->"
12599 << getDeletedOrUnavailableSuffix(Best->Function)
12600 << Base->getSourceRange();
12601 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12602 return ExprError();
12603 }
12604
12605 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12606
12607 // Convert the object parameter.
12608 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12609 ExprResult BaseResult =
12610 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
12611 Best->FoundDecl, Method);
12612 if (BaseResult.isInvalid())
12613 return ExprError();
12614 Base = BaseResult.get();
12615
12616 // Build the operator call.
12617 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12618 HadMultipleCandidates, OpLoc);
12619 if (FnExpr.isInvalid())
12620 return ExprError();
12621
12622 QualType ResultTy = Method->getReturnType();
12623 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12624 ResultTy = ResultTy.getNonLValueExprType(Context);
12625 CXXOperatorCallExpr *TheCall =
12626 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
12627 Base, ResultTy, VK, OpLoc, false);
12628
12629 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
12630 return ExprError();
12631
12632 return MaybeBindToTemporary(TheCall);
12633}
12634
12635/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12636/// a literal operator described by the provided lookup results.
12637ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12638 DeclarationNameInfo &SuffixInfo,
12639 ArrayRef<Expr*> Args,
12640 SourceLocation LitEndLoc,
12641 TemplateArgumentListInfo *TemplateArgs) {
12642 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
12643
12644 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12645 OverloadCandidateSet::CSK_Normal);
12646 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12647 /*SuppressUserConversions=*/true);
12648
12649 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12650
12651 // Perform overload resolution. This will usually be trivial, but might need
12652 // to perform substitutions for a literal operator template.
12653 OverloadCandidateSet::iterator Best;
12654 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12655 case OR_Success:
12656 case OR_Deleted:
12657 break;
12658
12659 case OR_No_Viable_Function:
12660 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12661 << R.getLookupName();
12662 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12663 return ExprError();
12664
12665 case OR_Ambiguous:
12666 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12667 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12668 return ExprError();
12669 }
12670
12671 FunctionDecl *FD = Best->Function;
12672 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12673 HadMultipleCandidates,
12674 SuffixInfo.getLoc(),
12675 SuffixInfo.getInfo());
12676 if (Fn.isInvalid())
12677 return true;
12678
12679 // Check the argument types. This should almost always be a no-op, except
12680 // that array-to-pointer decay is applied to string literals.
12681 Expr *ConvArgs[2];
12682 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12683 ExprResult InputInit = PerformCopyInitialization(
12684 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12685 SourceLocation(), Args[ArgIdx]);
12686 if (InputInit.isInvalid())
12687 return true;
12688 ConvArgs[ArgIdx] = InputInit.get();
12689 }
12690
12691 QualType ResultTy = FD->getReturnType();
12692 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12693 ResultTy = ResultTy.getNonLValueExprType(Context);
12694
12695 UserDefinedLiteral *UDL =
12696 new (Context) UserDefinedLiteral(Context, Fn.get(),
12697 llvm::makeArrayRef(ConvArgs, Args.size()),
12698 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12699
12700 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12701 return ExprError();
12702
12703 if (CheckFunctionCall(FD, UDL, nullptr))
12704 return ExprError();
12705
12706 return MaybeBindToTemporary(UDL);
12707}
12708
12709/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12710/// given LookupResult is non-empty, it is assumed to describe a member which
12711/// will be invoked. Otherwise, the function will be found via argument
12712/// dependent lookup.
12713/// CallExpr is set to a valid expression and FRS_Success returned on success,
12714/// otherwise CallExpr is set to ExprError() and some non-success value
12715/// is returned.
12716Sema::ForRangeStatus
12717Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
12718 SourceLocation RangeLoc,
12719 const DeclarationNameInfo &NameInfo,
12720 LookupResult &MemberLookup,
12721 OverloadCandidateSet *CandidateSet,
12722 Expr *Range, ExprResult *CallExpr) {
12723 Scope *S = nullptr;
12724
12725 CandidateSet->clear();
12726 if (!MemberLookup.empty()) {
12727 ExprResult MemberRef =
12728 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12729 /*IsPtr=*/false, CXXScopeSpec(),
12730 /*TemplateKWLoc=*/SourceLocation(),
12731 /*FirstQualifierInScope=*/nullptr,
12732 MemberLookup,
12733 /*TemplateArgs=*/nullptr, S);
12734 if (MemberRef.isInvalid()) {
12735 *CallExpr = ExprError();
12736 return FRS_DiagnosticIssued;
12737 }
12738 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12739 if (CallExpr->isInvalid()) {
12740 *CallExpr = ExprError();
12741 return FRS_DiagnosticIssued;
12742 }
12743 } else {
12744 UnresolvedSet<0> FoundNames;
12745 UnresolvedLookupExpr *Fn =
12746 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12747 NestedNameSpecifierLoc(), NameInfo,
12748 /*NeedsADL=*/true, /*Overloaded=*/false,
12749 FoundNames.begin(), FoundNames.end());
12750
12751 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12752 CandidateSet, CallExpr);
12753 if (CandidateSet->empty() || CandidateSetError) {
12754 *CallExpr = ExprError();
12755 return FRS_NoViableFunction;
12756 }
12757 OverloadCandidateSet::iterator Best;
12758 OverloadingResult OverloadResult =
12759 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12760
12761 if (OverloadResult == OR_No_Viable_Function) {
12762 *CallExpr = ExprError();
12763 return FRS_NoViableFunction;
12764 }
12765 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12766 Loc, nullptr, CandidateSet, &Best,
12767 OverloadResult,
12768 /*AllowTypoCorrection=*/false);
12769 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12770 *CallExpr = ExprError();
12771 return FRS_DiagnosticIssued;
12772 }
12773 }
12774 return FRS_Success;
12775}
12776
12777
12778/// FixOverloadedFunctionReference - E is an expression that refers to
12779/// a C++ overloaded function (possibly with some parentheses and
12780/// perhaps a '&' around it). We have resolved the overloaded function
12781/// to the function declaration Fn, so patch up the expression E to
12782/// refer (possibly indirectly) to Fn. Returns the new expr.
12783Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12784 FunctionDecl *Fn) {
12785 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12786 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12787 Found, Fn);
12788 if (SubExpr == PE->getSubExpr())
12789 return PE;
12790
12791 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12792 }
12793
12794 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12795 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12796 Found, Fn);
12797 assert(Context.hasSameType(ICE->getSubExpr()->getType(),((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12799, __PRETTY_FUNCTION__))
12798 SubExpr->getType()) &&((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12799, __PRETTY_FUNCTION__))
12799 "Implicit cast type cannot be determined from overload")((Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr
->getType()) && "Implicit cast type cannot be determined from overload"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(ICE->getSubExpr()->getType(), SubExpr->getType()) && \"Implicit cast type cannot be determined from overload\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12799, __PRETTY_FUNCTION__))
;
12800 assert(ICE->path_empty() && "fixing up hierarchy conversion?")((ICE->path_empty() && "fixing up hierarchy conversion?"
) ? static_cast<void> (0) : __assert_fail ("ICE->path_empty() && \"fixing up hierarchy conversion?\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12800, __PRETTY_FUNCTION__))
;
12801 if (SubExpr == ICE->getSubExpr())
12802 return ICE;
12803
12804 return ImplicitCastExpr::Create(Context, ICE->getType(),
12805 ICE->getCastKind(),
12806 SubExpr, nullptr,
12807 ICE->getValueKind());
12808 }
12809
12810 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12811 assert(UnOp->getOpcode() == UO_AddrOf &&((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12812, __PRETTY_FUNCTION__))
12812 "Can only take the address of an overloaded function")((UnOp->getOpcode() == UO_AddrOf && "Can only take the address of an overloaded function"
) ? static_cast<void> (0) : __assert_fail ("UnOp->getOpcode() == UO_AddrOf && \"Can only take the address of an overloaded function\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12812, __PRETTY_FUNCTION__))
;
12813 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12814 if (Method->isStatic()) {
12815 // Do nothing: static member functions aren't any different
12816 // from non-member functions.
12817 } else {
12818 // Fix the subexpression, which really has to be an
12819 // UnresolvedLookupExpr holding an overloaded member function
12820 // or template.
12821 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12822 Found, Fn);
12823 if (SubExpr == UnOp->getSubExpr())
12824 return UnOp;
12825
12826 assert(isa<DeclRefExpr>(SubExpr)((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12827, __PRETTY_FUNCTION__))
12827 && "fixed to something other than a decl ref")((isa<DeclRefExpr>(SubExpr) && "fixed to something other than a decl ref"
) ? static_cast<void> (0) : __assert_fail ("isa<DeclRefExpr>(SubExpr) && \"fixed to something other than a decl ref\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12827, __PRETTY_FUNCTION__))
;
12828 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12829, __PRETTY_FUNCTION__))
12829 && "fixed to a member ref with no nested name qualifier")((cast<DeclRefExpr>(SubExpr)->getQualifier() &&
"fixed to a member ref with no nested name qualifier") ? static_cast
<void> (0) : __assert_fail ("cast<DeclRefExpr>(SubExpr)->getQualifier() && \"fixed to a member ref with no nested name qualifier\""
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12829, __PRETTY_FUNCTION__))
;
12830
12831 // We have taken the address of a pointer to member
12832 // function. Perform the computation here so that we get the
12833 // appropriate pointer to member type.
12834 QualType ClassType
12835 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12836 QualType MemPtrType
12837 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12838
12839 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12840 VK_RValue, OK_Ordinary,
12841 UnOp->getOperatorLoc());
12842 }
12843 }
12844 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12845 Found, Fn);
12846 if (SubExpr == UnOp->getSubExpr())
12847 return UnOp;
12848
12849 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12850 Context.getPointerType(SubExpr->getType()),
12851 VK_RValue, OK_Ordinary,
12852 UnOp->getOperatorLoc());
12853 }
12854
12855 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12856 // FIXME: avoid copy.
12857 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12858 if (ULE->hasExplicitTemplateArgs()) {
12859 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12860 TemplateArgs = &TemplateArgsBuffer;
12861 }
12862
12863 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12864 ULE->getQualifierLoc(),
12865 ULE->getTemplateKeywordLoc(),
12866 Fn,
12867 /*enclosing*/ false, // FIXME?
12868 ULE->getNameLoc(),
12869 Fn->getType(),
12870 VK_LValue,
12871 Found.getDecl(),
12872 TemplateArgs);
12873 MarkDeclRefReferenced(DRE);
12874 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12875 return DRE;
12876 }
12877
12878 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12879 // FIXME: avoid copy.
12880 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12881 if (MemExpr->hasExplicitTemplateArgs()) {
12882 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12883 TemplateArgs = &TemplateArgsBuffer;
12884 }
12885
12886 Expr *Base;
12887
12888 // If we're filling in a static method where we used to have an
12889 // implicit member access, rewrite to a simple decl ref.
12890 if (MemExpr->isImplicitAccess()) {
12891 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12892 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12893 MemExpr->getQualifierLoc(),
12894 MemExpr->getTemplateKeywordLoc(),
12895 Fn,
12896 /*enclosing*/ false,
12897 MemExpr->getMemberLoc(),
12898 Fn->getType(),
12899 VK_LValue,
12900 Found.getDecl(),
12901 TemplateArgs);
12902 MarkDeclRefReferenced(DRE);
12903 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12904 return DRE;
12905 } else {
12906 SourceLocation Loc = MemExpr->getMemberLoc();
12907 if (MemExpr->getQualifier())
12908 Loc = MemExpr->getQualifierLoc().getBeginLoc();
12909 CheckCXXThisCapture(Loc);
12910 Base = new (Context) CXXThisExpr(Loc,
12911 MemExpr->getBaseType(),
12912 /*isImplicit=*/true);
12913 }
12914 } else
12915 Base = MemExpr->getBase();
12916
12917 ExprValueKind valueKind;
12918 QualType type;
12919 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12920 valueKind = VK_LValue;
12921 type = Fn->getType();
12922 } else {
12923 valueKind = VK_RValue;
12924 type = Context.BoundMemberTy;
12925 }
12926
12927 MemberExpr *ME = MemberExpr::Create(
12928 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12929 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12930 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12931 OK_Ordinary);
12932 ME->setHadMultipleCandidates(true);
12933 MarkMemberReferenced(ME);
12934 return ME;
12935 }
12936
12937 llvm_unreachable("Invalid reference to overloaded function")::llvm::llvm_unreachable_internal("Invalid reference to overloaded function"
, "/tmp/buildd/llvm-toolchain-snapshot-3.8~svn257205/tools/clang/lib/Sema/SemaOverload.cpp"
, 12937)
;
12938}
12939
12940ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12941 DeclAccessPair Found,
12942 FunctionDecl *Fn) {
12943 return FixOverloadedFunctionReference(E.get(), Found, Fn);
12944}