• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
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/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Template.h"
18 #include "clang/Sema/TemplateDeduction.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CXXInheritance.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include <algorithm>
33 
34 namespace clang {
35 using namespace sema;
36 
37 /// A convenience routine for creating a decayed reference to a
38 /// function.
39 static ExprResult
CreateFunctionRefExpr(Sema & S,FunctionDecl * Fn,bool HadMultipleCandidates,SourceLocation Loc=SourceLocation (),const DeclarationNameLoc & LocInfo=DeclarationNameLoc ())40 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
41                       SourceLocation Loc = SourceLocation(),
42                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
43   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
44                                                  VK_LValue, Loc, LocInfo);
45   if (HadMultipleCandidates)
46     DRE->setHadMultipleCandidates(true);
47   ExprResult E = S.Owned(DRE);
48   E = S.DefaultFunctionArrayConversion(E.take());
49   if (E.isInvalid())
50     return ExprError();
51   return move(E);
52 }
53 
54 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55                                  bool InOverloadResolution,
56                                  StandardConversionSequence &SCS,
57                                  bool CStyle,
58                                  bool AllowObjCWritebackConversion);
59 
60 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61                                                  QualType &ToType,
62                                                  bool InOverloadResolution,
63                                                  StandardConversionSequence &SCS,
64                                                  bool CStyle);
65 static OverloadingResult
66 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67                         UserDefinedConversionSequence& User,
68                         OverloadCandidateSet& Conversions,
69                         bool AllowExplicit);
70 
71 
72 static ImplicitConversionSequence::CompareKind
73 CompareStandardConversionSequences(Sema &S,
74                                    const StandardConversionSequence& SCS1,
75                                    const StandardConversionSequence& SCS2);
76 
77 static ImplicitConversionSequence::CompareKind
78 CompareQualificationConversions(Sema &S,
79                                 const StandardConversionSequence& SCS1,
80                                 const StandardConversionSequence& SCS2);
81 
82 static ImplicitConversionSequence::CompareKind
83 CompareDerivedToBaseConversions(Sema &S,
84                                 const StandardConversionSequence& SCS1,
85                                 const StandardConversionSequence& SCS2);
86 
87 
88 
89 /// GetConversionCategory - Retrieve the implicit conversion
90 /// category corresponding to the given implicit conversion kind.
91 ImplicitConversionCategory
GetConversionCategory(ImplicitConversionKind Kind)92 GetConversionCategory(ImplicitConversionKind Kind) {
93   static const ImplicitConversionCategory
94     Category[(int)ICK_Num_Conversion_Kinds] = {
95     ICC_Identity,
96     ICC_Lvalue_Transformation,
97     ICC_Lvalue_Transformation,
98     ICC_Lvalue_Transformation,
99     ICC_Identity,
100     ICC_Qualification_Adjustment,
101     ICC_Promotion,
102     ICC_Promotion,
103     ICC_Promotion,
104     ICC_Conversion,
105     ICC_Conversion,
106     ICC_Conversion,
107     ICC_Conversion,
108     ICC_Conversion,
109     ICC_Conversion,
110     ICC_Conversion,
111     ICC_Conversion,
112     ICC_Conversion,
113     ICC_Conversion,
114     ICC_Conversion,
115     ICC_Conversion,
116     ICC_Conversion
117   };
118   return Category[(int)Kind];
119 }
120 
121 /// GetConversionRank - Retrieve the implicit conversion rank
122 /// corresponding to the given implicit conversion kind.
GetConversionRank(ImplicitConversionKind Kind)123 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124   static const ImplicitConversionRank
125     Rank[(int)ICK_Num_Conversion_Kinds] = {
126     ICR_Exact_Match,
127     ICR_Exact_Match,
128     ICR_Exact_Match,
129     ICR_Exact_Match,
130     ICR_Exact_Match,
131     ICR_Exact_Match,
132     ICR_Promotion,
133     ICR_Promotion,
134     ICR_Promotion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Conversion,
146     ICR_Complex_Real_Conversion,
147     ICR_Conversion,
148     ICR_Conversion,
149     ICR_Writeback_Conversion
150   };
151   return Rank[(int)Kind];
152 }
153 
154 /// GetImplicitConversionName - Return the name of this kind of
155 /// implicit conversion.
GetImplicitConversionName(ImplicitConversionKind Kind)156 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
157   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158     "No conversion",
159     "Lvalue-to-rvalue",
160     "Array-to-pointer",
161     "Function-to-pointer",
162     "Noreturn adjustment",
163     "Qualification",
164     "Integral promotion",
165     "Floating point promotion",
166     "Complex promotion",
167     "Integral conversion",
168     "Floating conversion",
169     "Complex conversion",
170     "Floating-integral conversion",
171     "Pointer conversion",
172     "Pointer-to-member conversion",
173     "Boolean conversion",
174     "Compatible-types conversion",
175     "Derived-to-base conversion",
176     "Vector conversion",
177     "Vector splat",
178     "Complex-real conversion",
179     "Block Pointer conversion",
180     "Transparent Union Conversion"
181     "Writeback conversion"
182   };
183   return Name[Kind];
184 }
185 
186 /// StandardConversionSequence - Set the standard conversion
187 /// sequence to the identity conversion.
setAsIdentityConversion()188 void StandardConversionSequence::setAsIdentityConversion() {
189   First = ICK_Identity;
190   Second = ICK_Identity;
191   Third = ICK_Identity;
192   DeprecatedStringLiteralToCharPtr = false;
193   QualificationIncludesObjCLifetime = false;
194   ReferenceBinding = false;
195   DirectBinding = false;
196   IsLvalueReference = true;
197   BindsToFunctionLvalue = false;
198   BindsToRvalue = false;
199   BindsImplicitObjectArgumentWithoutRefQualifier = false;
200   ObjCLifetimeConversionBinding = false;
201   CopyConstructor = 0;
202 }
203 
204 /// getRank - Retrieve the rank of this standard conversion sequence
205 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206 /// implicit conversions.
getRank() const207 ImplicitConversionRank StandardConversionSequence::getRank() const {
208   ImplicitConversionRank Rank = ICR_Exact_Match;
209   if  (GetConversionRank(First) > Rank)
210     Rank = GetConversionRank(First);
211   if  (GetConversionRank(Second) > Rank)
212     Rank = GetConversionRank(Second);
213   if  (GetConversionRank(Third) > Rank)
214     Rank = GetConversionRank(Third);
215   return Rank;
216 }
217 
218 /// isPointerConversionToBool - Determines whether this conversion is
219 /// a conversion of a pointer or pointer-to-member to bool. This is
220 /// used as part of the ranking of standard conversion sequences
221 /// (C++ 13.3.3.2p4).
isPointerConversionToBool() const222 bool StandardConversionSequence::isPointerConversionToBool() const {
223   // Note that FromType has not necessarily been transformed by the
224   // array-to-pointer or function-to-pointer implicit conversions, so
225   // check for their presence as well as checking whether FromType is
226   // a pointer.
227   if (getToType(1)->isBooleanType() &&
228       (getFromType()->isPointerType() ||
229        getFromType()->isObjCObjectPointerType() ||
230        getFromType()->isBlockPointerType() ||
231        getFromType()->isNullPtrType() ||
232        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233     return true;
234 
235   return false;
236 }
237 
238 /// isPointerConversionToVoidPointer - Determines whether this
239 /// conversion is a conversion of a pointer to a void pointer. This is
240 /// used as part of the ranking of standard conversion sequences (C++
241 /// 13.3.3.2p4).
242 bool
243 StandardConversionSequence::
isPointerConversionToVoidPointer(ASTContext & Context) const244 isPointerConversionToVoidPointer(ASTContext& Context) const {
245   QualType FromType = getFromType();
246   QualType ToType = getToType(1);
247 
248   // Note that FromType has not necessarily been transformed by the
249   // array-to-pointer implicit conversion, so check for its presence
250   // and redo the conversion to get a pointer.
251   if (First == ICK_Array_To_Pointer)
252     FromType = Context.getArrayDecayedType(FromType);
253 
254   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
255     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
256       return ToPtrType->getPointeeType()->isVoidType();
257 
258   return false;
259 }
260 
261 /// Skip any implicit casts which could be either part of a narrowing conversion
262 /// or after one in an implicit conversion.
IgnoreNarrowingConversion(const Expr * Converted)263 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
264   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
265     switch (ICE->getCastKind()) {
266     case CK_NoOp:
267     case CK_IntegralCast:
268     case CK_IntegralToBoolean:
269     case CK_IntegralToFloating:
270     case CK_FloatingToIntegral:
271     case CK_FloatingToBoolean:
272     case CK_FloatingCast:
273       Converted = ICE->getSubExpr();
274       continue;
275 
276     default:
277       return Converted;
278     }
279   }
280 
281   return Converted;
282 }
283 
284 /// Check if this standard conversion sequence represents a narrowing
285 /// conversion, according to C++11 [dcl.init.list]p7.
286 ///
287 /// \param Ctx  The AST context.
288 /// \param Converted  The result of applying this standard conversion sequence.
289 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
290 ///        value of the expression prior to the narrowing conversion.
291 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
292 ///        type of the expression prior to the narrowing conversion.
293 NarrowingKind
getNarrowingKind(ASTContext & Ctx,const Expr * Converted,APValue & ConstantValue,QualType & ConstantType) const294 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
295                                              const Expr *Converted,
296                                              APValue &ConstantValue,
297                                              QualType &ConstantType) const {
298   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
299 
300   // C++11 [dcl.init.list]p7:
301   //   A narrowing conversion is an implicit conversion ...
302   QualType FromType = getToType(0);
303   QualType ToType = getToType(1);
304   switch (Second) {
305   // -- from a floating-point type to an integer type, or
306   //
307   // -- from an integer type or unscoped enumeration type to a floating-point
308   //    type, except where the source is a constant expression and the actual
309   //    value after conversion will fit into the target type and will produce
310   //    the original value when converted back to the original type, or
311   case ICK_Floating_Integral:
312     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
313       return NK_Type_Narrowing;
314     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
315       llvm::APSInt IntConstantValue;
316       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
317       if (Initializer &&
318           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
319         // Convert the integer to the floating type.
320         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
321         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
322                                 llvm::APFloat::rmNearestTiesToEven);
323         // And back.
324         llvm::APSInt ConvertedValue = IntConstantValue;
325         bool ignored;
326         Result.convertToInteger(ConvertedValue,
327                                 llvm::APFloat::rmTowardZero, &ignored);
328         // If the resulting value is different, this was a narrowing conversion.
329         if (IntConstantValue != ConvertedValue) {
330           ConstantValue = APValue(IntConstantValue);
331           ConstantType = Initializer->getType();
332           return NK_Constant_Narrowing;
333         }
334       } else {
335         // Variables are always narrowings.
336         return NK_Variable_Narrowing;
337       }
338     }
339     return NK_Not_Narrowing;
340 
341   // -- from long double to double or float, or from double to float, except
342   //    where the source is a constant expression and the actual value after
343   //    conversion is within the range of values that can be represented (even
344   //    if it cannot be represented exactly), or
345   case ICK_Floating_Conversion:
346     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
347         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
348       // FromType is larger than ToType.
349       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
350       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
351         // Constant!
352         assert(ConstantValue.isFloat());
353         llvm::APFloat FloatVal = ConstantValue.getFloat();
354         // Convert the source value into the target type.
355         bool ignored;
356         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
357           Ctx.getFloatTypeSemantics(ToType),
358           llvm::APFloat::rmNearestTiesToEven, &ignored);
359         // If there was no overflow, the source value is within the range of
360         // values that can be represented.
361         if (ConvertStatus & llvm::APFloat::opOverflow) {
362           ConstantType = Initializer->getType();
363           return NK_Constant_Narrowing;
364         }
365       } else {
366         return NK_Variable_Narrowing;
367       }
368     }
369     return NK_Not_Narrowing;
370 
371   // -- from an integer type or unscoped enumeration type to an integer type
372   //    that cannot represent all the values of the original type, except where
373   //    the source is a constant expression and the actual value after
374   //    conversion will fit into the target type and will produce the original
375   //    value when converted back to the original type.
376   case ICK_Boolean_Conversion:  // Bools are integers too.
377     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
378       // Boolean conversions can be from pointers and pointers to members
379       // [conv.bool], and those aren't considered narrowing conversions.
380       return NK_Not_Narrowing;
381     }  // Otherwise, fall through to the integral case.
382   case ICK_Integral_Conversion: {
383     assert(FromType->isIntegralOrUnscopedEnumerationType());
384     assert(ToType->isIntegralOrUnscopedEnumerationType());
385     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
386     const unsigned FromWidth = Ctx.getIntWidth(FromType);
387     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
388     const unsigned ToWidth = Ctx.getIntWidth(ToType);
389 
390     if (FromWidth > ToWidth ||
391         (FromWidth == ToWidth && FromSigned != ToSigned)) {
392       // Not all values of FromType can be represented in ToType.
393       llvm::APSInt InitializerValue;
394       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
395       if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
396         ConstantValue = APValue(InitializerValue);
397 
398         // Add a bit to the InitializerValue so we don't have to worry about
399         // signed vs. unsigned comparisons.
400         InitializerValue = InitializerValue.extend(
401           InitializerValue.getBitWidth() + 1);
402         // Convert the initializer to and from the target width and signed-ness.
403         llvm::APSInt ConvertedValue = InitializerValue;
404         ConvertedValue = ConvertedValue.trunc(ToWidth);
405         ConvertedValue.setIsSigned(ToSigned);
406         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
407         ConvertedValue.setIsSigned(InitializerValue.isSigned());
408         // If the result is different, this was a narrowing conversion.
409         if (ConvertedValue != InitializerValue) {
410           ConstantType = Initializer->getType();
411           return NK_Constant_Narrowing;
412         }
413       } else {
414         // Variables are always narrowings.
415         return NK_Variable_Narrowing;
416       }
417     }
418     return NK_Not_Narrowing;
419   }
420 
421   default:
422     // Other kinds of conversions are not narrowings.
423     return NK_Not_Narrowing;
424   }
425 }
426 
427 /// DebugPrint - Print this standard conversion sequence to standard
428 /// error. Useful for debugging overloading issues.
DebugPrint() const429 void StandardConversionSequence::DebugPrint() const {
430   raw_ostream &OS = llvm::errs();
431   bool PrintedSomething = false;
432   if (First != ICK_Identity) {
433     OS << GetImplicitConversionName(First);
434     PrintedSomething = true;
435   }
436 
437   if (Second != ICK_Identity) {
438     if (PrintedSomething) {
439       OS << " -> ";
440     }
441     OS << GetImplicitConversionName(Second);
442 
443     if (CopyConstructor) {
444       OS << " (by copy constructor)";
445     } else if (DirectBinding) {
446       OS << " (direct reference binding)";
447     } else if (ReferenceBinding) {
448       OS << " (reference binding)";
449     }
450     PrintedSomething = true;
451   }
452 
453   if (Third != ICK_Identity) {
454     if (PrintedSomething) {
455       OS << " -> ";
456     }
457     OS << GetImplicitConversionName(Third);
458     PrintedSomething = true;
459   }
460 
461   if (!PrintedSomething) {
462     OS << "No conversions required";
463   }
464 }
465 
466 /// DebugPrint - Print this user-defined conversion sequence to standard
467 /// error. Useful for debugging overloading issues.
DebugPrint() const468 void UserDefinedConversionSequence::DebugPrint() const {
469   raw_ostream &OS = llvm::errs();
470   if (Before.First || Before.Second || Before.Third) {
471     Before.DebugPrint();
472     OS << " -> ";
473   }
474   if (ConversionFunction)
475     OS << '\'' << *ConversionFunction << '\'';
476   else
477     OS << "aggregate initialization";
478   if (After.First || After.Second || After.Third) {
479     OS << " -> ";
480     After.DebugPrint();
481   }
482 }
483 
484 /// DebugPrint - Print this implicit conversion sequence to standard
485 /// error. Useful for debugging overloading issues.
DebugPrint() const486 void ImplicitConversionSequence::DebugPrint() const {
487   raw_ostream &OS = llvm::errs();
488   switch (ConversionKind) {
489   case StandardConversion:
490     OS << "Standard conversion: ";
491     Standard.DebugPrint();
492     break;
493   case UserDefinedConversion:
494     OS << "User-defined conversion: ";
495     UserDefined.DebugPrint();
496     break;
497   case EllipsisConversion:
498     OS << "Ellipsis conversion";
499     break;
500   case AmbiguousConversion:
501     OS << "Ambiguous conversion";
502     break;
503   case BadConversion:
504     OS << "Bad conversion";
505     break;
506   }
507 
508   OS << "\n";
509 }
510 
construct()511 void AmbiguousConversionSequence::construct() {
512   new (&conversions()) ConversionSet();
513 }
514 
destruct()515 void AmbiguousConversionSequence::destruct() {
516   conversions().~ConversionSet();
517 }
518 
519 void
copyFrom(const AmbiguousConversionSequence & O)520 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
521   FromTypePtr = O.FromTypePtr;
522   ToTypePtr = O.ToTypePtr;
523   new (&conversions()) ConversionSet(O.conversions());
524 }
525 
526 namespace {
527   // Structure used by OverloadCandidate::DeductionFailureInfo to store
528   // template parameter and template argument information.
529   struct DFIParamWithArguments {
530     TemplateParameter Param;
531     TemplateArgument FirstArg;
532     TemplateArgument SecondArg;
533   };
534 }
535 
536 /// \brief Convert from Sema's representation of template deduction information
537 /// to the form used in overload-candidate information.
538 OverloadCandidate::DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext & Context,Sema::TemplateDeductionResult TDK,TemplateDeductionInfo & Info)539 static MakeDeductionFailureInfo(ASTContext &Context,
540                                 Sema::TemplateDeductionResult TDK,
541                                 TemplateDeductionInfo &Info) {
542   OverloadCandidate::DeductionFailureInfo Result;
543   Result.Result = static_cast<unsigned>(TDK);
544   Result.Data = 0;
545   switch (TDK) {
546   case Sema::TDK_Success:
547   case Sema::TDK_InstantiationDepth:
548   case Sema::TDK_TooManyArguments:
549   case Sema::TDK_TooFewArguments:
550     break;
551 
552   case Sema::TDK_Incomplete:
553   case Sema::TDK_InvalidExplicitArguments:
554     Result.Data = Info.Param.getOpaqueValue();
555     break;
556 
557   case Sema::TDK_Inconsistent:
558   case Sema::TDK_Underqualified: {
559     // FIXME: Should allocate from normal heap so that we can free this later.
560     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
561     Saved->Param = Info.Param;
562     Saved->FirstArg = Info.FirstArg;
563     Saved->SecondArg = Info.SecondArg;
564     Result.Data = Saved;
565     break;
566   }
567 
568   case Sema::TDK_SubstitutionFailure:
569     Result.Data = Info.take();
570     break;
571 
572   case Sema::TDK_NonDeducedMismatch:
573   case Sema::TDK_FailedOverloadResolution:
574     break;
575   }
576 
577   return Result;
578 }
579 
Destroy()580 void OverloadCandidate::DeductionFailureInfo::Destroy() {
581   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
582   case Sema::TDK_Success:
583   case Sema::TDK_InstantiationDepth:
584   case Sema::TDK_Incomplete:
585   case Sema::TDK_TooManyArguments:
586   case Sema::TDK_TooFewArguments:
587   case Sema::TDK_InvalidExplicitArguments:
588     break;
589 
590   case Sema::TDK_Inconsistent:
591   case Sema::TDK_Underqualified:
592     // FIXME: Destroy the data?
593     Data = 0;
594     break;
595 
596   case Sema::TDK_SubstitutionFailure:
597     // FIXME: Destroy the template arugment list?
598     Data = 0;
599     break;
600 
601   // Unhandled
602   case Sema::TDK_NonDeducedMismatch:
603   case Sema::TDK_FailedOverloadResolution:
604     break;
605   }
606 }
607 
608 TemplateParameter
getTemplateParameter()609 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
610   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
611   case Sema::TDK_Success:
612   case Sema::TDK_InstantiationDepth:
613   case Sema::TDK_TooManyArguments:
614   case Sema::TDK_TooFewArguments:
615   case Sema::TDK_SubstitutionFailure:
616     return TemplateParameter();
617 
618   case Sema::TDK_Incomplete:
619   case Sema::TDK_InvalidExplicitArguments:
620     return TemplateParameter::getFromOpaqueValue(Data);
621 
622   case Sema::TDK_Inconsistent:
623   case Sema::TDK_Underqualified:
624     return static_cast<DFIParamWithArguments*>(Data)->Param;
625 
626   // Unhandled
627   case Sema::TDK_NonDeducedMismatch:
628   case Sema::TDK_FailedOverloadResolution:
629     break;
630   }
631 
632   return TemplateParameter();
633 }
634 
635 TemplateArgumentList *
getTemplateArgumentList()636 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
637   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
638     case Sema::TDK_Success:
639     case Sema::TDK_InstantiationDepth:
640     case Sema::TDK_TooManyArguments:
641     case Sema::TDK_TooFewArguments:
642     case Sema::TDK_Incomplete:
643     case Sema::TDK_InvalidExplicitArguments:
644     case Sema::TDK_Inconsistent:
645     case Sema::TDK_Underqualified:
646       return 0;
647 
648     case Sema::TDK_SubstitutionFailure:
649       return static_cast<TemplateArgumentList*>(Data);
650 
651     // Unhandled
652     case Sema::TDK_NonDeducedMismatch:
653     case Sema::TDK_FailedOverloadResolution:
654       break;
655   }
656 
657   return 0;
658 }
659 
getFirstArg()660 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
661   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
662   case Sema::TDK_Success:
663   case Sema::TDK_InstantiationDepth:
664   case Sema::TDK_Incomplete:
665   case Sema::TDK_TooManyArguments:
666   case Sema::TDK_TooFewArguments:
667   case Sema::TDK_InvalidExplicitArguments:
668   case Sema::TDK_SubstitutionFailure:
669     return 0;
670 
671   case Sema::TDK_Inconsistent:
672   case Sema::TDK_Underqualified:
673     return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
674 
675   // Unhandled
676   case Sema::TDK_NonDeducedMismatch:
677   case Sema::TDK_FailedOverloadResolution:
678     break;
679   }
680 
681   return 0;
682 }
683 
684 const TemplateArgument *
getSecondArg()685 OverloadCandidate::DeductionFailureInfo::getSecondArg() {
686   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
687   case Sema::TDK_Success:
688   case Sema::TDK_InstantiationDepth:
689   case Sema::TDK_Incomplete:
690   case Sema::TDK_TooManyArguments:
691   case Sema::TDK_TooFewArguments:
692   case Sema::TDK_InvalidExplicitArguments:
693   case Sema::TDK_SubstitutionFailure:
694     return 0;
695 
696   case Sema::TDK_Inconsistent:
697   case Sema::TDK_Underqualified:
698     return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
699 
700   // Unhandled
701   case Sema::TDK_NonDeducedMismatch:
702   case Sema::TDK_FailedOverloadResolution:
703     break;
704   }
705 
706   return 0;
707 }
708 
clear()709 void OverloadCandidateSet::clear() {
710   for (iterator i = begin(), e = end(); i != e; ++i)
711     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
712       i->Conversions[ii].~ImplicitConversionSequence();
713   NumInlineSequences = 0;
714   Candidates.clear();
715   Functions.clear();
716 }
717 
718 namespace {
719   class UnbridgedCastsSet {
720     struct Entry {
721       Expr **Addr;
722       Expr *Saved;
723     };
724     SmallVector<Entry, 2> Entries;
725 
726   public:
save(Sema & S,Expr * & E)727     void save(Sema &S, Expr *&E) {
728       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
729       Entry entry = { &E, E };
730       Entries.push_back(entry);
731       E = S.stripARCUnbridgedCast(E);
732     }
733 
restore()734     void restore() {
735       for (SmallVectorImpl<Entry>::iterator
736              i = Entries.begin(), e = Entries.end(); i != e; ++i)
737         *i->Addr = i->Saved;
738     }
739   };
740 }
741 
742 /// checkPlaceholderForOverload - Do any interesting placeholder-like
743 /// preprocessing on the given expression.
744 ///
745 /// \param unbridgedCasts a collection to which to add unbridged casts;
746 ///   without this, they will be immediately diagnosed as errors
747 ///
748 /// Return true on unrecoverable error.
checkPlaceholderForOverload(Sema & S,Expr * & E,UnbridgedCastsSet * unbridgedCasts=0)749 static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
750                                         UnbridgedCastsSet *unbridgedCasts = 0) {
751   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
752     // We can't handle overloaded expressions here because overload
753     // resolution might reasonably tweak them.
754     if (placeholder->getKind() == BuiltinType::Overload) return false;
755 
756     // If the context potentially accepts unbridged ARC casts, strip
757     // the unbridged cast and add it to the collection for later restoration.
758     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
759         unbridgedCasts) {
760       unbridgedCasts->save(S, E);
761       return false;
762     }
763 
764     // Go ahead and check everything else.
765     ExprResult result = S.CheckPlaceholderExpr(E);
766     if (result.isInvalid())
767       return true;
768 
769     E = result.take();
770     return false;
771   }
772 
773   // Nothing to do.
774   return false;
775 }
776 
777 /// checkArgPlaceholdersForOverload - Check a set of call operands for
778 /// placeholders.
checkArgPlaceholdersForOverload(Sema & S,Expr ** args,unsigned numArgs,UnbridgedCastsSet & unbridged)779 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
780                                             unsigned numArgs,
781                                             UnbridgedCastsSet &unbridged) {
782   for (unsigned i = 0; i != numArgs; ++i)
783     if (checkPlaceholderForOverload(S, args[i], &unbridged))
784       return true;
785 
786   return false;
787 }
788 
789 // IsOverload - Determine whether the given New declaration is an
790 // overload of the declarations in Old. This routine returns false if
791 // New and Old cannot be overloaded, e.g., if New has the same
792 // signature as some function in Old (C++ 1.3.10) or if the Old
793 // declarations aren't functions (or function templates) at all. When
794 // it does return false, MatchedDecl will point to the decl that New
795 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
796 // top of the underlying declaration.
797 //
798 // Example: Given the following input:
799 //
800 //   void f(int, float); // #1
801 //   void f(int, int); // #2
802 //   int f(int, int); // #3
803 //
804 // When we process #1, there is no previous declaration of "f",
805 // so IsOverload will not be used.
806 //
807 // When we process #2, Old contains only the FunctionDecl for #1.  By
808 // comparing the parameter types, we see that #1 and #2 are overloaded
809 // (since they have different signatures), so this routine returns
810 // false; MatchedDecl is unchanged.
811 //
812 // When we process #3, Old is an overload set containing #1 and #2. We
813 // compare the signatures of #3 to #1 (they're overloaded, so we do
814 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
815 // identical (return types of functions are not part of the
816 // signature), IsOverload returns false and MatchedDecl will be set to
817 // point to the FunctionDecl for #2.
818 //
819 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
820 // into a class by a using declaration.  The rules for whether to hide
821 // shadow declarations ignore some properties which otherwise figure
822 // into a function template's signature.
823 Sema::OverloadKind
CheckOverload(Scope * S,FunctionDecl * New,const LookupResult & Old,NamedDecl * & Match,bool NewIsUsingDecl)824 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
825                     NamedDecl *&Match, bool NewIsUsingDecl) {
826   for (LookupResult::iterator I = Old.begin(), E = Old.end();
827          I != E; ++I) {
828     NamedDecl *OldD = *I;
829 
830     bool OldIsUsingDecl = false;
831     if (isa<UsingShadowDecl>(OldD)) {
832       OldIsUsingDecl = true;
833 
834       // We can always introduce two using declarations into the same
835       // context, even if they have identical signatures.
836       if (NewIsUsingDecl) continue;
837 
838       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
839     }
840 
841     // If either declaration was introduced by a using declaration,
842     // we'll need to use slightly different rules for matching.
843     // Essentially, these rules are the normal rules, except that
844     // function templates hide function templates with different
845     // return types or template parameter lists.
846     bool UseMemberUsingDeclRules =
847       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
848 
849     if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
850       if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
851         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
852           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
853           continue;
854         }
855 
856         Match = *I;
857         return Ovl_Match;
858       }
859     } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
860       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
861         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
862           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
863           continue;
864         }
865 
866         Match = *I;
867         return Ovl_Match;
868       }
869     } else if (isa<UsingDecl>(OldD)) {
870       // We can overload with these, which can show up when doing
871       // redeclaration checks for UsingDecls.
872       assert(Old.getLookupKind() == LookupUsingDeclName);
873     } else if (isa<TagDecl>(OldD)) {
874       // We can always overload with tags by hiding them.
875     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
876       // Optimistically assume that an unresolved using decl will
877       // overload; if it doesn't, we'll have to diagnose during
878       // template instantiation.
879     } else {
880       // (C++ 13p1):
881       //   Only function declarations can be overloaded; object and type
882       //   declarations cannot be overloaded.
883       Match = *I;
884       return Ovl_NonFunction;
885     }
886   }
887 
888   return Ovl_Overload;
889 }
890 
IsOverload(FunctionDecl * New,FunctionDecl * Old,bool UseUsingDeclRules)891 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
892                       bool UseUsingDeclRules) {
893   // If both of the functions are extern "C", then they are not
894   // overloads.
895   if (Old->isExternC() && New->isExternC())
896     return false;
897 
898   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
899   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
900 
901   // C++ [temp.fct]p2:
902   //   A function template can be overloaded with other function templates
903   //   and with normal (non-template) functions.
904   if ((OldTemplate == 0) != (NewTemplate == 0))
905     return true;
906 
907   // Is the function New an overload of the function Old?
908   QualType OldQType = Context.getCanonicalType(Old->getType());
909   QualType NewQType = Context.getCanonicalType(New->getType());
910 
911   // Compare the signatures (C++ 1.3.10) of the two functions to
912   // determine whether they are overloads. If we find any mismatch
913   // in the signature, they are overloads.
914 
915   // If either of these functions is a K&R-style function (no
916   // prototype), then we consider them to have matching signatures.
917   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
918       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
919     return false;
920 
921   const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
922   const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
923 
924   // The signature of a function includes the types of its
925   // parameters (C++ 1.3.10), which includes the presence or absence
926   // of the ellipsis; see C++ DR 357).
927   if (OldQType != NewQType &&
928       (OldType->getNumArgs() != NewType->getNumArgs() ||
929        OldType->isVariadic() != NewType->isVariadic() ||
930        !FunctionArgTypesAreEqual(OldType, NewType)))
931     return true;
932 
933   // C++ [temp.over.link]p4:
934   //   The signature of a function template consists of its function
935   //   signature, its return type and its template parameter list. The names
936   //   of the template parameters are significant only for establishing the
937   //   relationship between the template parameters and the rest of the
938   //   signature.
939   //
940   // We check the return type and template parameter lists for function
941   // templates first; the remaining checks follow.
942   //
943   // However, we don't consider either of these when deciding whether
944   // a member introduced by a shadow declaration is hidden.
945   if (!UseUsingDeclRules && NewTemplate &&
946       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
947                                        OldTemplate->getTemplateParameters(),
948                                        false, TPL_TemplateMatch) ||
949        OldType->getResultType() != NewType->getResultType()))
950     return true;
951 
952   // If the function is a class member, its signature includes the
953   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
954   //
955   // As part of this, also check whether one of the member functions
956   // is static, in which case they are not overloads (C++
957   // 13.1p2). While not part of the definition of the signature,
958   // this check is important to determine whether these functions
959   // can be overloaded.
960   CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
961   CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
962   if (OldMethod && NewMethod &&
963       !OldMethod->isStatic() && !NewMethod->isStatic() &&
964       (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
965        OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
966     if (!UseUsingDeclRules &&
967         OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
968         (OldMethod->getRefQualifier() == RQ_None ||
969          NewMethod->getRefQualifier() == RQ_None)) {
970       // C++0x [over.load]p2:
971       //   - Member function declarations with the same name and the same
972       //     parameter-type-list as well as member function template
973       //     declarations with the same name, the same parameter-type-list, and
974       //     the same template parameter lists cannot be overloaded if any of
975       //     them, but not all, have a ref-qualifier (8.3.5).
976       Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
977         << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
978       Diag(OldMethod->getLocation(), diag::note_previous_declaration);
979     }
980 
981     return true;
982   }
983 
984   // The signatures match; this is not an overload.
985   return false;
986 }
987 
988 /// \brief Checks availability of the function depending on the current
989 /// function context. Inside an unavailable function, unavailability is ignored.
990 ///
991 /// \returns true if \arg FD is unavailable and current context is inside
992 /// an available function, false otherwise.
isFunctionConsideredUnavailable(FunctionDecl * FD)993 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
994   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
995 }
996 
997 /// \brief Tries a user-defined conversion from From to ToType.
998 ///
999 /// Produces an implicit conversion sequence for when a standard conversion
1000 /// is not an option. See TryImplicitConversion for more information.
1001 static ImplicitConversionSequence
TryUserDefinedConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1002 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1003                          bool SuppressUserConversions,
1004                          bool AllowExplicit,
1005                          bool InOverloadResolution,
1006                          bool CStyle,
1007                          bool AllowObjCWritebackConversion) {
1008   ImplicitConversionSequence ICS;
1009 
1010   if (SuppressUserConversions) {
1011     // We're not in the case above, so there is no conversion that
1012     // we can perform.
1013     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1014     return ICS;
1015   }
1016 
1017   // Attempt user-defined conversion.
1018   OverloadCandidateSet Conversions(From->getExprLoc());
1019   OverloadingResult UserDefResult
1020     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1021                               AllowExplicit);
1022 
1023   if (UserDefResult == OR_Success) {
1024     ICS.setUserDefined();
1025     // C++ [over.ics.user]p4:
1026     //   A conversion of an expression of class type to the same class
1027     //   type is given Exact Match rank, and a conversion of an
1028     //   expression of class type to a base class of that type is
1029     //   given Conversion rank, in spite of the fact that a copy
1030     //   constructor (i.e., a user-defined conversion function) is
1031     //   called for those cases.
1032     if (CXXConstructorDecl *Constructor
1033           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1034       QualType FromCanon
1035         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1036       QualType ToCanon
1037         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1038       if (Constructor->isCopyConstructor() &&
1039           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1040         // Turn this into a "standard" conversion sequence, so that it
1041         // gets ranked with standard conversion sequences.
1042         ICS.setStandard();
1043         ICS.Standard.setAsIdentityConversion();
1044         ICS.Standard.setFromType(From->getType());
1045         ICS.Standard.setAllToTypes(ToType);
1046         ICS.Standard.CopyConstructor = Constructor;
1047         if (ToCanon != FromCanon)
1048           ICS.Standard.Second = ICK_Derived_To_Base;
1049       }
1050     }
1051 
1052     // C++ [over.best.ics]p4:
1053     //   However, when considering the argument of a user-defined
1054     //   conversion function that is a candidate by 13.3.1.3 when
1055     //   invoked for the copying of the temporary in the second step
1056     //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1057     //   13.3.1.6 in all cases, only standard conversion sequences and
1058     //   ellipsis conversion sequences are allowed.
1059     if (SuppressUserConversions && ICS.isUserDefined()) {
1060       ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1061     }
1062   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1063     ICS.setAmbiguous();
1064     ICS.Ambiguous.setFromType(From->getType());
1065     ICS.Ambiguous.setToType(ToType);
1066     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1067          Cand != Conversions.end(); ++Cand)
1068       if (Cand->Viable)
1069         ICS.Ambiguous.addConversion(Cand->Function);
1070   } else {
1071     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1072   }
1073 
1074   return ICS;
1075 }
1076 
1077 /// TryImplicitConversion - Attempt to perform an implicit conversion
1078 /// from the given expression (Expr) to the given type (ToType). This
1079 /// function returns an implicit conversion sequence that can be used
1080 /// to perform the initialization. Given
1081 ///
1082 ///   void f(float f);
1083 ///   void g(int i) { f(i); }
1084 ///
1085 /// this routine would produce an implicit conversion sequence to
1086 /// describe the initialization of f from i, which will be a standard
1087 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1088 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1089 //
1090 /// Note that this routine only determines how the conversion can be
1091 /// performed; it does not actually perform the conversion. As such,
1092 /// it will not produce any diagnostics if no conversion is available,
1093 /// but will instead return an implicit conversion sequence of kind
1094 /// "BadConversion".
1095 ///
1096 /// If @p SuppressUserConversions, then user-defined conversions are
1097 /// not permitted.
1098 /// If @p AllowExplicit, then explicit user-defined conversions are
1099 /// permitted.
1100 ///
1101 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1102 /// writeback conversion, which allows __autoreleasing id* parameters to
1103 /// be initialized with __strong id* or __weak id* arguments.
1104 static ImplicitConversionSequence
TryImplicitConversion(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1105 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1106                       bool SuppressUserConversions,
1107                       bool AllowExplicit,
1108                       bool InOverloadResolution,
1109                       bool CStyle,
1110                       bool AllowObjCWritebackConversion) {
1111   ImplicitConversionSequence ICS;
1112   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1113                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1114     ICS.setStandard();
1115     return ICS;
1116   }
1117 
1118   if (!S.getLangOpts().CPlusPlus) {
1119     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1120     return ICS;
1121   }
1122 
1123   // C++ [over.ics.user]p4:
1124   //   A conversion of an expression of class type to the same class
1125   //   type is given Exact Match rank, and a conversion of an
1126   //   expression of class type to a base class of that type is
1127   //   given Conversion rank, in spite of the fact that a copy/move
1128   //   constructor (i.e., a user-defined conversion function) is
1129   //   called for those cases.
1130   QualType FromType = From->getType();
1131   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1132       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1133        S.IsDerivedFrom(FromType, ToType))) {
1134     ICS.setStandard();
1135     ICS.Standard.setAsIdentityConversion();
1136     ICS.Standard.setFromType(FromType);
1137     ICS.Standard.setAllToTypes(ToType);
1138 
1139     // We don't actually check at this point whether there is a valid
1140     // copy/move constructor, since overloading just assumes that it
1141     // exists. When we actually perform initialization, we'll find the
1142     // appropriate constructor to copy the returned object, if needed.
1143     ICS.Standard.CopyConstructor = 0;
1144 
1145     // Determine whether this is considered a derived-to-base conversion.
1146     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1147       ICS.Standard.Second = ICK_Derived_To_Base;
1148 
1149     return ICS;
1150   }
1151 
1152   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1153                                   AllowExplicit, InOverloadResolution, CStyle,
1154                                   AllowObjCWritebackConversion);
1155 }
1156 
1157 ImplicitConversionSequence
TryImplicitConversion(Expr * From,QualType ToType,bool SuppressUserConversions,bool AllowExplicit,bool InOverloadResolution,bool CStyle,bool AllowObjCWritebackConversion)1158 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1159                             bool SuppressUserConversions,
1160                             bool AllowExplicit,
1161                             bool InOverloadResolution,
1162                             bool CStyle,
1163                             bool AllowObjCWritebackConversion) {
1164   return clang::TryImplicitConversion(*this, From, ToType,
1165                                       SuppressUserConversions, AllowExplicit,
1166                                       InOverloadResolution, CStyle,
1167                                       AllowObjCWritebackConversion);
1168 }
1169 
1170 /// PerformImplicitConversion - Perform an implicit conversion of the
1171 /// expression From to the type ToType. Returns the
1172 /// converted expression. Flavor is the kind of conversion we're
1173 /// performing, used in the error message. If @p AllowExplicit,
1174 /// explicit user-defined conversions are permitted.
1175 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit)1176 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1177                                 AssignmentAction Action, bool AllowExplicit) {
1178   ImplicitConversionSequence ICS;
1179   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1180 }
1181 
1182 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,AssignmentAction Action,bool AllowExplicit,ImplicitConversionSequence & ICS)1183 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1184                                 AssignmentAction Action, bool AllowExplicit,
1185                                 ImplicitConversionSequence& ICS) {
1186   if (checkPlaceholderForOverload(*this, From))
1187     return ExprError();
1188 
1189   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1190   bool AllowObjCWritebackConversion
1191     = getLangOpts().ObjCAutoRefCount &&
1192       (Action == AA_Passing || Action == AA_Sending);
1193 
1194   ICS = clang::TryImplicitConversion(*this, From, ToType,
1195                                      /*SuppressUserConversions=*/false,
1196                                      AllowExplicit,
1197                                      /*InOverloadResolution=*/false,
1198                                      /*CStyle=*/false,
1199                                      AllowObjCWritebackConversion);
1200   return PerformImplicitConversion(From, ToType, ICS, Action);
1201 }
1202 
1203 /// \brief Determine whether the conversion from FromType to ToType is a valid
1204 /// conversion that strips "noreturn" off the nested function type.
IsNoReturnConversion(QualType FromType,QualType ToType,QualType & ResultTy)1205 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1206                                 QualType &ResultTy) {
1207   if (Context.hasSameUnqualifiedType(FromType, ToType))
1208     return false;
1209 
1210   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1211   // where F adds one of the following at most once:
1212   //   - a pointer
1213   //   - a member pointer
1214   //   - a block pointer
1215   CanQualType CanTo = Context.getCanonicalType(ToType);
1216   CanQualType CanFrom = Context.getCanonicalType(FromType);
1217   Type::TypeClass TyClass = CanTo->getTypeClass();
1218   if (TyClass != CanFrom->getTypeClass()) return false;
1219   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1220     if (TyClass == Type::Pointer) {
1221       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1222       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1223     } else if (TyClass == Type::BlockPointer) {
1224       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1225       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1226     } else if (TyClass == Type::MemberPointer) {
1227       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1228       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1229     } else {
1230       return false;
1231     }
1232 
1233     TyClass = CanTo->getTypeClass();
1234     if (TyClass != CanFrom->getTypeClass()) return false;
1235     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1236       return false;
1237   }
1238 
1239   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1240   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1241   if (!EInfo.getNoReturn()) return false;
1242 
1243   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1244   assert(QualType(FromFn, 0).isCanonical());
1245   if (QualType(FromFn, 0) != CanTo) return false;
1246 
1247   ResultTy = ToType;
1248   return true;
1249 }
1250 
1251 /// \brief Determine whether the conversion from FromType to ToType is a valid
1252 /// vector conversion.
1253 ///
1254 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1255 /// conversion.
IsVectorConversion(ASTContext & Context,QualType FromType,QualType ToType,ImplicitConversionKind & ICK)1256 static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1257                                QualType ToType, ImplicitConversionKind &ICK) {
1258   // We need at least one of these types to be a vector type to have a vector
1259   // conversion.
1260   if (!ToType->isVectorType() && !FromType->isVectorType())
1261     return false;
1262 
1263   // Identical types require no conversions.
1264   if (Context.hasSameUnqualifiedType(FromType, ToType))
1265     return false;
1266 
1267   // There are no conversions between extended vector types, only identity.
1268   if (ToType->isExtVectorType()) {
1269     // There are no conversions between extended vector types other than the
1270     // identity conversion.
1271     if (FromType->isExtVectorType())
1272       return false;
1273 
1274     // Vector splat from any arithmetic type to a vector.
1275     if (FromType->isArithmeticType()) {
1276       ICK = ICK_Vector_Splat;
1277       return true;
1278     }
1279   }
1280 
1281   // We can perform the conversion between vector types in the following cases:
1282   // 1)vector types are equivalent AltiVec and GCC vector types
1283   // 2)lax vector conversions are permitted and the vector types are of the
1284   //   same size
1285   if (ToType->isVectorType() && FromType->isVectorType()) {
1286     if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1287         (Context.getLangOpts().LaxVectorConversions &&
1288          (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1289       ICK = ICK_Vector_Conversion;
1290       return true;
1291     }
1292   }
1293 
1294   return false;
1295 }
1296 
1297 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1298                                 bool InOverloadResolution,
1299                                 StandardConversionSequence &SCS,
1300                                 bool CStyle);
1301 
1302 /// IsStandardConversion - Determines whether there is a standard
1303 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1304 /// expression From to the type ToType. Standard conversion sequences
1305 /// only consider non-class types; for conversions that involve class
1306 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1307 /// contain the standard conversion sequence required to perform this
1308 /// conversion and this routine will return true. Otherwise, this
1309 /// routine will return false and the value of SCS is unspecified.
IsStandardConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle,bool AllowObjCWritebackConversion)1310 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1311                                  bool InOverloadResolution,
1312                                  StandardConversionSequence &SCS,
1313                                  bool CStyle,
1314                                  bool AllowObjCWritebackConversion) {
1315   QualType FromType = From->getType();
1316 
1317   // Standard conversions (C++ [conv])
1318   SCS.setAsIdentityConversion();
1319   SCS.DeprecatedStringLiteralToCharPtr = false;
1320   SCS.IncompatibleObjC = false;
1321   SCS.setFromType(FromType);
1322   SCS.CopyConstructor = 0;
1323 
1324   // There are no standard conversions for class types in C++, so
1325   // abort early. When overloading in C, however, we do permit
1326   if (FromType->isRecordType() || ToType->isRecordType()) {
1327     if (S.getLangOpts().CPlusPlus)
1328       return false;
1329 
1330     // When we're overloading in C, we allow, as standard conversions,
1331   }
1332 
1333   // The first conversion can be an lvalue-to-rvalue conversion,
1334   // array-to-pointer conversion, or function-to-pointer conversion
1335   // (C++ 4p1).
1336 
1337   if (FromType == S.Context.OverloadTy) {
1338     DeclAccessPair AccessPair;
1339     if (FunctionDecl *Fn
1340           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1341                                                  AccessPair)) {
1342       // We were able to resolve the address of the overloaded function,
1343       // so we can convert to the type of that function.
1344       FromType = Fn->getType();
1345 
1346       // we can sometimes resolve &foo<int> regardless of ToType, so check
1347       // if the type matches (identity) or we are converting to bool
1348       if (!S.Context.hasSameUnqualifiedType(
1349                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1350         QualType resultTy;
1351         // if the function type matches except for [[noreturn]], it's ok
1352         if (!S.IsNoReturnConversion(FromType,
1353               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1354           // otherwise, only a boolean conversion is standard
1355           if (!ToType->isBooleanType())
1356             return false;
1357       }
1358 
1359       // Check if the "from" expression is taking the address of an overloaded
1360       // function and recompute the FromType accordingly. Take advantage of the
1361       // fact that non-static member functions *must* have such an address-of
1362       // expression.
1363       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1364       if (Method && !Method->isStatic()) {
1365         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1366                "Non-unary operator on non-static member address");
1367         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1368                == UO_AddrOf &&
1369                "Non-address-of operator on non-static member address");
1370         const Type *ClassType
1371           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1372         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1373       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1374         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1375                UO_AddrOf &&
1376                "Non-address-of operator for overloaded function expression");
1377         FromType = S.Context.getPointerType(FromType);
1378       }
1379 
1380       // Check that we've computed the proper type after overload resolution.
1381       assert(S.Context.hasSameType(
1382         FromType,
1383         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1384     } else {
1385       return false;
1386     }
1387   }
1388   // Lvalue-to-rvalue conversion (C++11 4.1):
1389   //   A glvalue (3.10) of a non-function, non-array type T can
1390   //   be converted to a prvalue.
1391   bool argIsLValue = From->isGLValue();
1392   if (argIsLValue &&
1393       !FromType->isFunctionType() && !FromType->isArrayType() &&
1394       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1395     SCS.First = ICK_Lvalue_To_Rvalue;
1396 
1397     // C11 6.3.2.1p2:
1398     //   ... if the lvalue has atomic type, the value has the non-atomic version
1399     //   of the type of the lvalue ...
1400     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1401       FromType = Atomic->getValueType();
1402 
1403     // If T is a non-class type, the type of the rvalue is the
1404     // cv-unqualified version of T. Otherwise, the type of the rvalue
1405     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1406     // just strip the qualifiers because they don't matter.
1407     FromType = FromType.getUnqualifiedType();
1408   } else if (FromType->isArrayType()) {
1409     // Array-to-pointer conversion (C++ 4.2)
1410     SCS.First = ICK_Array_To_Pointer;
1411 
1412     // An lvalue or rvalue of type "array of N T" or "array of unknown
1413     // bound of T" can be converted to an rvalue of type "pointer to
1414     // T" (C++ 4.2p1).
1415     FromType = S.Context.getArrayDecayedType(FromType);
1416 
1417     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1418       // This conversion is deprecated. (C++ D.4).
1419       SCS.DeprecatedStringLiteralToCharPtr = true;
1420 
1421       // For the purpose of ranking in overload resolution
1422       // (13.3.3.1.1), this conversion is considered an
1423       // array-to-pointer conversion followed by a qualification
1424       // conversion (4.4). (C++ 4.2p2)
1425       SCS.Second = ICK_Identity;
1426       SCS.Third = ICK_Qualification;
1427       SCS.QualificationIncludesObjCLifetime = false;
1428       SCS.setAllToTypes(FromType);
1429       return true;
1430     }
1431   } else if (FromType->isFunctionType() && argIsLValue) {
1432     // Function-to-pointer conversion (C++ 4.3).
1433     SCS.First = ICK_Function_To_Pointer;
1434 
1435     // An lvalue of function type T can be converted to an rvalue of
1436     // type "pointer to T." The result is a pointer to the
1437     // function. (C++ 4.3p1).
1438     FromType = S.Context.getPointerType(FromType);
1439   } else {
1440     // We don't require any conversions for the first step.
1441     SCS.First = ICK_Identity;
1442   }
1443   SCS.setToType(0, FromType);
1444 
1445   // The second conversion can be an integral promotion, floating
1446   // point promotion, integral conversion, floating point conversion,
1447   // floating-integral conversion, pointer conversion,
1448   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1449   // For overloading in C, this can also be a "compatible-type"
1450   // conversion.
1451   bool IncompatibleObjC = false;
1452   ImplicitConversionKind SecondICK = ICK_Identity;
1453   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1454     // The unqualified versions of the types are the same: there's no
1455     // conversion to do.
1456     SCS.Second = ICK_Identity;
1457   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1458     // Integral promotion (C++ 4.5).
1459     SCS.Second = ICK_Integral_Promotion;
1460     FromType = ToType.getUnqualifiedType();
1461   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1462     // Floating point promotion (C++ 4.6).
1463     SCS.Second = ICK_Floating_Promotion;
1464     FromType = ToType.getUnqualifiedType();
1465   } else if (S.IsComplexPromotion(FromType, ToType)) {
1466     // Complex promotion (Clang extension)
1467     SCS.Second = ICK_Complex_Promotion;
1468     FromType = ToType.getUnqualifiedType();
1469   } else if (ToType->isBooleanType() &&
1470              (FromType->isArithmeticType() ||
1471               FromType->isAnyPointerType() ||
1472               FromType->isBlockPointerType() ||
1473               FromType->isMemberPointerType() ||
1474               FromType->isNullPtrType())) {
1475     // Boolean conversions (C++ 4.12).
1476     SCS.Second = ICK_Boolean_Conversion;
1477     FromType = S.Context.BoolTy;
1478   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1479              ToType->isIntegralType(S.Context)) {
1480     // Integral conversions (C++ 4.7).
1481     SCS.Second = ICK_Integral_Conversion;
1482     FromType = ToType.getUnqualifiedType();
1483   } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1484     // Complex conversions (C99 6.3.1.6)
1485     SCS.Second = ICK_Complex_Conversion;
1486     FromType = ToType.getUnqualifiedType();
1487   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1488              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1489     // Complex-real conversions (C99 6.3.1.7)
1490     SCS.Second = ICK_Complex_Real;
1491     FromType = ToType.getUnqualifiedType();
1492   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1493     // Floating point conversions (C++ 4.8).
1494     SCS.Second = ICK_Floating_Conversion;
1495     FromType = ToType.getUnqualifiedType();
1496   } else if ((FromType->isRealFloatingType() &&
1497               ToType->isIntegralType(S.Context)) ||
1498              (FromType->isIntegralOrUnscopedEnumerationType() &&
1499               ToType->isRealFloatingType())) {
1500     // Floating-integral conversions (C++ 4.9).
1501     SCS.Second = ICK_Floating_Integral;
1502     FromType = ToType.getUnqualifiedType();
1503   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1504     SCS.Second = ICK_Block_Pointer_Conversion;
1505   } else if (AllowObjCWritebackConversion &&
1506              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1507     SCS.Second = ICK_Writeback_Conversion;
1508   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1509                                    FromType, IncompatibleObjC)) {
1510     // Pointer conversions (C++ 4.10).
1511     SCS.Second = ICK_Pointer_Conversion;
1512     SCS.IncompatibleObjC = IncompatibleObjC;
1513     FromType = FromType.getUnqualifiedType();
1514   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1515                                          InOverloadResolution, FromType)) {
1516     // Pointer to member conversions (4.11).
1517     SCS.Second = ICK_Pointer_Member;
1518   } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1519     SCS.Second = SecondICK;
1520     FromType = ToType.getUnqualifiedType();
1521   } else if (!S.getLangOpts().CPlusPlus &&
1522              S.Context.typesAreCompatible(ToType, FromType)) {
1523     // Compatible conversions (Clang extension for C function overloading)
1524     SCS.Second = ICK_Compatible_Conversion;
1525     FromType = ToType.getUnqualifiedType();
1526   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1527     // Treat a conversion that strips "noreturn" as an identity conversion.
1528     SCS.Second = ICK_NoReturn_Adjustment;
1529   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1530                                              InOverloadResolution,
1531                                              SCS, CStyle)) {
1532     SCS.Second = ICK_TransparentUnionConversion;
1533     FromType = ToType;
1534   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1535                                  CStyle)) {
1536     // tryAtomicConversion has updated the standard conversion sequence
1537     // appropriately.
1538     return true;
1539   } else {
1540     // No second conversion required.
1541     SCS.Second = ICK_Identity;
1542   }
1543   SCS.setToType(1, FromType);
1544 
1545   QualType CanonFrom;
1546   QualType CanonTo;
1547   // The third conversion can be a qualification conversion (C++ 4p1).
1548   bool ObjCLifetimeConversion;
1549   if (S.IsQualificationConversion(FromType, ToType, CStyle,
1550                                   ObjCLifetimeConversion)) {
1551     SCS.Third = ICK_Qualification;
1552     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1553     FromType = ToType;
1554     CanonFrom = S.Context.getCanonicalType(FromType);
1555     CanonTo = S.Context.getCanonicalType(ToType);
1556   } else {
1557     // No conversion required
1558     SCS.Third = ICK_Identity;
1559 
1560     // C++ [over.best.ics]p6:
1561     //   [...] Any difference in top-level cv-qualification is
1562     //   subsumed by the initialization itself and does not constitute
1563     //   a conversion. [...]
1564     CanonFrom = S.Context.getCanonicalType(FromType);
1565     CanonTo = S.Context.getCanonicalType(ToType);
1566     if (CanonFrom.getLocalUnqualifiedType()
1567                                        == CanonTo.getLocalUnqualifiedType() &&
1568         (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1569          || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1570          || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
1571       FromType = ToType;
1572       CanonFrom = CanonTo;
1573     }
1574   }
1575   SCS.setToType(2, FromType);
1576 
1577   // If we have not converted the argument type to the parameter type,
1578   // this is a bad conversion sequence.
1579   if (CanonFrom != CanonTo)
1580     return false;
1581 
1582   return true;
1583 }
1584 
1585 static bool
IsTransparentUnionStandardConversion(Sema & S,Expr * From,QualType & ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)1586 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1587                                      QualType &ToType,
1588                                      bool InOverloadResolution,
1589                                      StandardConversionSequence &SCS,
1590                                      bool CStyle) {
1591 
1592   const RecordType *UT = ToType->getAsUnionType();
1593   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1594     return false;
1595   // The field to initialize within the transparent union.
1596   RecordDecl *UD = UT->getDecl();
1597   // It's compatible if the expression matches any of the fields.
1598   for (RecordDecl::field_iterator it = UD->field_begin(),
1599        itend = UD->field_end();
1600        it != itend; ++it) {
1601     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1602                              CStyle, /*ObjCWritebackConversion=*/false)) {
1603       ToType = it->getType();
1604       return true;
1605     }
1606   }
1607   return false;
1608 }
1609 
1610 /// IsIntegralPromotion - Determines whether the conversion from the
1611 /// expression From (whose potentially-adjusted type is FromType) to
1612 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1613 /// sets PromotedType to the promoted type.
IsIntegralPromotion(Expr * From,QualType FromType,QualType ToType)1614 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1615   const BuiltinType *To = ToType->getAs<BuiltinType>();
1616   // All integers are built-in.
1617   if (!To) {
1618     return false;
1619   }
1620 
1621   // An rvalue of type char, signed char, unsigned char, short int, or
1622   // unsigned short int can be converted to an rvalue of type int if
1623   // int can represent all the values of the source type; otherwise,
1624   // the source rvalue can be converted to an rvalue of type unsigned
1625   // int (C++ 4.5p1).
1626   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1627       !FromType->isEnumeralType()) {
1628     if (// We can promote any signed, promotable integer type to an int
1629         (FromType->isSignedIntegerType() ||
1630          // We can promote any unsigned integer type whose size is
1631          // less than int to an int.
1632          (!FromType->isSignedIntegerType() &&
1633           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1634       return To->getKind() == BuiltinType::Int;
1635     }
1636 
1637     return To->getKind() == BuiltinType::UInt;
1638   }
1639 
1640   // C++0x [conv.prom]p3:
1641   //   A prvalue of an unscoped enumeration type whose underlying type is not
1642   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1643   //   following types that can represent all the values of the enumeration
1644   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1645   //   unsigned int, long int, unsigned long int, long long int, or unsigned
1646   //   long long int. If none of the types in that list can represent all the
1647   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1648   //   type can be converted to an rvalue a prvalue of the extended integer type
1649   //   with lowest integer conversion rank (4.13) greater than the rank of long
1650   //   long in which all the values of the enumeration can be represented. If
1651   //   there are two such extended types, the signed one is chosen.
1652   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1653     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1654     // provided for a scoped enumeration.
1655     if (FromEnumType->getDecl()->isScoped())
1656       return false;
1657 
1658     // We have already pre-calculated the promotion type, so this is trivial.
1659     if (ToType->isIntegerType() &&
1660         !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
1661       return Context.hasSameUnqualifiedType(ToType,
1662                                 FromEnumType->getDecl()->getPromotionType());
1663   }
1664 
1665   // C++0x [conv.prom]p2:
1666   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1667   //   to an rvalue a prvalue of the first of the following types that can
1668   //   represent all the values of its underlying type: int, unsigned int,
1669   //   long int, unsigned long int, long long int, or unsigned long long int.
1670   //   If none of the types in that list can represent all the values of its
1671   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1672   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1673   //   type.
1674   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1675       ToType->isIntegerType()) {
1676     // Determine whether the type we're converting from is signed or
1677     // unsigned.
1678     bool FromIsSigned = FromType->isSignedIntegerType();
1679     uint64_t FromSize = Context.getTypeSize(FromType);
1680 
1681     // The types we'll try to promote to, in the appropriate
1682     // order. Try each of these types.
1683     QualType PromoteTypes[6] = {
1684       Context.IntTy, Context.UnsignedIntTy,
1685       Context.LongTy, Context.UnsignedLongTy ,
1686       Context.LongLongTy, Context.UnsignedLongLongTy
1687     };
1688     for (int Idx = 0; Idx < 6; ++Idx) {
1689       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1690       if (FromSize < ToSize ||
1691           (FromSize == ToSize &&
1692            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1693         // We found the type that we can promote to. If this is the
1694         // type we wanted, we have a promotion. Otherwise, no
1695         // promotion.
1696         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1697       }
1698     }
1699   }
1700 
1701   // An rvalue for an integral bit-field (9.6) can be converted to an
1702   // rvalue of type int if int can represent all the values of the
1703   // bit-field; otherwise, it can be converted to unsigned int if
1704   // unsigned int can represent all the values of the bit-field. If
1705   // the bit-field is larger yet, no integral promotion applies to
1706   // it. If the bit-field has an enumerated type, it is treated as any
1707   // other value of that type for promotion purposes (C++ 4.5p3).
1708   // FIXME: We should delay checking of bit-fields until we actually perform the
1709   // conversion.
1710   using llvm::APSInt;
1711   if (From)
1712     if (FieldDecl *MemberDecl = From->getBitField()) {
1713       APSInt BitWidth;
1714       if (FromType->isIntegralType(Context) &&
1715           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1716         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1717         ToSize = Context.getTypeSize(ToType);
1718 
1719         // Are we promoting to an int from a bitfield that fits in an int?
1720         if (BitWidth < ToSize ||
1721             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1722           return To->getKind() == BuiltinType::Int;
1723         }
1724 
1725         // Are we promoting to an unsigned int from an unsigned bitfield
1726         // that fits into an unsigned int?
1727         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1728           return To->getKind() == BuiltinType::UInt;
1729         }
1730 
1731         return false;
1732       }
1733     }
1734 
1735   // An rvalue of type bool can be converted to an rvalue of type int,
1736   // with false becoming zero and true becoming one (C++ 4.5p4).
1737   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1738     return true;
1739   }
1740 
1741   return false;
1742 }
1743 
1744 /// IsFloatingPointPromotion - Determines whether the conversion from
1745 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1746 /// returns true and sets PromotedType to the promoted type.
IsFloatingPointPromotion(QualType FromType,QualType ToType)1747 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1748   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1749     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1750       /// An rvalue of type float can be converted to an rvalue of type
1751       /// double. (C++ 4.6p1).
1752       if (FromBuiltin->getKind() == BuiltinType::Float &&
1753           ToBuiltin->getKind() == BuiltinType::Double)
1754         return true;
1755 
1756       // C99 6.3.1.5p1:
1757       //   When a float is promoted to double or long double, or a
1758       //   double is promoted to long double [...].
1759       if (!getLangOpts().CPlusPlus &&
1760           (FromBuiltin->getKind() == BuiltinType::Float ||
1761            FromBuiltin->getKind() == BuiltinType::Double) &&
1762           (ToBuiltin->getKind() == BuiltinType::LongDouble))
1763         return true;
1764 
1765       // Half can be promoted to float.
1766       if (FromBuiltin->getKind() == BuiltinType::Half &&
1767           ToBuiltin->getKind() == BuiltinType::Float)
1768         return true;
1769     }
1770 
1771   return false;
1772 }
1773 
1774 /// \brief Determine if a conversion is a complex promotion.
1775 ///
1776 /// A complex promotion is defined as a complex -> complex conversion
1777 /// where the conversion between the underlying real types is a
1778 /// floating-point or integral promotion.
IsComplexPromotion(QualType FromType,QualType ToType)1779 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1780   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1781   if (!FromComplex)
1782     return false;
1783 
1784   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1785   if (!ToComplex)
1786     return false;
1787 
1788   return IsFloatingPointPromotion(FromComplex->getElementType(),
1789                                   ToComplex->getElementType()) ||
1790     IsIntegralPromotion(0, FromComplex->getElementType(),
1791                         ToComplex->getElementType());
1792 }
1793 
1794 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1795 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1796 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1797 /// if non-empty, will be a pointer to ToType that may or may not have
1798 /// the right set of qualifiers on its pointee.
1799 ///
1800 static QualType
BuildSimilarlyQualifiedPointerType(const Type * FromPtr,QualType ToPointee,QualType ToType,ASTContext & Context,bool StripObjCLifetime=false)1801 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1802                                    QualType ToPointee, QualType ToType,
1803                                    ASTContext &Context,
1804                                    bool StripObjCLifetime = false) {
1805   assert((FromPtr->getTypeClass() == Type::Pointer ||
1806           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1807          "Invalid similarly-qualified pointer type");
1808 
1809   /// Conversions to 'id' subsume cv-qualifier conversions.
1810   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1811     return ToType.getUnqualifiedType();
1812 
1813   QualType CanonFromPointee
1814     = Context.getCanonicalType(FromPtr->getPointeeType());
1815   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1816   Qualifiers Quals = CanonFromPointee.getQualifiers();
1817 
1818   if (StripObjCLifetime)
1819     Quals.removeObjCLifetime();
1820 
1821   // Exact qualifier match -> return the pointer type we're converting to.
1822   if (CanonToPointee.getLocalQualifiers() == Quals) {
1823     // ToType is exactly what we need. Return it.
1824     if (!ToType.isNull())
1825       return ToType.getUnqualifiedType();
1826 
1827     // Build a pointer to ToPointee. It has the right qualifiers
1828     // already.
1829     if (isa<ObjCObjectPointerType>(ToType))
1830       return Context.getObjCObjectPointerType(ToPointee);
1831     return Context.getPointerType(ToPointee);
1832   }
1833 
1834   // Just build a canonical type that has the right qualifiers.
1835   QualType QualifiedCanonToPointee
1836     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1837 
1838   if (isa<ObjCObjectPointerType>(ToType))
1839     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1840   return Context.getPointerType(QualifiedCanonToPointee);
1841 }
1842 
isNullPointerConstantForConversion(Expr * Expr,bool InOverloadResolution,ASTContext & Context)1843 static bool isNullPointerConstantForConversion(Expr *Expr,
1844                                                bool InOverloadResolution,
1845                                                ASTContext &Context) {
1846   // Handle value-dependent integral null pointer constants correctly.
1847   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1848   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1849       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1850     return !InOverloadResolution;
1851 
1852   return Expr->isNullPointerConstant(Context,
1853                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1854                                         : Expr::NPC_ValueDependentIsNull);
1855 }
1856 
1857 /// IsPointerConversion - Determines whether the conversion of the
1858 /// expression From, which has the (possibly adjusted) type FromType,
1859 /// can be converted to the type ToType via a pointer conversion (C++
1860 /// 4.10). If so, returns true and places the converted type (that
1861 /// might differ from ToType in its cv-qualifiers at some level) into
1862 /// ConvertedType.
1863 ///
1864 /// This routine also supports conversions to and from block pointers
1865 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1866 /// pointers to interfaces. FIXME: Once we've determined the
1867 /// appropriate overloading rules for Objective-C, we may want to
1868 /// split the Objective-C checks into a different routine; however,
1869 /// GCC seems to consider all of these conversions to be pointer
1870 /// conversions, so for now they live here. IncompatibleObjC will be
1871 /// set if the conversion is an allowed Objective-C conversion that
1872 /// should result in a warning.
IsPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType,bool & IncompatibleObjC)1873 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1874                                bool InOverloadResolution,
1875                                QualType& ConvertedType,
1876                                bool &IncompatibleObjC) {
1877   IncompatibleObjC = false;
1878   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1879                               IncompatibleObjC))
1880     return true;
1881 
1882   // Conversion from a null pointer constant to any Objective-C pointer type.
1883   if (ToType->isObjCObjectPointerType() &&
1884       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1885     ConvertedType = ToType;
1886     return true;
1887   }
1888 
1889   // Blocks: Block pointers can be converted to void*.
1890   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1891       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1892     ConvertedType = ToType;
1893     return true;
1894   }
1895   // Blocks: A null pointer constant can be converted to a block
1896   // pointer type.
1897   if (ToType->isBlockPointerType() &&
1898       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1899     ConvertedType = ToType;
1900     return true;
1901   }
1902 
1903   // If the left-hand-side is nullptr_t, the right side can be a null
1904   // pointer constant.
1905   if (ToType->isNullPtrType() &&
1906       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1907     ConvertedType = ToType;
1908     return true;
1909   }
1910 
1911   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1912   if (!ToTypePtr)
1913     return false;
1914 
1915   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1916   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1917     ConvertedType = ToType;
1918     return true;
1919   }
1920 
1921   // Beyond this point, both types need to be pointers
1922   // , including objective-c pointers.
1923   QualType ToPointeeType = ToTypePtr->getPointeeType();
1924   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1925       !getLangOpts().ObjCAutoRefCount) {
1926     ConvertedType = BuildSimilarlyQualifiedPointerType(
1927                                       FromType->getAs<ObjCObjectPointerType>(),
1928                                                        ToPointeeType,
1929                                                        ToType, Context);
1930     return true;
1931   }
1932   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1933   if (!FromTypePtr)
1934     return false;
1935 
1936   QualType FromPointeeType = FromTypePtr->getPointeeType();
1937 
1938   // If the unqualified pointee types are the same, this can't be a
1939   // pointer conversion, so don't do all of the work below.
1940   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1941     return false;
1942 
1943   // An rvalue of type "pointer to cv T," where T is an object type,
1944   // can be converted to an rvalue of type "pointer to cv void" (C++
1945   // 4.10p2).
1946   if (FromPointeeType->isIncompleteOrObjectType() &&
1947       ToPointeeType->isVoidType()) {
1948     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1949                                                        ToPointeeType,
1950                                                        ToType, Context,
1951                                                    /*StripObjCLifetime=*/true);
1952     return true;
1953   }
1954 
1955   // MSVC allows implicit function to void* type conversion.
1956   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
1957       ToPointeeType->isVoidType()) {
1958     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1959                                                        ToPointeeType,
1960                                                        ToType, Context);
1961     return true;
1962   }
1963 
1964   // When we're overloading in C, we allow a special kind of pointer
1965   // conversion for compatible-but-not-identical pointee types.
1966   if (!getLangOpts().CPlusPlus &&
1967       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1968     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1969                                                        ToPointeeType,
1970                                                        ToType, Context);
1971     return true;
1972   }
1973 
1974   // C++ [conv.ptr]p3:
1975   //
1976   //   An rvalue of type "pointer to cv D," where D is a class type,
1977   //   can be converted to an rvalue of type "pointer to cv B," where
1978   //   B is a base class (clause 10) of D. If B is an inaccessible
1979   //   (clause 11) or ambiguous (10.2) base class of D, a program that
1980   //   necessitates this conversion is ill-formed. The result of the
1981   //   conversion is a pointer to the base class sub-object of the
1982   //   derived class object. The null pointer value is converted to
1983   //   the null pointer value of the destination type.
1984   //
1985   // Note that we do not check for ambiguity or inaccessibility
1986   // here. That is handled by CheckPointerConversion.
1987   if (getLangOpts().CPlusPlus &&
1988       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1989       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
1990       !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1991       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1992     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1993                                                        ToPointeeType,
1994                                                        ToType, Context);
1995     return true;
1996   }
1997 
1998   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1999       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2000     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2001                                                        ToPointeeType,
2002                                                        ToType, Context);
2003     return true;
2004   }
2005 
2006   return false;
2007 }
2008 
2009 /// \brief Adopt the given qualifiers for the given type.
AdoptQualifiers(ASTContext & Context,QualType T,Qualifiers Qs)2010 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2011   Qualifiers TQs = T.getQualifiers();
2012 
2013   // Check whether qualifiers already match.
2014   if (TQs == Qs)
2015     return T;
2016 
2017   if (Qs.compatiblyIncludes(TQs))
2018     return Context.getQualifiedType(T, Qs);
2019 
2020   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2021 }
2022 
2023 /// isObjCPointerConversion - Determines whether this is an
2024 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2025 /// with the same arguments and return values.
isObjCPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType,bool & IncompatibleObjC)2026 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2027                                    QualType& ConvertedType,
2028                                    bool &IncompatibleObjC) {
2029   if (!getLangOpts().ObjC1)
2030     return false;
2031 
2032   // The set of qualifiers on the type we're converting from.
2033   Qualifiers FromQualifiers = FromType.getQualifiers();
2034 
2035   // First, we handle all conversions on ObjC object pointer types.
2036   const ObjCObjectPointerType* ToObjCPtr =
2037     ToType->getAs<ObjCObjectPointerType>();
2038   const ObjCObjectPointerType *FromObjCPtr =
2039     FromType->getAs<ObjCObjectPointerType>();
2040 
2041   if (ToObjCPtr && FromObjCPtr) {
2042     // If the pointee types are the same (ignoring qualifications),
2043     // then this is not a pointer conversion.
2044     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2045                                        FromObjCPtr->getPointeeType()))
2046       return false;
2047 
2048     // Check for compatible
2049     // Objective C++: We're able to convert between "id" or "Class" and a
2050     // pointer to any interface (in both directions).
2051     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2052       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2053       return true;
2054     }
2055     // Conversions with Objective-C's id<...>.
2056     if ((FromObjCPtr->isObjCQualifiedIdType() ||
2057          ToObjCPtr->isObjCQualifiedIdType()) &&
2058         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2059                                                   /*compare=*/false)) {
2060       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2061       return true;
2062     }
2063     // Objective C++: We're able to convert from a pointer to an
2064     // interface to a pointer to a different interface.
2065     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2066       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2067       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2068       if (getLangOpts().CPlusPlus && LHS && RHS &&
2069           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2070                                                 FromObjCPtr->getPointeeType()))
2071         return false;
2072       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2073                                                    ToObjCPtr->getPointeeType(),
2074                                                          ToType, Context);
2075       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2076       return true;
2077     }
2078 
2079     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2080       // Okay: this is some kind of implicit downcast of Objective-C
2081       // interfaces, which is permitted. However, we're going to
2082       // complain about it.
2083       IncompatibleObjC = true;
2084       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2085                                                    ToObjCPtr->getPointeeType(),
2086                                                          ToType, Context);
2087       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2088       return true;
2089     }
2090   }
2091   // Beyond this point, both types need to be C pointers or block pointers.
2092   QualType ToPointeeType;
2093   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2094     ToPointeeType = ToCPtr->getPointeeType();
2095   else if (const BlockPointerType *ToBlockPtr =
2096             ToType->getAs<BlockPointerType>()) {
2097     // Objective C++: We're able to convert from a pointer to any object
2098     // to a block pointer type.
2099     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2100       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2101       return true;
2102     }
2103     ToPointeeType = ToBlockPtr->getPointeeType();
2104   }
2105   else if (FromType->getAs<BlockPointerType>() &&
2106            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2107     // Objective C++: We're able to convert from a block pointer type to a
2108     // pointer to any object.
2109     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2110     return true;
2111   }
2112   else
2113     return false;
2114 
2115   QualType FromPointeeType;
2116   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2117     FromPointeeType = FromCPtr->getPointeeType();
2118   else if (const BlockPointerType *FromBlockPtr =
2119            FromType->getAs<BlockPointerType>())
2120     FromPointeeType = FromBlockPtr->getPointeeType();
2121   else
2122     return false;
2123 
2124   // If we have pointers to pointers, recursively check whether this
2125   // is an Objective-C conversion.
2126   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2127       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2128                               IncompatibleObjC)) {
2129     // We always complain about this conversion.
2130     IncompatibleObjC = true;
2131     ConvertedType = Context.getPointerType(ConvertedType);
2132     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2133     return true;
2134   }
2135   // Allow conversion of pointee being objective-c pointer to another one;
2136   // as in I* to id.
2137   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2138       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2139       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2140                               IncompatibleObjC)) {
2141 
2142     ConvertedType = Context.getPointerType(ConvertedType);
2143     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2144     return true;
2145   }
2146 
2147   // If we have pointers to functions or blocks, check whether the only
2148   // differences in the argument and result types are in Objective-C
2149   // pointer conversions. If so, we permit the conversion (but
2150   // complain about it).
2151   const FunctionProtoType *FromFunctionType
2152     = FromPointeeType->getAs<FunctionProtoType>();
2153   const FunctionProtoType *ToFunctionType
2154     = ToPointeeType->getAs<FunctionProtoType>();
2155   if (FromFunctionType && ToFunctionType) {
2156     // If the function types are exactly the same, this isn't an
2157     // Objective-C pointer conversion.
2158     if (Context.getCanonicalType(FromPointeeType)
2159           == Context.getCanonicalType(ToPointeeType))
2160       return false;
2161 
2162     // Perform the quick checks that will tell us whether these
2163     // function types are obviously different.
2164     if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2165         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2166         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2167       return false;
2168 
2169     bool HasObjCConversion = false;
2170     if (Context.getCanonicalType(FromFunctionType->getResultType())
2171           == Context.getCanonicalType(ToFunctionType->getResultType())) {
2172       // Okay, the types match exactly. Nothing to do.
2173     } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2174                                        ToFunctionType->getResultType(),
2175                                        ConvertedType, IncompatibleObjC)) {
2176       // Okay, we have an Objective-C pointer conversion.
2177       HasObjCConversion = true;
2178     } else {
2179       // Function types are too different. Abort.
2180       return false;
2181     }
2182 
2183     // Check argument types.
2184     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2185          ArgIdx != NumArgs; ++ArgIdx) {
2186       QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2187       QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2188       if (Context.getCanonicalType(FromArgType)
2189             == Context.getCanonicalType(ToArgType)) {
2190         // Okay, the types match exactly. Nothing to do.
2191       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2192                                          ConvertedType, IncompatibleObjC)) {
2193         // Okay, we have an Objective-C pointer conversion.
2194         HasObjCConversion = true;
2195       } else {
2196         // Argument types are too different. Abort.
2197         return false;
2198       }
2199     }
2200 
2201     if (HasObjCConversion) {
2202       // We had an Objective-C conversion. Allow this pointer
2203       // conversion, but complain about it.
2204       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2205       IncompatibleObjC = true;
2206       return true;
2207     }
2208   }
2209 
2210   return false;
2211 }
2212 
2213 /// \brief Determine whether this is an Objective-C writeback conversion,
2214 /// used for parameter passing when performing automatic reference counting.
2215 ///
2216 /// \param FromType The type we're converting form.
2217 ///
2218 /// \param ToType The type we're converting to.
2219 ///
2220 /// \param ConvertedType The type that will be produced after applying
2221 /// this conversion.
isObjCWritebackConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2222 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2223                                      QualType &ConvertedType) {
2224   if (!getLangOpts().ObjCAutoRefCount ||
2225       Context.hasSameUnqualifiedType(FromType, ToType))
2226     return false;
2227 
2228   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2229   QualType ToPointee;
2230   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2231     ToPointee = ToPointer->getPointeeType();
2232   else
2233     return false;
2234 
2235   Qualifiers ToQuals = ToPointee.getQualifiers();
2236   if (!ToPointee->isObjCLifetimeType() ||
2237       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2238       !ToQuals.withoutObjCLifetime().empty())
2239     return false;
2240 
2241   // Argument must be a pointer to __strong to __weak.
2242   QualType FromPointee;
2243   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2244     FromPointee = FromPointer->getPointeeType();
2245   else
2246     return false;
2247 
2248   Qualifiers FromQuals = FromPointee.getQualifiers();
2249   if (!FromPointee->isObjCLifetimeType() ||
2250       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2251        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2252     return false;
2253 
2254   // Make sure that we have compatible qualifiers.
2255   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2256   if (!ToQuals.compatiblyIncludes(FromQuals))
2257     return false;
2258 
2259   // Remove qualifiers from the pointee type we're converting from; they
2260   // aren't used in the compatibility check belong, and we'll be adding back
2261   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2262   FromPointee = FromPointee.getUnqualifiedType();
2263 
2264   // The unqualified form of the pointee types must be compatible.
2265   ToPointee = ToPointee.getUnqualifiedType();
2266   bool IncompatibleObjC;
2267   if (Context.typesAreCompatible(FromPointee, ToPointee))
2268     FromPointee = ToPointee;
2269   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2270                                     IncompatibleObjC))
2271     return false;
2272 
2273   /// \brief Construct the type we're converting to, which is a pointer to
2274   /// __autoreleasing pointee.
2275   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2276   ConvertedType = Context.getPointerType(FromPointee);
2277   return true;
2278 }
2279 
IsBlockPointerConversion(QualType FromType,QualType ToType,QualType & ConvertedType)2280 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2281                                     QualType& ConvertedType) {
2282   QualType ToPointeeType;
2283   if (const BlockPointerType *ToBlockPtr =
2284         ToType->getAs<BlockPointerType>())
2285     ToPointeeType = ToBlockPtr->getPointeeType();
2286   else
2287     return false;
2288 
2289   QualType FromPointeeType;
2290   if (const BlockPointerType *FromBlockPtr =
2291       FromType->getAs<BlockPointerType>())
2292     FromPointeeType = FromBlockPtr->getPointeeType();
2293   else
2294     return false;
2295   // We have pointer to blocks, check whether the only
2296   // differences in the argument and result types are in Objective-C
2297   // pointer conversions. If so, we permit the conversion.
2298 
2299   const FunctionProtoType *FromFunctionType
2300     = FromPointeeType->getAs<FunctionProtoType>();
2301   const FunctionProtoType *ToFunctionType
2302     = ToPointeeType->getAs<FunctionProtoType>();
2303 
2304   if (!FromFunctionType || !ToFunctionType)
2305     return false;
2306 
2307   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2308     return true;
2309 
2310   // Perform the quick checks that will tell us whether these
2311   // function types are obviously different.
2312   if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2313       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2314     return false;
2315 
2316   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2317   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2318   if (FromEInfo != ToEInfo)
2319     return false;
2320 
2321   bool IncompatibleObjC = false;
2322   if (Context.hasSameType(FromFunctionType->getResultType(),
2323                           ToFunctionType->getResultType())) {
2324     // Okay, the types match exactly. Nothing to do.
2325   } else {
2326     QualType RHS = FromFunctionType->getResultType();
2327     QualType LHS = ToFunctionType->getResultType();
2328     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2329         !RHS.hasQualifiers() && LHS.hasQualifiers())
2330        LHS = LHS.getUnqualifiedType();
2331 
2332      if (Context.hasSameType(RHS,LHS)) {
2333        // OK exact match.
2334      } else if (isObjCPointerConversion(RHS, LHS,
2335                                         ConvertedType, IncompatibleObjC)) {
2336      if (IncompatibleObjC)
2337        return false;
2338      // Okay, we have an Objective-C pointer conversion.
2339      }
2340      else
2341        return false;
2342    }
2343 
2344    // Check argument types.
2345    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2346         ArgIdx != NumArgs; ++ArgIdx) {
2347      IncompatibleObjC = false;
2348      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2349      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2350      if (Context.hasSameType(FromArgType, ToArgType)) {
2351        // Okay, the types match exactly. Nothing to do.
2352      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2353                                         ConvertedType, IncompatibleObjC)) {
2354        if (IncompatibleObjC)
2355          return false;
2356        // Okay, we have an Objective-C pointer conversion.
2357      } else
2358        // Argument types are too different. Abort.
2359        return false;
2360    }
2361    if (LangOpts.ObjCAutoRefCount &&
2362        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2363                                                     ToFunctionType))
2364      return false;
2365 
2366    ConvertedType = ToType;
2367    return true;
2368 }
2369 
2370 enum {
2371   ft_default,
2372   ft_different_class,
2373   ft_parameter_arity,
2374   ft_parameter_mismatch,
2375   ft_return_type,
2376   ft_qualifer_mismatch
2377 };
2378 
2379 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2380 /// function types.  Catches different number of parameter, mismatch in
2381 /// parameter types, and different return types.
HandleFunctionTypeMismatch(PartialDiagnostic & PDiag,QualType FromType,QualType ToType)2382 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2383                                       QualType FromType, QualType ToType) {
2384   // If either type is not valid, include no extra info.
2385   if (FromType.isNull() || ToType.isNull()) {
2386     PDiag << ft_default;
2387     return;
2388   }
2389 
2390   // Get the function type from the pointers.
2391   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2392     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2393                             *ToMember = ToType->getAs<MemberPointerType>();
2394     if (FromMember->getClass() != ToMember->getClass()) {
2395       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2396             << QualType(FromMember->getClass(), 0);
2397       return;
2398     }
2399     FromType = FromMember->getPointeeType();
2400     ToType = ToMember->getPointeeType();
2401   }
2402 
2403   if (FromType->isPointerType())
2404     FromType = FromType->getPointeeType();
2405   if (ToType->isPointerType())
2406     ToType = ToType->getPointeeType();
2407 
2408   // Remove references.
2409   FromType = FromType.getNonReferenceType();
2410   ToType = ToType.getNonReferenceType();
2411 
2412   // Don't print extra info for non-specialized template functions.
2413   if (FromType->isInstantiationDependentType() &&
2414       !FromType->getAs<TemplateSpecializationType>()) {
2415     PDiag << ft_default;
2416     return;
2417   }
2418 
2419   // No extra info for same types.
2420   if (Context.hasSameType(FromType, ToType)) {
2421     PDiag << ft_default;
2422     return;
2423   }
2424 
2425   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2426                           *ToFunction = ToType->getAs<FunctionProtoType>();
2427 
2428   // Both types need to be function types.
2429   if (!FromFunction || !ToFunction) {
2430     PDiag << ft_default;
2431     return;
2432   }
2433 
2434   if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2435     PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2436           << FromFunction->getNumArgs();
2437     return;
2438   }
2439 
2440   // Handle different parameter types.
2441   unsigned ArgPos;
2442   if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2443     PDiag << ft_parameter_mismatch << ArgPos + 1
2444           << ToFunction->getArgType(ArgPos)
2445           << FromFunction->getArgType(ArgPos);
2446     return;
2447   }
2448 
2449   // Handle different return type.
2450   if (!Context.hasSameType(FromFunction->getResultType(),
2451                            ToFunction->getResultType())) {
2452     PDiag << ft_return_type << ToFunction->getResultType()
2453           << FromFunction->getResultType();
2454     return;
2455   }
2456 
2457   unsigned FromQuals = FromFunction->getTypeQuals(),
2458            ToQuals = ToFunction->getTypeQuals();
2459   if (FromQuals != ToQuals) {
2460     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2461     return;
2462   }
2463 
2464   // Unable to find a difference, so add no extra info.
2465   PDiag << ft_default;
2466 }
2467 
2468 /// FunctionArgTypesAreEqual - This routine checks two function proto types
2469 /// for equality of their argument types. Caller has already checked that
2470 /// they have same number of arguments. This routine assumes that Objective-C
2471 /// pointer types which only differ in their protocol qualifiers are equal.
2472 /// If the parameters are different, ArgPos will have the the parameter index
2473 /// of the first different parameter.
FunctionArgTypesAreEqual(const FunctionProtoType * OldType,const FunctionProtoType * NewType,unsigned * ArgPos)2474 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2475                                     const FunctionProtoType *NewType,
2476                                     unsigned *ArgPos) {
2477   if (!getLangOpts().ObjC1) {
2478     for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2479          N = NewType->arg_type_begin(),
2480          E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2481       if (!Context.hasSameType(*O, *N)) {
2482         if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2483         return false;
2484       }
2485     }
2486     return true;
2487   }
2488 
2489   for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2490        N = NewType->arg_type_begin(),
2491        E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2492     QualType ToType = (*O);
2493     QualType FromType = (*N);
2494     if (!Context.hasSameType(ToType, FromType)) {
2495       if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2496         if (const PointerType *PTFr = FromType->getAs<PointerType>())
2497           if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2498                PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2499               (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2500                PTFr->getPointeeType()->isObjCQualifiedClassType()))
2501             continue;
2502       }
2503       else if (const ObjCObjectPointerType *PTTo =
2504                  ToType->getAs<ObjCObjectPointerType>()) {
2505         if (const ObjCObjectPointerType *PTFr =
2506               FromType->getAs<ObjCObjectPointerType>())
2507           if (Context.hasSameUnqualifiedType(
2508                 PTTo->getObjectType()->getBaseType(),
2509                 PTFr->getObjectType()->getBaseType()))
2510             continue;
2511       }
2512       if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2513       return false;
2514     }
2515   }
2516   return true;
2517 }
2518 
2519 /// CheckPointerConversion - Check the pointer conversion from the
2520 /// expression From to the type ToType. This routine checks for
2521 /// ambiguous or inaccessible derived-to-base pointer
2522 /// conversions for which IsPointerConversion has already returned
2523 /// true. It returns true and produces a diagnostic if there was an
2524 /// error, or returns false otherwise.
CheckPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess)2525 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2526                                   CastKind &Kind,
2527                                   CXXCastPath& BasePath,
2528                                   bool IgnoreBaseAccess) {
2529   QualType FromType = From->getType();
2530   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2531 
2532   Kind = CK_BitCast;
2533 
2534   if (!IsCStyleOrFunctionalCast &&
2535       Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2536       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2537     DiagRuntimeBehavior(From->getExprLoc(), From,
2538                         PDiag(diag::warn_impcast_bool_to_null_pointer)
2539                           << ToType << From->getSourceRange());
2540 
2541   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2542     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2543       QualType FromPointeeType = FromPtrType->getPointeeType(),
2544                ToPointeeType   = ToPtrType->getPointeeType();
2545 
2546       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2547           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2548         // We must have a derived-to-base conversion. Check an
2549         // ambiguous or inaccessible conversion.
2550         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2551                                          From->getExprLoc(),
2552                                          From->getSourceRange(), &BasePath,
2553                                          IgnoreBaseAccess))
2554           return true;
2555 
2556         // The conversion was successful.
2557         Kind = CK_DerivedToBase;
2558       }
2559     }
2560   } else if (const ObjCObjectPointerType *ToPtrType =
2561                ToType->getAs<ObjCObjectPointerType>()) {
2562     if (const ObjCObjectPointerType *FromPtrType =
2563           FromType->getAs<ObjCObjectPointerType>()) {
2564       // Objective-C++ conversions are always okay.
2565       // FIXME: We should have a different class of conversions for the
2566       // Objective-C++ implicit conversions.
2567       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2568         return false;
2569     } else if (FromType->isBlockPointerType()) {
2570       Kind = CK_BlockPointerToObjCPointerCast;
2571     } else {
2572       Kind = CK_CPointerToObjCPointerCast;
2573     }
2574   } else if (ToType->isBlockPointerType()) {
2575     if (!FromType->isBlockPointerType())
2576       Kind = CK_AnyPointerToBlockPointerCast;
2577   }
2578 
2579   // We shouldn't fall into this case unless it's valid for other
2580   // reasons.
2581   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2582     Kind = CK_NullToPointer;
2583 
2584   return false;
2585 }
2586 
2587 /// IsMemberPointerConversion - Determines whether the conversion of the
2588 /// expression From, which has the (possibly adjusted) type FromType, can be
2589 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2590 /// If so, returns true and places the converted type (that might differ from
2591 /// ToType in its cv-qualifiers at some level) into ConvertedType.
IsMemberPointerConversion(Expr * From,QualType FromType,QualType ToType,bool InOverloadResolution,QualType & ConvertedType)2592 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2593                                      QualType ToType,
2594                                      bool InOverloadResolution,
2595                                      QualType &ConvertedType) {
2596   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2597   if (!ToTypePtr)
2598     return false;
2599 
2600   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2601   if (From->isNullPointerConstant(Context,
2602                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2603                                         : Expr::NPC_ValueDependentIsNull)) {
2604     ConvertedType = ToType;
2605     return true;
2606   }
2607 
2608   // Otherwise, both types have to be member pointers.
2609   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2610   if (!FromTypePtr)
2611     return false;
2612 
2613   // A pointer to member of B can be converted to a pointer to member of D,
2614   // where D is derived from B (C++ 4.11p2).
2615   QualType FromClass(FromTypePtr->getClass(), 0);
2616   QualType ToClass(ToTypePtr->getClass(), 0);
2617 
2618   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2619       !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2620       IsDerivedFrom(ToClass, FromClass)) {
2621     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2622                                                  ToClass.getTypePtr());
2623     return true;
2624   }
2625 
2626   return false;
2627 }
2628 
2629 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2630 /// expression From to the type ToType. This routine checks for ambiguous or
2631 /// virtual or inaccessible base-to-derived member pointer conversions
2632 /// for which IsMemberPointerConversion has already returned true. It returns
2633 /// true and produces a diagnostic if there was an error, or returns false
2634 /// otherwise.
CheckMemberPointerConversion(Expr * From,QualType ToType,CastKind & Kind,CXXCastPath & BasePath,bool IgnoreBaseAccess)2635 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2636                                         CastKind &Kind,
2637                                         CXXCastPath &BasePath,
2638                                         bool IgnoreBaseAccess) {
2639   QualType FromType = From->getType();
2640   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2641   if (!FromPtrType) {
2642     // This must be a null pointer to member pointer conversion
2643     assert(From->isNullPointerConstant(Context,
2644                                        Expr::NPC_ValueDependentIsNull) &&
2645            "Expr must be null pointer constant!");
2646     Kind = CK_NullToMemberPointer;
2647     return false;
2648   }
2649 
2650   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2651   assert(ToPtrType && "No member pointer cast has a target type "
2652                       "that is not a member pointer.");
2653 
2654   QualType FromClass = QualType(FromPtrType->getClass(), 0);
2655   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2656 
2657   // FIXME: What about dependent types?
2658   assert(FromClass->isRecordType() && "Pointer into non-class.");
2659   assert(ToClass->isRecordType() && "Pointer into non-class.");
2660 
2661   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2662                      /*DetectVirtual=*/true);
2663   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2664   assert(DerivationOkay &&
2665          "Should not have been called if derivation isn't OK.");
2666   (void)DerivationOkay;
2667 
2668   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2669                                   getUnqualifiedType())) {
2670     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2671     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2672       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2673     return true;
2674   }
2675 
2676   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2677     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2678       << FromClass << ToClass << QualType(VBase, 0)
2679       << From->getSourceRange();
2680     return true;
2681   }
2682 
2683   if (!IgnoreBaseAccess)
2684     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2685                          Paths.front(),
2686                          diag::err_downcast_from_inaccessible_base);
2687 
2688   // Must be a base to derived member conversion.
2689   BuildBasePathArray(Paths, BasePath);
2690   Kind = CK_BaseToDerivedMemberPointer;
2691   return false;
2692 }
2693 
2694 /// IsQualificationConversion - Determines whether the conversion from
2695 /// an rvalue of type FromType to ToType is a qualification conversion
2696 /// (C++ 4.4).
2697 ///
2698 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2699 /// when the qualification conversion involves a change in the Objective-C
2700 /// object lifetime.
2701 bool
IsQualificationConversion(QualType FromType,QualType ToType,bool CStyle,bool & ObjCLifetimeConversion)2702 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2703                                 bool CStyle, bool &ObjCLifetimeConversion) {
2704   FromType = Context.getCanonicalType(FromType);
2705   ToType = Context.getCanonicalType(ToType);
2706   ObjCLifetimeConversion = false;
2707 
2708   // If FromType and ToType are the same type, this is not a
2709   // qualification conversion.
2710   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2711     return false;
2712 
2713   // (C++ 4.4p4):
2714   //   A conversion can add cv-qualifiers at levels other than the first
2715   //   in multi-level pointers, subject to the following rules: [...]
2716   bool PreviousToQualsIncludeConst = true;
2717   bool UnwrappedAnyPointer = false;
2718   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2719     // Within each iteration of the loop, we check the qualifiers to
2720     // determine if this still looks like a qualification
2721     // conversion. Then, if all is well, we unwrap one more level of
2722     // pointers or pointers-to-members and do it all again
2723     // until there are no more pointers or pointers-to-members left to
2724     // unwrap.
2725     UnwrappedAnyPointer = true;
2726 
2727     Qualifiers FromQuals = FromType.getQualifiers();
2728     Qualifiers ToQuals = ToType.getQualifiers();
2729 
2730     // Objective-C ARC:
2731     //   Check Objective-C lifetime conversions.
2732     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2733         UnwrappedAnyPointer) {
2734       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2735         ObjCLifetimeConversion = true;
2736         FromQuals.removeObjCLifetime();
2737         ToQuals.removeObjCLifetime();
2738       } else {
2739         // Qualification conversions cannot cast between different
2740         // Objective-C lifetime qualifiers.
2741         return false;
2742       }
2743     }
2744 
2745     // Allow addition/removal of GC attributes but not changing GC attributes.
2746     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2747         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2748       FromQuals.removeObjCGCAttr();
2749       ToQuals.removeObjCGCAttr();
2750     }
2751 
2752     //   -- for every j > 0, if const is in cv 1,j then const is in cv
2753     //      2,j, and similarly for volatile.
2754     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2755       return false;
2756 
2757     //   -- if the cv 1,j and cv 2,j are different, then const is in
2758     //      every cv for 0 < k < j.
2759     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2760         && !PreviousToQualsIncludeConst)
2761       return false;
2762 
2763     // Keep track of whether all prior cv-qualifiers in the "to" type
2764     // include const.
2765     PreviousToQualsIncludeConst
2766       = PreviousToQualsIncludeConst && ToQuals.hasConst();
2767   }
2768 
2769   // We are left with FromType and ToType being the pointee types
2770   // after unwrapping the original FromType and ToType the same number
2771   // of types. If we unwrapped any pointers, and if FromType and
2772   // ToType have the same unqualified type (since we checked
2773   // qualifiers above), then this is a qualification conversion.
2774   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2775 }
2776 
2777 /// \brief - Determine whether this is a conversion from a scalar type to an
2778 /// atomic type.
2779 ///
2780 /// If successful, updates \c SCS's second and third steps in the conversion
2781 /// sequence to finish the conversion.
tryAtomicConversion(Sema & S,Expr * From,QualType ToType,bool InOverloadResolution,StandardConversionSequence & SCS,bool CStyle)2782 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2783                                 bool InOverloadResolution,
2784                                 StandardConversionSequence &SCS,
2785                                 bool CStyle) {
2786   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2787   if (!ToAtomic)
2788     return false;
2789 
2790   StandardConversionSequence InnerSCS;
2791   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2792                             InOverloadResolution, InnerSCS,
2793                             CStyle, /*AllowObjCWritebackConversion=*/false))
2794     return false;
2795 
2796   SCS.Second = InnerSCS.Second;
2797   SCS.setToType(1, InnerSCS.getToType(1));
2798   SCS.Third = InnerSCS.Third;
2799   SCS.QualificationIncludesObjCLifetime
2800     = InnerSCS.QualificationIncludesObjCLifetime;
2801   SCS.setToType(2, InnerSCS.getToType(2));
2802   return true;
2803 }
2804 
isFirstArgumentCompatibleWithType(ASTContext & Context,CXXConstructorDecl * Constructor,QualType Type)2805 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2806                                               CXXConstructorDecl *Constructor,
2807                                               QualType Type) {
2808   const FunctionProtoType *CtorType =
2809       Constructor->getType()->getAs<FunctionProtoType>();
2810   if (CtorType->getNumArgs() > 0) {
2811     QualType FirstArg = CtorType->getArgType(0);
2812     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2813       return true;
2814   }
2815   return false;
2816 }
2817 
2818 static OverloadingResult
IsInitializerListConstructorConversion(Sema & S,Expr * From,QualType ToType,CXXRecordDecl * To,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit)2819 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2820                                        CXXRecordDecl *To,
2821                                        UserDefinedConversionSequence &User,
2822                                        OverloadCandidateSet &CandidateSet,
2823                                        bool AllowExplicit) {
2824   DeclContext::lookup_iterator Con, ConEnd;
2825   for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2826        Con != ConEnd; ++Con) {
2827     NamedDecl *D = *Con;
2828     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2829 
2830     // Find the constructor (which may be a template).
2831     CXXConstructorDecl *Constructor = 0;
2832     FunctionTemplateDecl *ConstructorTmpl
2833       = dyn_cast<FunctionTemplateDecl>(D);
2834     if (ConstructorTmpl)
2835       Constructor
2836         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2837     else
2838       Constructor = cast<CXXConstructorDecl>(D);
2839 
2840     bool Usable = !Constructor->isInvalidDecl() &&
2841                   S.isInitListConstructor(Constructor) &&
2842                   (AllowExplicit || !Constructor->isExplicit());
2843     if (Usable) {
2844       // If the first argument is (a reference to) the target type,
2845       // suppress conversions.
2846       bool SuppressUserConversions =
2847           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2848       if (ConstructorTmpl)
2849         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2850                                        /*ExplicitArgs*/ 0,
2851                                        From, CandidateSet,
2852                                        SuppressUserConversions);
2853       else
2854         S.AddOverloadCandidate(Constructor, FoundDecl,
2855                                From, CandidateSet,
2856                                SuppressUserConversions);
2857     }
2858   }
2859 
2860   bool HadMultipleCandidates = (CandidateSet.size() > 1);
2861 
2862   OverloadCandidateSet::iterator Best;
2863   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2864   case OR_Success: {
2865     // Record the standard conversion we used and the conversion function.
2866     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2867     S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2868 
2869     QualType ThisType = Constructor->getThisType(S.Context);
2870     // Initializer lists don't have conversions as such.
2871     User.Before.setAsIdentityConversion();
2872     User.HadMultipleCandidates = HadMultipleCandidates;
2873     User.ConversionFunction = Constructor;
2874     User.FoundConversionFunction = Best->FoundDecl;
2875     User.After.setAsIdentityConversion();
2876     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2877     User.After.setAllToTypes(ToType);
2878     return OR_Success;
2879   }
2880 
2881   case OR_No_Viable_Function:
2882     return OR_No_Viable_Function;
2883   case OR_Deleted:
2884     return OR_Deleted;
2885   case OR_Ambiguous:
2886     return OR_Ambiguous;
2887   }
2888 
2889   llvm_unreachable("Invalid OverloadResult!");
2890 }
2891 
2892 /// Determines whether there is a user-defined conversion sequence
2893 /// (C++ [over.ics.user]) that converts expression From to the type
2894 /// ToType. If such a conversion exists, User will contain the
2895 /// user-defined conversion sequence that performs such a conversion
2896 /// and this routine will return true. Otherwise, this routine returns
2897 /// false and User is unspecified.
2898 ///
2899 /// \param AllowExplicit  true if the conversion should consider C++0x
2900 /// "explicit" conversion functions as well as non-explicit conversion
2901 /// functions (C++0x [class.conv.fct]p2).
2902 static OverloadingResult
IsUserDefinedConversion(Sema & S,Expr * From,QualType ToType,UserDefinedConversionSequence & User,OverloadCandidateSet & CandidateSet,bool AllowExplicit)2903 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2904                         UserDefinedConversionSequence &User,
2905                         OverloadCandidateSet &CandidateSet,
2906                         bool AllowExplicit) {
2907   // Whether we will only visit constructors.
2908   bool ConstructorsOnly = false;
2909 
2910   // If the type we are conversion to is a class type, enumerate its
2911   // constructors.
2912   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2913     // C++ [over.match.ctor]p1:
2914     //   When objects of class type are direct-initialized (8.5), or
2915     //   copy-initialized from an expression of the same or a
2916     //   derived class type (8.5), overload resolution selects the
2917     //   constructor. [...] For copy-initialization, the candidate
2918     //   functions are all the converting constructors (12.3.1) of
2919     //   that class. The argument list is the expression-list within
2920     //   the parentheses of the initializer.
2921     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2922         (From->getType()->getAs<RecordType>() &&
2923          S.IsDerivedFrom(From->getType(), ToType)))
2924       ConstructorsOnly = true;
2925 
2926     S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2927     // RequireCompleteType may have returned true due to some invalid decl
2928     // during template instantiation, but ToType may be complete enough now
2929     // to try to recover.
2930     if (ToType->isIncompleteType()) {
2931       // We're not going to find any constructors.
2932     } else if (CXXRecordDecl *ToRecordDecl
2933                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
2934 
2935       Expr **Args = &From;
2936       unsigned NumArgs = 1;
2937       bool ListInitializing = false;
2938       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2939         // But first, see if there is an init-list-contructor that will work.
2940         OverloadingResult Result = IsInitializerListConstructorConversion(
2941             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2942         if (Result != OR_No_Viable_Function)
2943           return Result;
2944         // Never mind.
2945         CandidateSet.clear();
2946 
2947         // If we're list-initializing, we pass the individual elements as
2948         // arguments, not the entire list.
2949         Args = InitList->getInits();
2950         NumArgs = InitList->getNumInits();
2951         ListInitializing = true;
2952       }
2953 
2954       DeclContext::lookup_iterator Con, ConEnd;
2955       for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
2956            Con != ConEnd; ++Con) {
2957         NamedDecl *D = *Con;
2958         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2959 
2960         // Find the constructor (which may be a template).
2961         CXXConstructorDecl *Constructor = 0;
2962         FunctionTemplateDecl *ConstructorTmpl
2963           = dyn_cast<FunctionTemplateDecl>(D);
2964         if (ConstructorTmpl)
2965           Constructor
2966             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2967         else
2968           Constructor = cast<CXXConstructorDecl>(D);
2969 
2970         bool Usable = !Constructor->isInvalidDecl();
2971         if (ListInitializing)
2972           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2973         else
2974           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2975         if (Usable) {
2976           bool SuppressUserConversions = !ConstructorsOnly;
2977           if (SuppressUserConversions && ListInitializing) {
2978             SuppressUserConversions = false;
2979             if (NumArgs == 1) {
2980               // If the first argument is (a reference to) the target type,
2981               // suppress conversions.
2982               SuppressUserConversions = isFirstArgumentCompatibleWithType(
2983                                                 S.Context, Constructor, ToType);
2984             }
2985           }
2986           if (ConstructorTmpl)
2987             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2988                                            /*ExplicitArgs*/ 0,
2989                                            llvm::makeArrayRef(Args, NumArgs),
2990                                            CandidateSet, SuppressUserConversions);
2991           else
2992             // Allow one user-defined conversion when user specifies a
2993             // From->ToType conversion via an static cast (c-style, etc).
2994             S.AddOverloadCandidate(Constructor, FoundDecl,
2995                                    llvm::makeArrayRef(Args, NumArgs),
2996                                    CandidateSet, SuppressUserConversions);
2997         }
2998       }
2999     }
3000   }
3001 
3002   // Enumerate conversion functions, if we're allowed to.
3003   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3004   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
3005                                    S.PDiag(0) << From->getSourceRange())) {
3006     // No conversion functions from incomplete types.
3007   } else if (const RecordType *FromRecordType
3008                                    = From->getType()->getAs<RecordType>()) {
3009     if (CXXRecordDecl *FromRecordDecl
3010          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3011       // Add all of the conversion functions as candidates.
3012       const UnresolvedSetImpl *Conversions
3013         = FromRecordDecl->getVisibleConversionFunctions();
3014       for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3015              E = Conversions->end(); I != E; ++I) {
3016         DeclAccessPair FoundDecl = I.getPair();
3017         NamedDecl *D = FoundDecl.getDecl();
3018         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3019         if (isa<UsingShadowDecl>(D))
3020           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3021 
3022         CXXConversionDecl *Conv;
3023         FunctionTemplateDecl *ConvTemplate;
3024         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3025           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3026         else
3027           Conv = cast<CXXConversionDecl>(D);
3028 
3029         if (AllowExplicit || !Conv->isExplicit()) {
3030           if (ConvTemplate)
3031             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3032                                              ActingContext, From, ToType,
3033                                              CandidateSet);
3034           else
3035             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3036                                      From, ToType, CandidateSet);
3037         }
3038       }
3039     }
3040   }
3041 
3042   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3043 
3044   OverloadCandidateSet::iterator Best;
3045   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3046   case OR_Success:
3047     // Record the standard conversion we used and the conversion function.
3048     if (CXXConstructorDecl *Constructor
3049           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3050       S.MarkFunctionReferenced(From->getLocStart(), Constructor);
3051 
3052       // C++ [over.ics.user]p1:
3053       //   If the user-defined conversion is specified by a
3054       //   constructor (12.3.1), the initial standard conversion
3055       //   sequence converts the source type to the type required by
3056       //   the argument of the constructor.
3057       //
3058       QualType ThisType = Constructor->getThisType(S.Context);
3059       if (isa<InitListExpr>(From)) {
3060         // Initializer lists don't have conversions as such.
3061         User.Before.setAsIdentityConversion();
3062       } else {
3063         if (Best->Conversions[0].isEllipsis())
3064           User.EllipsisConversion = true;
3065         else {
3066           User.Before = Best->Conversions[0].Standard;
3067           User.EllipsisConversion = false;
3068         }
3069       }
3070       User.HadMultipleCandidates = HadMultipleCandidates;
3071       User.ConversionFunction = Constructor;
3072       User.FoundConversionFunction = Best->FoundDecl;
3073       User.After.setAsIdentityConversion();
3074       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3075       User.After.setAllToTypes(ToType);
3076       return OR_Success;
3077     }
3078     if (CXXConversionDecl *Conversion
3079                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3080       S.MarkFunctionReferenced(From->getLocStart(), Conversion);
3081 
3082       // C++ [over.ics.user]p1:
3083       //
3084       //   [...] If the user-defined conversion is specified by a
3085       //   conversion function (12.3.2), the initial standard
3086       //   conversion sequence converts the source type to the
3087       //   implicit object parameter of the conversion function.
3088       User.Before = Best->Conversions[0].Standard;
3089       User.HadMultipleCandidates = HadMultipleCandidates;
3090       User.ConversionFunction = Conversion;
3091       User.FoundConversionFunction = Best->FoundDecl;
3092       User.EllipsisConversion = false;
3093 
3094       // C++ [over.ics.user]p2:
3095       //   The second standard conversion sequence converts the
3096       //   result of the user-defined conversion to the target type
3097       //   for the sequence. Since an implicit conversion sequence
3098       //   is an initialization, the special rules for
3099       //   initialization by user-defined conversion apply when
3100       //   selecting the best user-defined conversion for a
3101       //   user-defined conversion sequence (see 13.3.3 and
3102       //   13.3.3.1).
3103       User.After = Best->FinalConversion;
3104       return OR_Success;
3105     }
3106     llvm_unreachable("Not a constructor or conversion function?");
3107 
3108   case OR_No_Viable_Function:
3109     return OR_No_Viable_Function;
3110   case OR_Deleted:
3111     // No conversion here! We're done.
3112     return OR_Deleted;
3113 
3114   case OR_Ambiguous:
3115     return OR_Ambiguous;
3116   }
3117 
3118   llvm_unreachable("Invalid OverloadResult!");
3119 }
3120 
3121 bool
DiagnoseMultipleUserDefinedConversion(Expr * From,QualType ToType)3122 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3123   ImplicitConversionSequence ICS;
3124   OverloadCandidateSet CandidateSet(From->getExprLoc());
3125   OverloadingResult OvResult =
3126     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3127                             CandidateSet, false);
3128   if (OvResult == OR_Ambiguous)
3129     Diag(From->getLocStart(),
3130          diag::err_typecheck_ambiguous_condition)
3131           << From->getType() << ToType << From->getSourceRange();
3132   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
3133     Diag(From->getLocStart(),
3134          diag::err_typecheck_nonviable_condition)
3135     << From->getType() << ToType << From->getSourceRange();
3136   else
3137     return false;
3138   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3139   return true;
3140 }
3141 
3142 /// \brief Compare the user-defined conversion functions or constructors
3143 /// of two user-defined conversion sequences to determine whether any ordering
3144 /// is possible.
3145 static ImplicitConversionSequence::CompareKind
compareConversionFunctions(Sema & S,FunctionDecl * Function1,FunctionDecl * Function2)3146 compareConversionFunctions(Sema &S,
3147                            FunctionDecl *Function1,
3148                            FunctionDecl *Function2) {
3149   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
3150     return ImplicitConversionSequence::Indistinguishable;
3151 
3152   // Objective-C++:
3153   //   If both conversion functions are implicitly-declared conversions from
3154   //   a lambda closure type to a function pointer and a block pointer,
3155   //   respectively, always prefer the conversion to a function pointer,
3156   //   because the function pointer is more lightweight and is more likely
3157   //   to keep code working.
3158   CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3159   if (!Conv1)
3160     return ImplicitConversionSequence::Indistinguishable;
3161 
3162   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3163   if (!Conv2)
3164     return ImplicitConversionSequence::Indistinguishable;
3165 
3166   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3167     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3168     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3169     if (Block1 != Block2)
3170       return Block1? ImplicitConversionSequence::Worse
3171                    : ImplicitConversionSequence::Better;
3172   }
3173 
3174   return ImplicitConversionSequence::Indistinguishable;
3175 }
3176 
3177 /// CompareImplicitConversionSequences - Compare two implicit
3178 /// conversion sequences to determine whether one is better than the
3179 /// other or if they are indistinguishable (C++ 13.3.3.2).
3180 static ImplicitConversionSequence::CompareKind
CompareImplicitConversionSequences(Sema & S,const ImplicitConversionSequence & ICS1,const ImplicitConversionSequence & ICS2)3181 CompareImplicitConversionSequences(Sema &S,
3182                                    const ImplicitConversionSequence& ICS1,
3183                                    const ImplicitConversionSequence& ICS2)
3184 {
3185   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3186   // conversion sequences (as defined in 13.3.3.1)
3187   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3188   //      conversion sequence than a user-defined conversion sequence or
3189   //      an ellipsis conversion sequence, and
3190   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3191   //      conversion sequence than an ellipsis conversion sequence
3192   //      (13.3.3.1.3).
3193   //
3194   // C++0x [over.best.ics]p10:
3195   //   For the purpose of ranking implicit conversion sequences as
3196   //   described in 13.3.3.2, the ambiguous conversion sequence is
3197   //   treated as a user-defined sequence that is indistinguishable
3198   //   from any other user-defined conversion sequence.
3199   if (ICS1.getKindRank() < ICS2.getKindRank())
3200     return ImplicitConversionSequence::Better;
3201   if (ICS2.getKindRank() < ICS1.getKindRank())
3202     return ImplicitConversionSequence::Worse;
3203 
3204   // The following checks require both conversion sequences to be of
3205   // the same kind.
3206   if (ICS1.getKind() != ICS2.getKind())
3207     return ImplicitConversionSequence::Indistinguishable;
3208 
3209   ImplicitConversionSequence::CompareKind Result =
3210       ImplicitConversionSequence::Indistinguishable;
3211 
3212   // Two implicit conversion sequences of the same form are
3213   // indistinguishable conversion sequences unless one of the
3214   // following rules apply: (C++ 13.3.3.2p3):
3215   if (ICS1.isStandard())
3216     Result = CompareStandardConversionSequences(S,
3217                                                 ICS1.Standard, ICS2.Standard);
3218   else if (ICS1.isUserDefined()) {
3219     // User-defined conversion sequence U1 is a better conversion
3220     // sequence than another user-defined conversion sequence U2 if
3221     // they contain the same user-defined conversion function or
3222     // constructor and if the second standard conversion sequence of
3223     // U1 is better than the second standard conversion sequence of
3224     // U2 (C++ 13.3.3.2p3).
3225     if (ICS1.UserDefined.ConversionFunction ==
3226           ICS2.UserDefined.ConversionFunction)
3227       Result = CompareStandardConversionSequences(S,
3228                                                   ICS1.UserDefined.After,
3229                                                   ICS2.UserDefined.After);
3230     else
3231       Result = compareConversionFunctions(S,
3232                                           ICS1.UserDefined.ConversionFunction,
3233                                           ICS2.UserDefined.ConversionFunction);
3234   }
3235 
3236   // List-initialization sequence L1 is a better conversion sequence than
3237   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3238   // for some X and L2 does not.
3239   if (Result == ImplicitConversionSequence::Indistinguishable &&
3240       !ICS1.isBad() &&
3241       ICS1.isListInitializationSequence() &&
3242       ICS2.isListInitializationSequence()) {
3243     if (ICS1.isStdInitializerListElement() &&
3244         !ICS2.isStdInitializerListElement())
3245       return ImplicitConversionSequence::Better;
3246     if (!ICS1.isStdInitializerListElement() &&
3247         ICS2.isStdInitializerListElement())
3248       return ImplicitConversionSequence::Worse;
3249   }
3250 
3251   return Result;
3252 }
3253 
hasSimilarType(ASTContext & Context,QualType T1,QualType T2)3254 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3255   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3256     Qualifiers Quals;
3257     T1 = Context.getUnqualifiedArrayType(T1, Quals);
3258     T2 = Context.getUnqualifiedArrayType(T2, Quals);
3259   }
3260 
3261   return Context.hasSameUnqualifiedType(T1, T2);
3262 }
3263 
3264 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3265 // determine if one is a proper subset of the other.
3266 static ImplicitConversionSequence::CompareKind
compareStandardConversionSubsets(ASTContext & Context,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3267 compareStandardConversionSubsets(ASTContext &Context,
3268                                  const StandardConversionSequence& SCS1,
3269                                  const StandardConversionSequence& SCS2) {
3270   ImplicitConversionSequence::CompareKind Result
3271     = ImplicitConversionSequence::Indistinguishable;
3272 
3273   // the identity conversion sequence is considered to be a subsequence of
3274   // any non-identity conversion sequence
3275   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3276     return ImplicitConversionSequence::Better;
3277   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3278     return ImplicitConversionSequence::Worse;
3279 
3280   if (SCS1.Second != SCS2.Second) {
3281     if (SCS1.Second == ICK_Identity)
3282       Result = ImplicitConversionSequence::Better;
3283     else if (SCS2.Second == ICK_Identity)
3284       Result = ImplicitConversionSequence::Worse;
3285     else
3286       return ImplicitConversionSequence::Indistinguishable;
3287   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3288     return ImplicitConversionSequence::Indistinguishable;
3289 
3290   if (SCS1.Third == SCS2.Third) {
3291     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3292                              : ImplicitConversionSequence::Indistinguishable;
3293   }
3294 
3295   if (SCS1.Third == ICK_Identity)
3296     return Result == ImplicitConversionSequence::Worse
3297              ? ImplicitConversionSequence::Indistinguishable
3298              : ImplicitConversionSequence::Better;
3299 
3300   if (SCS2.Third == ICK_Identity)
3301     return Result == ImplicitConversionSequence::Better
3302              ? ImplicitConversionSequence::Indistinguishable
3303              : ImplicitConversionSequence::Worse;
3304 
3305   return ImplicitConversionSequence::Indistinguishable;
3306 }
3307 
3308 /// \brief Determine whether one of the given reference bindings is better
3309 /// than the other based on what kind of bindings they are.
isBetterReferenceBindingKind(const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3310 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3311                                        const StandardConversionSequence &SCS2) {
3312   // C++0x [over.ics.rank]p3b4:
3313   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3314   //      implicit object parameter of a non-static member function declared
3315   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3316   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3317   //      lvalue reference to a function lvalue and S2 binds an rvalue
3318   //      reference*.
3319   //
3320   // FIXME: Rvalue references. We're going rogue with the above edits,
3321   // because the semantics in the current C++0x working paper (N3225 at the
3322   // time of this writing) break the standard definition of std::forward
3323   // and std::reference_wrapper when dealing with references to functions.
3324   // Proposed wording changes submitted to CWG for consideration.
3325   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3326       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3327     return false;
3328 
3329   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3330           SCS2.IsLvalueReference) ||
3331          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3332           !SCS2.IsLvalueReference);
3333 }
3334 
3335 /// CompareStandardConversionSequences - Compare two standard
3336 /// conversion sequences to determine whether one is better than the
3337 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3338 static ImplicitConversionSequence::CompareKind
CompareStandardConversionSequences(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3339 CompareStandardConversionSequences(Sema &S,
3340                                    const StandardConversionSequence& SCS1,
3341                                    const StandardConversionSequence& SCS2)
3342 {
3343   // Standard conversion sequence S1 is a better conversion sequence
3344   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3345 
3346   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3347   //     sequences in the canonical form defined by 13.3.3.1.1,
3348   //     excluding any Lvalue Transformation; the identity conversion
3349   //     sequence is considered to be a subsequence of any
3350   //     non-identity conversion sequence) or, if not that,
3351   if (ImplicitConversionSequence::CompareKind CK
3352         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3353     return CK;
3354 
3355   //  -- the rank of S1 is better than the rank of S2 (by the rules
3356   //     defined below), or, if not that,
3357   ImplicitConversionRank Rank1 = SCS1.getRank();
3358   ImplicitConversionRank Rank2 = SCS2.getRank();
3359   if (Rank1 < Rank2)
3360     return ImplicitConversionSequence::Better;
3361   else if (Rank2 < Rank1)
3362     return ImplicitConversionSequence::Worse;
3363 
3364   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3365   // are indistinguishable unless one of the following rules
3366   // applies:
3367 
3368   //   A conversion that is not a conversion of a pointer, or
3369   //   pointer to member, to bool is better than another conversion
3370   //   that is such a conversion.
3371   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3372     return SCS2.isPointerConversionToBool()
3373              ? ImplicitConversionSequence::Better
3374              : ImplicitConversionSequence::Worse;
3375 
3376   // C++ [over.ics.rank]p4b2:
3377   //
3378   //   If class B is derived directly or indirectly from class A,
3379   //   conversion of B* to A* is better than conversion of B* to
3380   //   void*, and conversion of A* to void* is better than conversion
3381   //   of B* to void*.
3382   bool SCS1ConvertsToVoid
3383     = SCS1.isPointerConversionToVoidPointer(S.Context);
3384   bool SCS2ConvertsToVoid
3385     = SCS2.isPointerConversionToVoidPointer(S.Context);
3386   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3387     // Exactly one of the conversion sequences is a conversion to
3388     // a void pointer; it's the worse conversion.
3389     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3390                               : ImplicitConversionSequence::Worse;
3391   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3392     // Neither conversion sequence converts to a void pointer; compare
3393     // their derived-to-base conversions.
3394     if (ImplicitConversionSequence::CompareKind DerivedCK
3395           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3396       return DerivedCK;
3397   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3398              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3399     // Both conversion sequences are conversions to void
3400     // pointers. Compare the source types to determine if there's an
3401     // inheritance relationship in their sources.
3402     QualType FromType1 = SCS1.getFromType();
3403     QualType FromType2 = SCS2.getFromType();
3404 
3405     // Adjust the types we're converting from via the array-to-pointer
3406     // conversion, if we need to.
3407     if (SCS1.First == ICK_Array_To_Pointer)
3408       FromType1 = S.Context.getArrayDecayedType(FromType1);
3409     if (SCS2.First == ICK_Array_To_Pointer)
3410       FromType2 = S.Context.getArrayDecayedType(FromType2);
3411 
3412     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3413     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3414 
3415     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3416       return ImplicitConversionSequence::Better;
3417     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3418       return ImplicitConversionSequence::Worse;
3419 
3420     // Objective-C++: If one interface is more specific than the
3421     // other, it is the better one.
3422     const ObjCObjectPointerType* FromObjCPtr1
3423       = FromType1->getAs<ObjCObjectPointerType>();
3424     const ObjCObjectPointerType* FromObjCPtr2
3425       = FromType2->getAs<ObjCObjectPointerType>();
3426     if (FromObjCPtr1 && FromObjCPtr2) {
3427       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3428                                                           FromObjCPtr2);
3429       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3430                                                            FromObjCPtr1);
3431       if (AssignLeft != AssignRight) {
3432         return AssignLeft? ImplicitConversionSequence::Better
3433                          : ImplicitConversionSequence::Worse;
3434       }
3435     }
3436   }
3437 
3438   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3439   // bullet 3).
3440   if (ImplicitConversionSequence::CompareKind QualCK
3441         = CompareQualificationConversions(S, SCS1, SCS2))
3442     return QualCK;
3443 
3444   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3445     // Check for a better reference binding based on the kind of bindings.
3446     if (isBetterReferenceBindingKind(SCS1, SCS2))
3447       return ImplicitConversionSequence::Better;
3448     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3449       return ImplicitConversionSequence::Worse;
3450 
3451     // C++ [over.ics.rank]p3b4:
3452     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3453     //      which the references refer are the same type except for
3454     //      top-level cv-qualifiers, and the type to which the reference
3455     //      initialized by S2 refers is more cv-qualified than the type
3456     //      to which the reference initialized by S1 refers.
3457     QualType T1 = SCS1.getToType(2);
3458     QualType T2 = SCS2.getToType(2);
3459     T1 = S.Context.getCanonicalType(T1);
3460     T2 = S.Context.getCanonicalType(T2);
3461     Qualifiers T1Quals, T2Quals;
3462     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3463     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3464     if (UnqualT1 == UnqualT2) {
3465       // Objective-C++ ARC: If the references refer to objects with different
3466       // lifetimes, prefer bindings that don't change lifetime.
3467       if (SCS1.ObjCLifetimeConversionBinding !=
3468                                           SCS2.ObjCLifetimeConversionBinding) {
3469         return SCS1.ObjCLifetimeConversionBinding
3470                                            ? ImplicitConversionSequence::Worse
3471                                            : ImplicitConversionSequence::Better;
3472       }
3473 
3474       // If the type is an array type, promote the element qualifiers to the
3475       // type for comparison.
3476       if (isa<ArrayType>(T1) && T1Quals)
3477         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3478       if (isa<ArrayType>(T2) && T2Quals)
3479         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3480       if (T2.isMoreQualifiedThan(T1))
3481         return ImplicitConversionSequence::Better;
3482       else if (T1.isMoreQualifiedThan(T2))
3483         return ImplicitConversionSequence::Worse;
3484     }
3485   }
3486 
3487   // In Microsoft mode, prefer an integral conversion to a
3488   // floating-to-integral conversion if the integral conversion
3489   // is between types of the same size.
3490   // For example:
3491   // void f(float);
3492   // void f(int);
3493   // int main {
3494   //    long a;
3495   //    f(a);
3496   // }
3497   // Here, MSVC will call f(int) instead of generating a compile error
3498   // as clang will do in standard mode.
3499   if (S.getLangOpts().MicrosoftMode &&
3500       SCS1.Second == ICK_Integral_Conversion &&
3501       SCS2.Second == ICK_Floating_Integral &&
3502       S.Context.getTypeSize(SCS1.getFromType()) ==
3503       S.Context.getTypeSize(SCS1.getToType(2)))
3504     return ImplicitConversionSequence::Better;
3505 
3506   return ImplicitConversionSequence::Indistinguishable;
3507 }
3508 
3509 /// CompareQualificationConversions - Compares two standard conversion
3510 /// sequences to determine whether they can be ranked based on their
3511 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3512 ImplicitConversionSequence::CompareKind
CompareQualificationConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3513 CompareQualificationConversions(Sema &S,
3514                                 const StandardConversionSequence& SCS1,
3515                                 const StandardConversionSequence& SCS2) {
3516   // C++ 13.3.3.2p3:
3517   //  -- S1 and S2 differ only in their qualification conversion and
3518   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
3519   //     cv-qualification signature of type T1 is a proper subset of
3520   //     the cv-qualification signature of type T2, and S1 is not the
3521   //     deprecated string literal array-to-pointer conversion (4.2).
3522   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3523       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3524     return ImplicitConversionSequence::Indistinguishable;
3525 
3526   // FIXME: the example in the standard doesn't use a qualification
3527   // conversion (!)
3528   QualType T1 = SCS1.getToType(2);
3529   QualType T2 = SCS2.getToType(2);
3530   T1 = S.Context.getCanonicalType(T1);
3531   T2 = S.Context.getCanonicalType(T2);
3532   Qualifiers T1Quals, T2Quals;
3533   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3534   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3535 
3536   // If the types are the same, we won't learn anything by unwrapped
3537   // them.
3538   if (UnqualT1 == UnqualT2)
3539     return ImplicitConversionSequence::Indistinguishable;
3540 
3541   // If the type is an array type, promote the element qualifiers to the type
3542   // for comparison.
3543   if (isa<ArrayType>(T1) && T1Quals)
3544     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3545   if (isa<ArrayType>(T2) && T2Quals)
3546     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3547 
3548   ImplicitConversionSequence::CompareKind Result
3549     = ImplicitConversionSequence::Indistinguishable;
3550 
3551   // Objective-C++ ARC:
3552   //   Prefer qualification conversions not involving a change in lifetime
3553   //   to qualification conversions that do not change lifetime.
3554   if (SCS1.QualificationIncludesObjCLifetime !=
3555                                       SCS2.QualificationIncludesObjCLifetime) {
3556     Result = SCS1.QualificationIncludesObjCLifetime
3557                ? ImplicitConversionSequence::Worse
3558                : ImplicitConversionSequence::Better;
3559   }
3560 
3561   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3562     // Within each iteration of the loop, we check the qualifiers to
3563     // determine if this still looks like a qualification
3564     // conversion. Then, if all is well, we unwrap one more level of
3565     // pointers or pointers-to-members and do it all again
3566     // until there are no more pointers or pointers-to-members left
3567     // to unwrap. This essentially mimics what
3568     // IsQualificationConversion does, but here we're checking for a
3569     // strict subset of qualifiers.
3570     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3571       // The qualifiers are the same, so this doesn't tell us anything
3572       // about how the sequences rank.
3573       ;
3574     else if (T2.isMoreQualifiedThan(T1)) {
3575       // T1 has fewer qualifiers, so it could be the better sequence.
3576       if (Result == ImplicitConversionSequence::Worse)
3577         // Neither has qualifiers that are a subset of the other's
3578         // qualifiers.
3579         return ImplicitConversionSequence::Indistinguishable;
3580 
3581       Result = ImplicitConversionSequence::Better;
3582     } else if (T1.isMoreQualifiedThan(T2)) {
3583       // T2 has fewer qualifiers, so it could be the better sequence.
3584       if (Result == ImplicitConversionSequence::Better)
3585         // Neither has qualifiers that are a subset of the other's
3586         // qualifiers.
3587         return ImplicitConversionSequence::Indistinguishable;
3588 
3589       Result = ImplicitConversionSequence::Worse;
3590     } else {
3591       // Qualifiers are disjoint.
3592       return ImplicitConversionSequence::Indistinguishable;
3593     }
3594 
3595     // If the types after this point are equivalent, we're done.
3596     if (S.Context.hasSameUnqualifiedType(T1, T2))
3597       break;
3598   }
3599 
3600   // Check that the winning standard conversion sequence isn't using
3601   // the deprecated string literal array to pointer conversion.
3602   switch (Result) {
3603   case ImplicitConversionSequence::Better:
3604     if (SCS1.DeprecatedStringLiteralToCharPtr)
3605       Result = ImplicitConversionSequence::Indistinguishable;
3606     break;
3607 
3608   case ImplicitConversionSequence::Indistinguishable:
3609     break;
3610 
3611   case ImplicitConversionSequence::Worse:
3612     if (SCS2.DeprecatedStringLiteralToCharPtr)
3613       Result = ImplicitConversionSequence::Indistinguishable;
3614     break;
3615   }
3616 
3617   return Result;
3618 }
3619 
3620 /// CompareDerivedToBaseConversions - Compares two standard conversion
3621 /// sequences to determine whether they can be ranked based on their
3622 /// various kinds of derived-to-base conversions (C++
3623 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
3624 /// conversions between Objective-C interface types.
3625 ImplicitConversionSequence::CompareKind
CompareDerivedToBaseConversions(Sema & S,const StandardConversionSequence & SCS1,const StandardConversionSequence & SCS2)3626 CompareDerivedToBaseConversions(Sema &S,
3627                                 const StandardConversionSequence& SCS1,
3628                                 const StandardConversionSequence& SCS2) {
3629   QualType FromType1 = SCS1.getFromType();
3630   QualType ToType1 = SCS1.getToType(1);
3631   QualType FromType2 = SCS2.getFromType();
3632   QualType ToType2 = SCS2.getToType(1);
3633 
3634   // Adjust the types we're converting from via the array-to-pointer
3635   // conversion, if we need to.
3636   if (SCS1.First == ICK_Array_To_Pointer)
3637     FromType1 = S.Context.getArrayDecayedType(FromType1);
3638   if (SCS2.First == ICK_Array_To_Pointer)
3639     FromType2 = S.Context.getArrayDecayedType(FromType2);
3640 
3641   // Canonicalize all of the types.
3642   FromType1 = S.Context.getCanonicalType(FromType1);
3643   ToType1 = S.Context.getCanonicalType(ToType1);
3644   FromType2 = S.Context.getCanonicalType(FromType2);
3645   ToType2 = S.Context.getCanonicalType(ToType2);
3646 
3647   // C++ [over.ics.rank]p4b3:
3648   //
3649   //   If class B is derived directly or indirectly from class A and
3650   //   class C is derived directly or indirectly from B,
3651   //
3652   // Compare based on pointer conversions.
3653   if (SCS1.Second == ICK_Pointer_Conversion &&
3654       SCS2.Second == ICK_Pointer_Conversion &&
3655       /*FIXME: Remove if Objective-C id conversions get their own rank*/
3656       FromType1->isPointerType() && FromType2->isPointerType() &&
3657       ToType1->isPointerType() && ToType2->isPointerType()) {
3658     QualType FromPointee1
3659       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3660     QualType ToPointee1
3661       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3662     QualType FromPointee2
3663       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3664     QualType ToPointee2
3665       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3666 
3667     //   -- conversion of C* to B* is better than conversion of C* to A*,
3668     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3669       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3670         return ImplicitConversionSequence::Better;
3671       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3672         return ImplicitConversionSequence::Worse;
3673     }
3674 
3675     //   -- conversion of B* to A* is better than conversion of C* to A*,
3676     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3677       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3678         return ImplicitConversionSequence::Better;
3679       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3680         return ImplicitConversionSequence::Worse;
3681     }
3682   } else if (SCS1.Second == ICK_Pointer_Conversion &&
3683              SCS2.Second == ICK_Pointer_Conversion) {
3684     const ObjCObjectPointerType *FromPtr1
3685       = FromType1->getAs<ObjCObjectPointerType>();
3686     const ObjCObjectPointerType *FromPtr2
3687       = FromType2->getAs<ObjCObjectPointerType>();
3688     const ObjCObjectPointerType *ToPtr1
3689       = ToType1->getAs<ObjCObjectPointerType>();
3690     const ObjCObjectPointerType *ToPtr2
3691       = ToType2->getAs<ObjCObjectPointerType>();
3692 
3693     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3694       // Apply the same conversion ranking rules for Objective-C pointer types
3695       // that we do for C++ pointers to class types. However, we employ the
3696       // Objective-C pseudo-subtyping relationship used for assignment of
3697       // Objective-C pointer types.
3698       bool FromAssignLeft
3699         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3700       bool FromAssignRight
3701         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3702       bool ToAssignLeft
3703         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3704       bool ToAssignRight
3705         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3706 
3707       // A conversion to an a non-id object pointer type or qualified 'id'
3708       // type is better than a conversion to 'id'.
3709       if (ToPtr1->isObjCIdType() &&
3710           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3711         return ImplicitConversionSequence::Worse;
3712       if (ToPtr2->isObjCIdType() &&
3713           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3714         return ImplicitConversionSequence::Better;
3715 
3716       // A conversion to a non-id object pointer type is better than a
3717       // conversion to a qualified 'id' type
3718       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3719         return ImplicitConversionSequence::Worse;
3720       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3721         return ImplicitConversionSequence::Better;
3722 
3723       // A conversion to an a non-Class object pointer type or qualified 'Class'
3724       // type is better than a conversion to 'Class'.
3725       if (ToPtr1->isObjCClassType() &&
3726           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3727         return ImplicitConversionSequence::Worse;
3728       if (ToPtr2->isObjCClassType() &&
3729           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3730         return ImplicitConversionSequence::Better;
3731 
3732       // A conversion to a non-Class object pointer type is better than a
3733       // conversion to a qualified 'Class' type.
3734       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3735         return ImplicitConversionSequence::Worse;
3736       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3737         return ImplicitConversionSequence::Better;
3738 
3739       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3740       if (S.Context.hasSameType(FromType1, FromType2) &&
3741           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3742           (ToAssignLeft != ToAssignRight))
3743         return ToAssignLeft? ImplicitConversionSequence::Worse
3744                            : ImplicitConversionSequence::Better;
3745 
3746       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3747       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3748           (FromAssignLeft != FromAssignRight))
3749         return FromAssignLeft? ImplicitConversionSequence::Better
3750         : ImplicitConversionSequence::Worse;
3751     }
3752   }
3753 
3754   // Ranking of member-pointer types.
3755   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3756       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3757       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3758     const MemberPointerType * FromMemPointer1 =
3759                                         FromType1->getAs<MemberPointerType>();
3760     const MemberPointerType * ToMemPointer1 =
3761                                           ToType1->getAs<MemberPointerType>();
3762     const MemberPointerType * FromMemPointer2 =
3763                                           FromType2->getAs<MemberPointerType>();
3764     const MemberPointerType * ToMemPointer2 =
3765                                           ToType2->getAs<MemberPointerType>();
3766     const Type *FromPointeeType1 = FromMemPointer1->getClass();
3767     const Type *ToPointeeType1 = ToMemPointer1->getClass();
3768     const Type *FromPointeeType2 = FromMemPointer2->getClass();
3769     const Type *ToPointeeType2 = ToMemPointer2->getClass();
3770     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3771     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3772     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3773     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3774     // conversion of A::* to B::* is better than conversion of A::* to C::*,
3775     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3776       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3777         return ImplicitConversionSequence::Worse;
3778       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3779         return ImplicitConversionSequence::Better;
3780     }
3781     // conversion of B::* to C::* is better than conversion of A::* to C::*
3782     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3783       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3784         return ImplicitConversionSequence::Better;
3785       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3786         return ImplicitConversionSequence::Worse;
3787     }
3788   }
3789 
3790   if (SCS1.Second == ICK_Derived_To_Base) {
3791     //   -- conversion of C to B is better than conversion of C to A,
3792     //   -- binding of an expression of type C to a reference of type
3793     //      B& is better than binding an expression of type C to a
3794     //      reference of type A&,
3795     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3796         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3797       if (S.IsDerivedFrom(ToType1, ToType2))
3798         return ImplicitConversionSequence::Better;
3799       else if (S.IsDerivedFrom(ToType2, ToType1))
3800         return ImplicitConversionSequence::Worse;
3801     }
3802 
3803     //   -- conversion of B to A is better than conversion of C to A.
3804     //   -- binding of an expression of type B to a reference of type
3805     //      A& is better than binding an expression of type C to a
3806     //      reference of type A&,
3807     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3808         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3809       if (S.IsDerivedFrom(FromType2, FromType1))
3810         return ImplicitConversionSequence::Better;
3811       else if (S.IsDerivedFrom(FromType1, FromType2))
3812         return ImplicitConversionSequence::Worse;
3813     }
3814   }
3815 
3816   return ImplicitConversionSequence::Indistinguishable;
3817 }
3818 
3819 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3820 /// determine whether they are reference-related,
3821 /// reference-compatible, reference-compatible with added
3822 /// qualification, or incompatible, for use in C++ initialization by
3823 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3824 /// type, and the first type (T1) is the pointee type of the reference
3825 /// type being initialized.
3826 Sema::ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc,QualType OrigT1,QualType OrigT2,bool & DerivedToBase,bool & ObjCConversion,bool & ObjCLifetimeConversion)3827 Sema::CompareReferenceRelationship(SourceLocation Loc,
3828                                    QualType OrigT1, QualType OrigT2,
3829                                    bool &DerivedToBase,
3830                                    bool &ObjCConversion,
3831                                    bool &ObjCLifetimeConversion) {
3832   assert(!OrigT1->isReferenceType() &&
3833     "T1 must be the pointee type of the reference type");
3834   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3835 
3836   QualType T1 = Context.getCanonicalType(OrigT1);
3837   QualType T2 = Context.getCanonicalType(OrigT2);
3838   Qualifiers T1Quals, T2Quals;
3839   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3840   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3841 
3842   // C++ [dcl.init.ref]p4:
3843   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3844   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3845   //   T1 is a base class of T2.
3846   DerivedToBase = false;
3847   ObjCConversion = false;
3848   ObjCLifetimeConversion = false;
3849   if (UnqualT1 == UnqualT2) {
3850     // Nothing to do.
3851   } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
3852            IsDerivedFrom(UnqualT2, UnqualT1))
3853     DerivedToBase = true;
3854   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3855            UnqualT2->isObjCObjectOrInterfaceType() &&
3856            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3857     ObjCConversion = true;
3858   else
3859     return Ref_Incompatible;
3860 
3861   // At this point, we know that T1 and T2 are reference-related (at
3862   // least).
3863 
3864   // If the type is an array type, promote the element qualifiers to the type
3865   // for comparison.
3866   if (isa<ArrayType>(T1) && T1Quals)
3867     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3868   if (isa<ArrayType>(T2) && T2Quals)
3869     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3870 
3871   // C++ [dcl.init.ref]p4:
3872   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3873   //   reference-related to T2 and cv1 is the same cv-qualification
3874   //   as, or greater cv-qualification than, cv2. For purposes of
3875   //   overload resolution, cases for which cv1 is greater
3876   //   cv-qualification than cv2 are identified as
3877   //   reference-compatible with added qualification (see 13.3.3.2).
3878   //
3879   // Note that we also require equivalence of Objective-C GC and address-space
3880   // qualifiers when performing these computations, so that e.g., an int in
3881   // address space 1 is not reference-compatible with an int in address
3882   // space 2.
3883   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3884       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3885     T1Quals.removeObjCLifetime();
3886     T2Quals.removeObjCLifetime();
3887     ObjCLifetimeConversion = true;
3888   }
3889 
3890   if (T1Quals == T2Quals)
3891     return Ref_Compatible;
3892   else if (T1Quals.compatiblyIncludes(T2Quals))
3893     return Ref_Compatible_With_Added_Qualification;
3894   else
3895     return Ref_Related;
3896 }
3897 
3898 /// \brief Look for a user-defined conversion to an value reference-compatible
3899 ///        with DeclType. Return true if something definite is found.
3900 static bool
FindConversionForRefInit(Sema & S,ImplicitConversionSequence & ICS,QualType DeclType,SourceLocation DeclLoc,Expr * Init,QualType T2,bool AllowRvalues,bool AllowExplicit)3901 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3902                          QualType DeclType, SourceLocation DeclLoc,
3903                          Expr *Init, QualType T2, bool AllowRvalues,
3904                          bool AllowExplicit) {
3905   assert(T2->isRecordType() && "Can only find conversions of record types.");
3906   CXXRecordDecl *T2RecordDecl
3907     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3908 
3909   OverloadCandidateSet CandidateSet(DeclLoc);
3910   const UnresolvedSetImpl *Conversions
3911     = T2RecordDecl->getVisibleConversionFunctions();
3912   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3913          E = Conversions->end(); I != E; ++I) {
3914     NamedDecl *D = *I;
3915     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3916     if (isa<UsingShadowDecl>(D))
3917       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3918 
3919     FunctionTemplateDecl *ConvTemplate
3920       = dyn_cast<FunctionTemplateDecl>(D);
3921     CXXConversionDecl *Conv;
3922     if (ConvTemplate)
3923       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3924     else
3925       Conv = cast<CXXConversionDecl>(D);
3926 
3927     // If this is an explicit conversion, and we're not allowed to consider
3928     // explicit conversions, skip it.
3929     if (!AllowExplicit && Conv->isExplicit())
3930       continue;
3931 
3932     if (AllowRvalues) {
3933       bool DerivedToBase = false;
3934       bool ObjCConversion = false;
3935       bool ObjCLifetimeConversion = false;
3936 
3937       // If we are initializing an rvalue reference, don't permit conversion
3938       // functions that return lvalues.
3939       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3940         const ReferenceType *RefType
3941           = Conv->getConversionType()->getAs<LValueReferenceType>();
3942         if (RefType && !RefType->getPointeeType()->isFunctionType())
3943           continue;
3944       }
3945 
3946       if (!ConvTemplate &&
3947           S.CompareReferenceRelationship(
3948             DeclLoc,
3949             Conv->getConversionType().getNonReferenceType()
3950               .getUnqualifiedType(),
3951             DeclType.getNonReferenceType().getUnqualifiedType(),
3952             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
3953           Sema::Ref_Incompatible)
3954         continue;
3955     } else {
3956       // If the conversion function doesn't return a reference type,
3957       // it can't be considered for this conversion. An rvalue reference
3958       // is only acceptable if its referencee is a function type.
3959 
3960       const ReferenceType *RefType =
3961         Conv->getConversionType()->getAs<ReferenceType>();
3962       if (!RefType ||
3963           (!RefType->isLValueReferenceType() &&
3964            !RefType->getPointeeType()->isFunctionType()))
3965         continue;
3966     }
3967 
3968     if (ConvTemplate)
3969       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
3970                                        Init, DeclType, CandidateSet);
3971     else
3972       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
3973                                DeclType, CandidateSet);
3974   }
3975 
3976   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3977 
3978   OverloadCandidateSet::iterator Best;
3979   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3980   case OR_Success:
3981     // C++ [over.ics.ref]p1:
3982     //
3983     //   [...] If the parameter binds directly to the result of
3984     //   applying a conversion function to the argument
3985     //   expression, the implicit conversion sequence is a
3986     //   user-defined conversion sequence (13.3.3.1.2), with the
3987     //   second standard conversion sequence either an identity
3988     //   conversion or, if the conversion function returns an
3989     //   entity of a type that is a derived class of the parameter
3990     //   type, a derived-to-base Conversion.
3991     if (!Best->FinalConversion.DirectBinding)
3992       return false;
3993 
3994     if (Best->Function)
3995       S.MarkFunctionReferenced(DeclLoc, Best->Function);
3996     ICS.setUserDefined();
3997     ICS.UserDefined.Before = Best->Conversions[0].Standard;
3998     ICS.UserDefined.After = Best->FinalConversion;
3999     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4000     ICS.UserDefined.ConversionFunction = Best->Function;
4001     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4002     ICS.UserDefined.EllipsisConversion = false;
4003     assert(ICS.UserDefined.After.ReferenceBinding &&
4004            ICS.UserDefined.After.DirectBinding &&
4005            "Expected a direct reference binding!");
4006     return true;
4007 
4008   case OR_Ambiguous:
4009     ICS.setAmbiguous();
4010     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4011          Cand != CandidateSet.end(); ++Cand)
4012       if (Cand->Viable)
4013         ICS.Ambiguous.addConversion(Cand->Function);
4014     return true;
4015 
4016   case OR_No_Viable_Function:
4017   case OR_Deleted:
4018     // There was no suitable conversion, or we found a deleted
4019     // conversion; continue with other checks.
4020     return false;
4021   }
4022 
4023   llvm_unreachable("Invalid OverloadResult!");
4024 }
4025 
4026 /// \brief Compute an implicit conversion sequence for reference
4027 /// initialization.
4028 static ImplicitConversionSequence
TryReferenceInit(Sema & S,Expr * Init,QualType DeclType,SourceLocation DeclLoc,bool SuppressUserConversions,bool AllowExplicit)4029 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4030                  SourceLocation DeclLoc,
4031                  bool SuppressUserConversions,
4032                  bool AllowExplicit) {
4033   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4034 
4035   // Most paths end in a failed conversion.
4036   ImplicitConversionSequence ICS;
4037   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4038 
4039   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4040   QualType T2 = Init->getType();
4041 
4042   // If the initializer is the address of an overloaded function, try
4043   // to resolve the overloaded function. If all goes well, T2 is the
4044   // type of the resulting function.
4045   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4046     DeclAccessPair Found;
4047     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4048                                                                 false, Found))
4049       T2 = Fn->getType();
4050   }
4051 
4052   // Compute some basic properties of the types and the initializer.
4053   bool isRValRef = DeclType->isRValueReferenceType();
4054   bool DerivedToBase = false;
4055   bool ObjCConversion = false;
4056   bool ObjCLifetimeConversion = false;
4057   Expr::Classification InitCategory = Init->Classify(S.Context);
4058   Sema::ReferenceCompareResult RefRelationship
4059     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4060                                      ObjCConversion, ObjCLifetimeConversion);
4061 
4062 
4063   // C++0x [dcl.init.ref]p5:
4064   //   A reference to type "cv1 T1" is initialized by an expression
4065   //   of type "cv2 T2" as follows:
4066 
4067   //     -- If reference is an lvalue reference and the initializer expression
4068   if (!isRValRef) {
4069     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4070     //        reference-compatible with "cv2 T2," or
4071     //
4072     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4073     if (InitCategory.isLValue() &&
4074         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4075       // C++ [over.ics.ref]p1:
4076       //   When a parameter of reference type binds directly (8.5.3)
4077       //   to an argument expression, the implicit conversion sequence
4078       //   is the identity conversion, unless the argument expression
4079       //   has a type that is a derived class of the parameter type,
4080       //   in which case the implicit conversion sequence is a
4081       //   derived-to-base Conversion (13.3.3.1).
4082       ICS.setStandard();
4083       ICS.Standard.First = ICK_Identity;
4084       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4085                          : ObjCConversion? ICK_Compatible_Conversion
4086                          : ICK_Identity;
4087       ICS.Standard.Third = ICK_Identity;
4088       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4089       ICS.Standard.setToType(0, T2);
4090       ICS.Standard.setToType(1, T1);
4091       ICS.Standard.setToType(2, T1);
4092       ICS.Standard.ReferenceBinding = true;
4093       ICS.Standard.DirectBinding = true;
4094       ICS.Standard.IsLvalueReference = !isRValRef;
4095       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4096       ICS.Standard.BindsToRvalue = false;
4097       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4098       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4099       ICS.Standard.CopyConstructor = 0;
4100 
4101       // Nothing more to do: the inaccessibility/ambiguity check for
4102       // derived-to-base conversions is suppressed when we're
4103       // computing the implicit conversion sequence (C++
4104       // [over.best.ics]p2).
4105       return ICS;
4106     }
4107 
4108     //       -- has a class type (i.e., T2 is a class type), where T1 is
4109     //          not reference-related to T2, and can be implicitly
4110     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4111     //          is reference-compatible with "cv3 T3" 92) (this
4112     //          conversion is selected by enumerating the applicable
4113     //          conversion functions (13.3.1.6) and choosing the best
4114     //          one through overload resolution (13.3)),
4115     if (!SuppressUserConversions && T2->isRecordType() &&
4116         !S.RequireCompleteType(DeclLoc, T2, 0) &&
4117         RefRelationship == Sema::Ref_Incompatible) {
4118       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4119                                    Init, T2, /*AllowRvalues=*/false,
4120                                    AllowExplicit))
4121         return ICS;
4122     }
4123   }
4124 
4125   //     -- Otherwise, the reference shall be an lvalue reference to a
4126   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4127   //        shall be an rvalue reference.
4128   //
4129   // We actually handle one oddity of C++ [over.ics.ref] at this
4130   // point, which is that, due to p2 (which short-circuits reference
4131   // binding by only attempting a simple conversion for non-direct
4132   // bindings) and p3's strange wording, we allow a const volatile
4133   // reference to bind to an rvalue. Hence the check for the presence
4134   // of "const" rather than checking for "const" being the only
4135   // qualifier.
4136   // This is also the point where rvalue references and lvalue inits no longer
4137   // go together.
4138   if (!isRValRef && !T1.isConstQualified())
4139     return ICS;
4140 
4141   //       -- If the initializer expression
4142   //
4143   //            -- is an xvalue, class prvalue, array prvalue or function
4144   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4145   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4146       (InitCategory.isXValue() ||
4147       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4148       (InitCategory.isLValue() && T2->isFunctionType()))) {
4149     ICS.setStandard();
4150     ICS.Standard.First = ICK_Identity;
4151     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4152                       : ObjCConversion? ICK_Compatible_Conversion
4153                       : ICK_Identity;
4154     ICS.Standard.Third = ICK_Identity;
4155     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4156     ICS.Standard.setToType(0, T2);
4157     ICS.Standard.setToType(1, T1);
4158     ICS.Standard.setToType(2, T1);
4159     ICS.Standard.ReferenceBinding = true;
4160     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4161     // binding unless we're binding to a class prvalue.
4162     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4163     // allow the use of rvalue references in C++98/03 for the benefit of
4164     // standard library implementors; therefore, we need the xvalue check here.
4165     ICS.Standard.DirectBinding =
4166       S.getLangOpts().CPlusPlus0x ||
4167       (InitCategory.isPRValue() && !T2->isRecordType());
4168     ICS.Standard.IsLvalueReference = !isRValRef;
4169     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4170     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4171     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4172     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4173     ICS.Standard.CopyConstructor = 0;
4174     return ICS;
4175   }
4176 
4177   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4178   //               reference-related to T2, and can be implicitly converted to
4179   //               an xvalue, class prvalue, or function lvalue of type
4180   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4181   //               "cv3 T3",
4182   //
4183   //          then the reference is bound to the value of the initializer
4184   //          expression in the first case and to the result of the conversion
4185   //          in the second case (or, in either case, to an appropriate base
4186   //          class subobject).
4187   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4188       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4189       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4190                                Init, T2, /*AllowRvalues=*/true,
4191                                AllowExplicit)) {
4192     // In the second case, if the reference is an rvalue reference
4193     // and the second standard conversion sequence of the
4194     // user-defined conversion sequence includes an lvalue-to-rvalue
4195     // conversion, the program is ill-formed.
4196     if (ICS.isUserDefined() && isRValRef &&
4197         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4198       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4199 
4200     return ICS;
4201   }
4202 
4203   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4204   //          initialized from the initializer expression using the
4205   //          rules for a non-reference copy initialization (8.5). The
4206   //          reference is then bound to the temporary. If T1 is
4207   //          reference-related to T2, cv1 must be the same
4208   //          cv-qualification as, or greater cv-qualification than,
4209   //          cv2; otherwise, the program is ill-formed.
4210   if (RefRelationship == Sema::Ref_Related) {
4211     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4212     // we would be reference-compatible or reference-compatible with
4213     // added qualification. But that wasn't the case, so the reference
4214     // initialization fails.
4215     //
4216     // Note that we only want to check address spaces and cvr-qualifiers here.
4217     // ObjC GC and lifetime qualifiers aren't important.
4218     Qualifiers T1Quals = T1.getQualifiers();
4219     Qualifiers T2Quals = T2.getQualifiers();
4220     T1Quals.removeObjCGCAttr();
4221     T1Quals.removeObjCLifetime();
4222     T2Quals.removeObjCGCAttr();
4223     T2Quals.removeObjCLifetime();
4224     if (!T1Quals.compatiblyIncludes(T2Quals))
4225       return ICS;
4226   }
4227 
4228   // If at least one of the types is a class type, the types are not
4229   // related, and we aren't allowed any user conversions, the
4230   // reference binding fails. This case is important for breaking
4231   // recursion, since TryImplicitConversion below will attempt to
4232   // create a temporary through the use of a copy constructor.
4233   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4234       (T1->isRecordType() || T2->isRecordType()))
4235     return ICS;
4236 
4237   // If T1 is reference-related to T2 and the reference is an rvalue
4238   // reference, the initializer expression shall not be an lvalue.
4239   if (RefRelationship >= Sema::Ref_Related &&
4240       isRValRef && Init->Classify(S.Context).isLValue())
4241     return ICS;
4242 
4243   // C++ [over.ics.ref]p2:
4244   //   When a parameter of reference type is not bound directly to
4245   //   an argument expression, the conversion sequence is the one
4246   //   required to convert the argument expression to the
4247   //   underlying type of the reference according to
4248   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4249   //   to copy-initializing a temporary of the underlying type with
4250   //   the argument expression. Any difference in top-level
4251   //   cv-qualification is subsumed by the initialization itself
4252   //   and does not constitute a conversion.
4253   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4254                               /*AllowExplicit=*/false,
4255                               /*InOverloadResolution=*/false,
4256                               /*CStyle=*/false,
4257                               /*AllowObjCWritebackConversion=*/false);
4258 
4259   // Of course, that's still a reference binding.
4260   if (ICS.isStandard()) {
4261     ICS.Standard.ReferenceBinding = true;
4262     ICS.Standard.IsLvalueReference = !isRValRef;
4263     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4264     ICS.Standard.BindsToRvalue = true;
4265     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4266     ICS.Standard.ObjCLifetimeConversionBinding = false;
4267   } else if (ICS.isUserDefined()) {
4268     // Don't allow rvalue references to bind to lvalues.
4269     if (DeclType->isRValueReferenceType()) {
4270       if (const ReferenceType *RefType
4271             = ICS.UserDefined.ConversionFunction->getResultType()
4272                 ->getAs<LValueReferenceType>()) {
4273         if (!RefType->getPointeeType()->isFunctionType()) {
4274           ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4275                      DeclType);
4276           return ICS;
4277         }
4278       }
4279     }
4280 
4281     ICS.UserDefined.After.ReferenceBinding = true;
4282     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4283     ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4284     ICS.UserDefined.After.BindsToRvalue = true;
4285     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4286     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4287   }
4288 
4289   return ICS;
4290 }
4291 
4292 static ImplicitConversionSequence
4293 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4294                       bool SuppressUserConversions,
4295                       bool InOverloadResolution,
4296                       bool AllowObjCWritebackConversion,
4297                       bool AllowExplicit = false);
4298 
4299 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4300 /// initializer list From.
4301 static ImplicitConversionSequence
TryListConversion(Sema & S,InitListExpr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion)4302 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4303                   bool SuppressUserConversions,
4304                   bool InOverloadResolution,
4305                   bool AllowObjCWritebackConversion) {
4306   // C++11 [over.ics.list]p1:
4307   //   When an argument is an initializer list, it is not an expression and
4308   //   special rules apply for converting it to a parameter type.
4309 
4310   ImplicitConversionSequence Result;
4311   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4312   Result.setListInitializationSequence();
4313 
4314   // We need a complete type for what follows. Incomplete types can never be
4315   // initialized from init lists.
4316   if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4317     return Result;
4318 
4319   // C++11 [over.ics.list]p2:
4320   //   If the parameter type is std::initializer_list<X> or "array of X" and
4321   //   all the elements can be implicitly converted to X, the implicit
4322   //   conversion sequence is the worst conversion necessary to convert an
4323   //   element of the list to X.
4324   bool toStdInitializerList = false;
4325   QualType X;
4326   if (ToType->isArrayType())
4327     X = S.Context.getBaseElementType(ToType);
4328   else
4329     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4330   if (!X.isNull()) {
4331     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4332       Expr *Init = From->getInit(i);
4333       ImplicitConversionSequence ICS =
4334           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4335                                 InOverloadResolution,
4336                                 AllowObjCWritebackConversion);
4337       // If a single element isn't convertible, fail.
4338       if (ICS.isBad()) {
4339         Result = ICS;
4340         break;
4341       }
4342       // Otherwise, look for the worst conversion.
4343       if (Result.isBad() ||
4344           CompareImplicitConversionSequences(S, ICS, Result) ==
4345               ImplicitConversionSequence::Worse)
4346         Result = ICS;
4347     }
4348 
4349     // For an empty list, we won't have computed any conversion sequence.
4350     // Introduce the identity conversion sequence.
4351     if (From->getNumInits() == 0) {
4352       Result.setStandard();
4353       Result.Standard.setAsIdentityConversion();
4354       Result.Standard.setFromType(ToType);
4355       Result.Standard.setAllToTypes(ToType);
4356     }
4357 
4358     Result.setListInitializationSequence();
4359     Result.setStdInitializerListElement(toStdInitializerList);
4360     return Result;
4361   }
4362 
4363   // C++11 [over.ics.list]p3:
4364   //   Otherwise, if the parameter is a non-aggregate class X and overload
4365   //   resolution chooses a single best constructor [...] the implicit
4366   //   conversion sequence is a user-defined conversion sequence. If multiple
4367   //   constructors are viable but none is better than the others, the
4368   //   implicit conversion sequence is a user-defined conversion sequence.
4369   if (ToType->isRecordType() && !ToType->isAggregateType()) {
4370     // This function can deal with initializer lists.
4371     Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4372                                       /*AllowExplicit=*/false,
4373                                       InOverloadResolution, /*CStyle=*/false,
4374                                       AllowObjCWritebackConversion);
4375     Result.setListInitializationSequence();
4376     return Result;
4377   }
4378 
4379   // C++11 [over.ics.list]p4:
4380   //   Otherwise, if the parameter has an aggregate type which can be
4381   //   initialized from the initializer list [...] the implicit conversion
4382   //   sequence is a user-defined conversion sequence.
4383   if (ToType->isAggregateType()) {
4384     // Type is an aggregate, argument is an init list. At this point it comes
4385     // down to checking whether the initialization works.
4386     // FIXME: Find out whether this parameter is consumed or not.
4387     InitializedEntity Entity =
4388         InitializedEntity::InitializeParameter(S.Context, ToType,
4389                                                /*Consumed=*/false);
4390     if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4391       Result.setUserDefined();
4392       Result.UserDefined.Before.setAsIdentityConversion();
4393       // Initializer lists don't have a type.
4394       Result.UserDefined.Before.setFromType(QualType());
4395       Result.UserDefined.Before.setAllToTypes(QualType());
4396 
4397       Result.UserDefined.After.setAsIdentityConversion();
4398       Result.UserDefined.After.setFromType(ToType);
4399       Result.UserDefined.After.setAllToTypes(ToType);
4400       Result.UserDefined.ConversionFunction = 0;
4401     }
4402     return Result;
4403   }
4404 
4405   // C++11 [over.ics.list]p5:
4406   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4407   if (ToType->isReferenceType()) {
4408     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4409     // mention initializer lists in any way. So we go by what list-
4410     // initialization would do and try to extrapolate from that.
4411 
4412     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4413 
4414     // If the initializer list has a single element that is reference-related
4415     // to the parameter type, we initialize the reference from that.
4416     if (From->getNumInits() == 1) {
4417       Expr *Init = From->getInit(0);
4418 
4419       QualType T2 = Init->getType();
4420 
4421       // If the initializer is the address of an overloaded function, try
4422       // to resolve the overloaded function. If all goes well, T2 is the
4423       // type of the resulting function.
4424       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4425         DeclAccessPair Found;
4426         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4427                                    Init, ToType, false, Found))
4428           T2 = Fn->getType();
4429       }
4430 
4431       // Compute some basic properties of the types and the initializer.
4432       bool dummy1 = false;
4433       bool dummy2 = false;
4434       bool dummy3 = false;
4435       Sema::ReferenceCompareResult RefRelationship
4436         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4437                                          dummy2, dummy3);
4438 
4439       if (RefRelationship >= Sema::Ref_Related)
4440         return TryReferenceInit(S, Init, ToType,
4441                                 /*FIXME:*/From->getLocStart(),
4442                                 SuppressUserConversions,
4443                                 /*AllowExplicit=*/false);
4444     }
4445 
4446     // Otherwise, we bind the reference to a temporary created from the
4447     // initializer list.
4448     Result = TryListConversion(S, From, T1, SuppressUserConversions,
4449                                InOverloadResolution,
4450                                AllowObjCWritebackConversion);
4451     if (Result.isFailure())
4452       return Result;
4453     assert(!Result.isEllipsis() &&
4454            "Sub-initialization cannot result in ellipsis conversion.");
4455 
4456     // Can we even bind to a temporary?
4457     if (ToType->isRValueReferenceType() ||
4458         (T1.isConstQualified() && !T1.isVolatileQualified())) {
4459       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4460                                             Result.UserDefined.After;
4461       SCS.ReferenceBinding = true;
4462       SCS.IsLvalueReference = ToType->isLValueReferenceType();
4463       SCS.BindsToRvalue = true;
4464       SCS.BindsToFunctionLvalue = false;
4465       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4466       SCS.ObjCLifetimeConversionBinding = false;
4467     } else
4468       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4469                     From, ToType);
4470     return Result;
4471   }
4472 
4473   // C++11 [over.ics.list]p6:
4474   //   Otherwise, if the parameter type is not a class:
4475   if (!ToType->isRecordType()) {
4476     //    - if the initializer list has one element, the implicit conversion
4477     //      sequence is the one required to convert the element to the
4478     //      parameter type.
4479     unsigned NumInits = From->getNumInits();
4480     if (NumInits == 1)
4481       Result = TryCopyInitialization(S, From->getInit(0), ToType,
4482                                      SuppressUserConversions,
4483                                      InOverloadResolution,
4484                                      AllowObjCWritebackConversion);
4485     //    - if the initializer list has no elements, the implicit conversion
4486     //      sequence is the identity conversion.
4487     else if (NumInits == 0) {
4488       Result.setStandard();
4489       Result.Standard.setAsIdentityConversion();
4490       Result.Standard.setFromType(ToType);
4491       Result.Standard.setAllToTypes(ToType);
4492     }
4493     Result.setListInitializationSequence();
4494     return Result;
4495   }
4496 
4497   // C++11 [over.ics.list]p7:
4498   //   In all cases other than those enumerated above, no conversion is possible
4499   return Result;
4500 }
4501 
4502 /// TryCopyInitialization - Try to copy-initialize a value of type
4503 /// ToType from the expression From. Return the implicit conversion
4504 /// sequence required to pass this argument, which may be a bad
4505 /// conversion sequence (meaning that the argument cannot be passed to
4506 /// a parameter of this type). If @p SuppressUserConversions, then we
4507 /// do not permit any user-defined conversion sequences.
4508 static ImplicitConversionSequence
TryCopyInitialization(Sema & S,Expr * From,QualType ToType,bool SuppressUserConversions,bool InOverloadResolution,bool AllowObjCWritebackConversion,bool AllowExplicit)4509 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4510                       bool SuppressUserConversions,
4511                       bool InOverloadResolution,
4512                       bool AllowObjCWritebackConversion,
4513                       bool AllowExplicit) {
4514   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4515     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4516                              InOverloadResolution,AllowObjCWritebackConversion);
4517 
4518   if (ToType->isReferenceType())
4519     return TryReferenceInit(S, From, ToType,
4520                             /*FIXME:*/From->getLocStart(),
4521                             SuppressUserConversions,
4522                             AllowExplicit);
4523 
4524   return TryImplicitConversion(S, From, ToType,
4525                                SuppressUserConversions,
4526                                /*AllowExplicit=*/false,
4527                                InOverloadResolution,
4528                                /*CStyle=*/false,
4529                                AllowObjCWritebackConversion);
4530 }
4531 
TryCopyInitialization(const CanQualType FromQTy,const CanQualType ToQTy,Sema & S,SourceLocation Loc,ExprValueKind FromVK)4532 static bool TryCopyInitialization(const CanQualType FromQTy,
4533                                   const CanQualType ToQTy,
4534                                   Sema &S,
4535                                   SourceLocation Loc,
4536                                   ExprValueKind FromVK) {
4537   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4538   ImplicitConversionSequence ICS =
4539     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4540 
4541   return !ICS.isBad();
4542 }
4543 
4544 /// TryObjectArgumentInitialization - Try to initialize the object
4545 /// parameter of the given member function (@c Method) from the
4546 /// expression @p From.
4547 static ImplicitConversionSequence
TryObjectArgumentInitialization(Sema & S,QualType OrigFromType,Expr::Classification FromClassification,CXXMethodDecl * Method,CXXRecordDecl * ActingContext)4548 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
4549                                 Expr::Classification FromClassification,
4550                                 CXXMethodDecl *Method,
4551                                 CXXRecordDecl *ActingContext) {
4552   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4553   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4554   //                 const volatile object.
4555   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4556     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4557   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
4558 
4559   // Set up the conversion sequence as a "bad" conversion, to allow us
4560   // to exit early.
4561   ImplicitConversionSequence ICS;
4562 
4563   // We need to have an object of class type.
4564   QualType FromType = OrigFromType;
4565   if (const PointerType *PT = FromType->getAs<PointerType>()) {
4566     FromType = PT->getPointeeType();
4567 
4568     // When we had a pointer, it's implicitly dereferenced, so we
4569     // better have an lvalue.
4570     assert(FromClassification.isLValue());
4571   }
4572 
4573   assert(FromType->isRecordType());
4574 
4575   // C++0x [over.match.funcs]p4:
4576   //   For non-static member functions, the type of the implicit object
4577   //   parameter is
4578   //
4579   //     - "lvalue reference to cv X" for functions declared without a
4580   //        ref-qualifier or with the & ref-qualifier
4581   //     - "rvalue reference to cv X" for functions declared with the &&
4582   //        ref-qualifier
4583   //
4584   // where X is the class of which the function is a member and cv is the
4585   // cv-qualification on the member function declaration.
4586   //
4587   // However, when finding an implicit conversion sequence for the argument, we
4588   // are not allowed to create temporaries or perform user-defined conversions
4589   // (C++ [over.match.funcs]p5). We perform a simplified version of
4590   // reference binding here, that allows class rvalues to bind to
4591   // non-constant references.
4592 
4593   // First check the qualifiers.
4594   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4595   if (ImplicitParamType.getCVRQualifiers()
4596                                     != FromTypeCanon.getLocalCVRQualifiers() &&
4597       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4598     ICS.setBad(BadConversionSequence::bad_qualifiers,
4599                OrigFromType, ImplicitParamType);
4600     return ICS;
4601   }
4602 
4603   // Check that we have either the same type or a derived type. It
4604   // affects the conversion rank.
4605   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4606   ImplicitConversionKind SecondKind;
4607   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4608     SecondKind = ICK_Identity;
4609   } else if (S.IsDerivedFrom(FromType, ClassType))
4610     SecondKind = ICK_Derived_To_Base;
4611   else {
4612     ICS.setBad(BadConversionSequence::unrelated_class,
4613                FromType, ImplicitParamType);
4614     return ICS;
4615   }
4616 
4617   // Check the ref-qualifier.
4618   switch (Method->getRefQualifier()) {
4619   case RQ_None:
4620     // Do nothing; we don't care about lvalueness or rvalueness.
4621     break;
4622 
4623   case RQ_LValue:
4624     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4625       // non-const lvalue reference cannot bind to an rvalue
4626       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4627                  ImplicitParamType);
4628       return ICS;
4629     }
4630     break;
4631 
4632   case RQ_RValue:
4633     if (!FromClassification.isRValue()) {
4634       // rvalue reference cannot bind to an lvalue
4635       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4636                  ImplicitParamType);
4637       return ICS;
4638     }
4639     break;
4640   }
4641 
4642   // Success. Mark this as a reference binding.
4643   ICS.setStandard();
4644   ICS.Standard.setAsIdentityConversion();
4645   ICS.Standard.Second = SecondKind;
4646   ICS.Standard.setFromType(FromType);
4647   ICS.Standard.setAllToTypes(ImplicitParamType);
4648   ICS.Standard.ReferenceBinding = true;
4649   ICS.Standard.DirectBinding = true;
4650   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4651   ICS.Standard.BindsToFunctionLvalue = false;
4652   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4653   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4654     = (Method->getRefQualifier() == RQ_None);
4655   return ICS;
4656 }
4657 
4658 /// PerformObjectArgumentInitialization - Perform initialization of
4659 /// the implicit object parameter for the given Method with the given
4660 /// expression.
4661 ExprResult
PerformObjectArgumentInitialization(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,CXXMethodDecl * Method)4662 Sema::PerformObjectArgumentInitialization(Expr *From,
4663                                           NestedNameSpecifier *Qualifier,
4664                                           NamedDecl *FoundDecl,
4665                                           CXXMethodDecl *Method) {
4666   QualType FromRecordType, DestType;
4667   QualType ImplicitParamRecordType  =
4668     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4669 
4670   Expr::Classification FromClassification;
4671   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4672     FromRecordType = PT->getPointeeType();
4673     DestType = Method->getThisType(Context);
4674     FromClassification = Expr::Classification::makeSimpleLValue();
4675   } else {
4676     FromRecordType = From->getType();
4677     DestType = ImplicitParamRecordType;
4678     FromClassification = From->Classify(Context);
4679   }
4680 
4681   // Note that we always use the true parent context when performing
4682   // the actual argument initialization.
4683   ImplicitConversionSequence ICS
4684     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4685                                       Method, Method->getParent());
4686   if (ICS.isBad()) {
4687     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4688       Qualifiers FromQs = FromRecordType.getQualifiers();
4689       Qualifiers ToQs = DestType.getQualifiers();
4690       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4691       if (CVR) {
4692         Diag(From->getLocStart(),
4693              diag::err_member_function_call_bad_cvr)
4694           << Method->getDeclName() << FromRecordType << (CVR - 1)
4695           << From->getSourceRange();
4696         Diag(Method->getLocation(), diag::note_previous_decl)
4697           << Method->getDeclName();
4698         return ExprError();
4699       }
4700     }
4701 
4702     return Diag(From->getLocStart(),
4703                 diag::err_implicit_object_parameter_init)
4704        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4705   }
4706 
4707   if (ICS.Standard.Second == ICK_Derived_To_Base) {
4708     ExprResult FromRes =
4709       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4710     if (FromRes.isInvalid())
4711       return ExprError();
4712     From = FromRes.take();
4713   }
4714 
4715   if (!Context.hasSameType(From->getType(), DestType))
4716     From = ImpCastExprToType(From, DestType, CK_NoOp,
4717                              From->getValueKind()).take();
4718   return Owned(From);
4719 }
4720 
4721 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4722 /// expression From to bool (C++0x [conv]p3).
4723 static ImplicitConversionSequence
TryContextuallyConvertToBool(Sema & S,Expr * From)4724 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4725   // FIXME: This is pretty broken.
4726   return TryImplicitConversion(S, From, S.Context.BoolTy,
4727                                // FIXME: Are these flags correct?
4728                                /*SuppressUserConversions=*/false,
4729                                /*AllowExplicit=*/true,
4730                                /*InOverloadResolution=*/false,
4731                                /*CStyle=*/false,
4732                                /*AllowObjCWritebackConversion=*/false);
4733 }
4734 
4735 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4736 /// of the expression From to bool (C++0x [conv]p3).
PerformContextuallyConvertToBool(Expr * From)4737 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4738   if (checkPlaceholderForOverload(*this, From))
4739     return ExprError();
4740 
4741   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4742   if (!ICS.isBad())
4743     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4744 
4745   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4746     return Diag(From->getLocStart(),
4747                 diag::err_typecheck_bool_condition)
4748                   << From->getType() << From->getSourceRange();
4749   return ExprError();
4750 }
4751 
4752 /// Check that the specified conversion is permitted in a converted constant
4753 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4754 /// is acceptable.
CheckConvertedConstantConversions(Sema & S,StandardConversionSequence & SCS)4755 static bool CheckConvertedConstantConversions(Sema &S,
4756                                               StandardConversionSequence &SCS) {
4757   // Since we know that the target type is an integral or unscoped enumeration
4758   // type, most conversion kinds are impossible. All possible First and Third
4759   // conversions are fine.
4760   switch (SCS.Second) {
4761   case ICK_Identity:
4762   case ICK_Integral_Promotion:
4763   case ICK_Integral_Conversion:
4764     return true;
4765 
4766   case ICK_Boolean_Conversion:
4767     // Conversion from an integral or unscoped enumeration type to bool is
4768     // classified as ICK_Boolean_Conversion, but it's also an integral
4769     // conversion, so it's permitted in a converted constant expression.
4770     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4771            SCS.getToType(2)->isBooleanType();
4772 
4773   case ICK_Floating_Integral:
4774   case ICK_Complex_Real:
4775     return false;
4776 
4777   case ICK_Lvalue_To_Rvalue:
4778   case ICK_Array_To_Pointer:
4779   case ICK_Function_To_Pointer:
4780   case ICK_NoReturn_Adjustment:
4781   case ICK_Qualification:
4782   case ICK_Compatible_Conversion:
4783   case ICK_Vector_Conversion:
4784   case ICK_Vector_Splat:
4785   case ICK_Derived_To_Base:
4786   case ICK_Pointer_Conversion:
4787   case ICK_Pointer_Member:
4788   case ICK_Block_Pointer_Conversion:
4789   case ICK_Writeback_Conversion:
4790   case ICK_Floating_Promotion:
4791   case ICK_Complex_Promotion:
4792   case ICK_Complex_Conversion:
4793   case ICK_Floating_Conversion:
4794   case ICK_TransparentUnionConversion:
4795     llvm_unreachable("unexpected second conversion kind");
4796 
4797   case ICK_Num_Conversion_Kinds:
4798     break;
4799   }
4800 
4801   llvm_unreachable("unknown conversion kind");
4802 }
4803 
4804 /// CheckConvertedConstantExpression - Check that the expression From is a
4805 /// converted constant expression of type T, perform the conversion and produce
4806 /// the converted expression, per C++11 [expr.const]p3.
CheckConvertedConstantExpression(Expr * From,QualType T,llvm::APSInt & Value,CCEKind CCE)4807 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4808                                                   llvm::APSInt &Value,
4809                                                   CCEKind CCE) {
4810   assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4811   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4812 
4813   if (checkPlaceholderForOverload(*this, From))
4814     return ExprError();
4815 
4816   // C++11 [expr.const]p3 with proposed wording fixes:
4817   //  A converted constant expression of type T is a core constant expression,
4818   //  implicitly converted to a prvalue of type T, where the converted
4819   //  expression is a literal constant expression and the implicit conversion
4820   //  sequence contains only user-defined conversions, lvalue-to-rvalue
4821   //  conversions, integral promotions, and integral conversions other than
4822   //  narrowing conversions.
4823   ImplicitConversionSequence ICS =
4824     TryImplicitConversion(From, T,
4825                           /*SuppressUserConversions=*/false,
4826                           /*AllowExplicit=*/false,
4827                           /*InOverloadResolution=*/false,
4828                           /*CStyle=*/false,
4829                           /*AllowObjcWritebackConversion=*/false);
4830   StandardConversionSequence *SCS = 0;
4831   switch (ICS.getKind()) {
4832   case ImplicitConversionSequence::StandardConversion:
4833     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
4834       return Diag(From->getLocStart(),
4835                   diag::err_typecheck_converted_constant_expression_disallowed)
4836                << From->getType() << From->getSourceRange() << T;
4837     SCS = &ICS.Standard;
4838     break;
4839   case ImplicitConversionSequence::UserDefinedConversion:
4840     // We are converting from class type to an integral or enumeration type, so
4841     // the Before sequence must be trivial.
4842     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
4843       return Diag(From->getLocStart(),
4844                   diag::err_typecheck_converted_constant_expression_disallowed)
4845                << From->getType() << From->getSourceRange() << T;
4846     SCS = &ICS.UserDefined.After;
4847     break;
4848   case ImplicitConversionSequence::AmbiguousConversion:
4849   case ImplicitConversionSequence::BadConversion:
4850     if (!DiagnoseMultipleUserDefinedConversion(From, T))
4851       return Diag(From->getLocStart(),
4852                   diag::err_typecheck_converted_constant_expression)
4853                     << From->getType() << From->getSourceRange() << T;
4854     return ExprError();
4855 
4856   case ImplicitConversionSequence::EllipsisConversion:
4857     llvm_unreachable("ellipsis conversion in converted constant expression");
4858   }
4859 
4860   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4861   if (Result.isInvalid())
4862     return Result;
4863 
4864   // Check for a narrowing implicit conversion.
4865   APValue PreNarrowingValue;
4866   QualType PreNarrowingType;
4867   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4868                                 PreNarrowingType)) {
4869   case NK_Variable_Narrowing:
4870     // Implicit conversion to a narrower type, and the value is not a constant
4871     // expression. We'll diagnose this in a moment.
4872   case NK_Not_Narrowing:
4873     break;
4874 
4875   case NK_Constant_Narrowing:
4876     Diag(From->getLocStart(),
4877          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4878                              diag::err_cce_narrowing)
4879       << CCE << /*Constant*/1
4880       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
4881     break;
4882 
4883   case NK_Type_Narrowing:
4884     Diag(From->getLocStart(),
4885          isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4886                              diag::err_cce_narrowing)
4887       << CCE << /*Constant*/0 << From->getType() << T;
4888     break;
4889   }
4890 
4891   // Check the expression is a constant expression.
4892   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4893   Expr::EvalResult Eval;
4894   Eval.Diag = &Notes;
4895 
4896   if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4897     // The expression can't be folded, so we can't keep it at this position in
4898     // the AST.
4899     Result = ExprError();
4900   } else {
4901     Value = Eval.Val.getInt();
4902 
4903     if (Notes.empty()) {
4904       // It's a constant expression.
4905       return Result;
4906     }
4907   }
4908 
4909   // It's not a constant expression. Produce an appropriate diagnostic.
4910   if (Notes.size() == 1 &&
4911       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4912     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4913   else {
4914     Diag(From->getLocStart(), diag::err_expr_not_cce)
4915       << CCE << From->getSourceRange();
4916     for (unsigned I = 0; I < Notes.size(); ++I)
4917       Diag(Notes[I].first, Notes[I].second);
4918   }
4919   return Result;
4920 }
4921 
4922 /// dropPointerConversions - If the given standard conversion sequence
4923 /// involves any pointer conversions, remove them.  This may change
4924 /// the result type of the conversion sequence.
dropPointerConversion(StandardConversionSequence & SCS)4925 static void dropPointerConversion(StandardConversionSequence &SCS) {
4926   if (SCS.Second == ICK_Pointer_Conversion) {
4927     SCS.Second = ICK_Identity;
4928     SCS.Third = ICK_Identity;
4929     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4930   }
4931 }
4932 
4933 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
4934 /// convert the expression From to an Objective-C pointer type.
4935 static ImplicitConversionSequence
TryContextuallyConvertToObjCPointer(Sema & S,Expr * From)4936 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4937   // Do an implicit conversion to 'id'.
4938   QualType Ty = S.Context.getObjCIdType();
4939   ImplicitConversionSequence ICS
4940     = TryImplicitConversion(S, From, Ty,
4941                             // FIXME: Are these flags correct?
4942                             /*SuppressUserConversions=*/false,
4943                             /*AllowExplicit=*/true,
4944                             /*InOverloadResolution=*/false,
4945                             /*CStyle=*/false,
4946                             /*AllowObjCWritebackConversion=*/false);
4947 
4948   // Strip off any final conversions to 'id'.
4949   switch (ICS.getKind()) {
4950   case ImplicitConversionSequence::BadConversion:
4951   case ImplicitConversionSequence::AmbiguousConversion:
4952   case ImplicitConversionSequence::EllipsisConversion:
4953     break;
4954 
4955   case ImplicitConversionSequence::UserDefinedConversion:
4956     dropPointerConversion(ICS.UserDefined.After);
4957     break;
4958 
4959   case ImplicitConversionSequence::StandardConversion:
4960     dropPointerConversion(ICS.Standard);
4961     break;
4962   }
4963 
4964   return ICS;
4965 }
4966 
4967 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
4968 /// conversion of the expression From to an Objective-C pointer type.
PerformContextuallyConvertToObjCPointer(Expr * From)4969 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
4970   if (checkPlaceholderForOverload(*this, From))
4971     return ExprError();
4972 
4973   QualType Ty = Context.getObjCIdType();
4974   ImplicitConversionSequence ICS =
4975     TryContextuallyConvertToObjCPointer(*this, From);
4976   if (!ICS.isBad())
4977     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
4978   return ExprError();
4979 }
4980 
4981 /// Determine whether the provided type is an integral type, or an enumeration
4982 /// type of a permitted flavor.
isIntegralOrEnumerationType(QualType T,bool AllowScopedEnum)4983 static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4984   return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4985                          : T->isIntegralOrUnscopedEnumerationType();
4986 }
4987 
4988 /// \brief Attempt to convert the given expression to an integral or
4989 /// enumeration type.
4990 ///
4991 /// This routine will attempt to convert an expression of class type to an
4992 /// integral or enumeration type, if that class type only has a single
4993 /// conversion to an integral or enumeration type.
4994 ///
4995 /// \param Loc The source location of the construct that requires the
4996 /// conversion.
4997 ///
4998 /// \param FromE The expression we're converting from.
4999 ///
5000 /// \param NotIntDiag The diagnostic to be emitted if the expression does not
5001 /// have integral or enumeration type.
5002 ///
5003 /// \param IncompleteDiag The diagnostic to be emitted if the expression has
5004 /// incomplete class type.
5005 ///
5006 /// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
5007 /// explicit conversion function (because no implicit conversion functions
5008 /// were available). This is a recovery mode.
5009 ///
5010 /// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
5011 /// showing which conversion was picked.
5012 ///
5013 /// \param AmbigDiag The diagnostic to be emitted if there is more than one
5014 /// conversion function that could convert to integral or enumeration type.
5015 ///
5016 /// \param AmbigNote The note to be emitted with \p AmbigDiag for each
5017 /// usable conversion function.
5018 ///
5019 /// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
5020 /// function, which may be an extension in this case.
5021 ///
5022 /// \param AllowScopedEnumerations Specifies whether conversions to scoped
5023 /// enumerations should be considered.
5024 ///
5025 /// \returns The expression, converted to an integral or enumeration type if
5026 /// successful.
5027 ExprResult
ConvertToIntegralOrEnumerationType(SourceLocation Loc,Expr * From,const PartialDiagnostic & NotIntDiag,const PartialDiagnostic & IncompleteDiag,const PartialDiagnostic & ExplicitConvDiag,const PartialDiagnostic & ExplicitConvNote,const PartialDiagnostic & AmbigDiag,const PartialDiagnostic & AmbigNote,const PartialDiagnostic & ConvDiag,bool AllowScopedEnumerations)5028 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
5029                                          const PartialDiagnostic &NotIntDiag,
5030                                        const PartialDiagnostic &IncompleteDiag,
5031                                      const PartialDiagnostic &ExplicitConvDiag,
5032                                      const PartialDiagnostic &ExplicitConvNote,
5033                                          const PartialDiagnostic &AmbigDiag,
5034                                          const PartialDiagnostic &AmbigNote,
5035                                          const PartialDiagnostic &ConvDiag,
5036                                          bool AllowScopedEnumerations) {
5037   // We can't perform any more checking for type-dependent expressions.
5038   if (From->isTypeDependent())
5039     return Owned(From);
5040 
5041   // Process placeholders immediately.
5042   if (From->hasPlaceholderType()) {
5043     ExprResult result = CheckPlaceholderExpr(From);
5044     if (result.isInvalid()) return result;
5045     From = result.take();
5046   }
5047 
5048   // If the expression already has integral or enumeration type, we're golden.
5049   QualType T = From->getType();
5050   if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
5051     return DefaultLvalueConversion(From);
5052 
5053   // FIXME: Check for missing '()' if T is a function type?
5054 
5055   // If we don't have a class type in C++, there's no way we can get an
5056   // expression of integral or enumeration type.
5057   const RecordType *RecordTy = T->getAs<RecordType>();
5058   if (!RecordTy || !getLangOpts().CPlusPlus) {
5059     if (NotIntDiag.getDiagID())
5060       Diag(Loc, NotIntDiag) << T << From->getSourceRange();
5061     return Owned(From);
5062   }
5063 
5064   // We must have a complete class type.
5065   if (RequireCompleteType(Loc, T, IncompleteDiag))
5066     return Owned(From);
5067 
5068   // Look for a conversion to an integral or enumeration type.
5069   UnresolvedSet<4> ViableConversions;
5070   UnresolvedSet<4> ExplicitConversions;
5071   const UnresolvedSetImpl *Conversions
5072     = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5073 
5074   bool HadMultipleCandidates = (Conversions->size() > 1);
5075 
5076   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5077                                    E = Conversions->end();
5078        I != E;
5079        ++I) {
5080     if (CXXConversionDecl *Conversion
5081           = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5082       if (isIntegralOrEnumerationType(
5083             Conversion->getConversionType().getNonReferenceType(),
5084             AllowScopedEnumerations)) {
5085         if (Conversion->isExplicit())
5086           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5087         else
5088           ViableConversions.addDecl(I.getDecl(), I.getAccess());
5089       }
5090     }
5091   }
5092 
5093   switch (ViableConversions.size()) {
5094   case 0:
5095     if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
5096       DeclAccessPair Found = ExplicitConversions[0];
5097       CXXConversionDecl *Conversion
5098         = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5099 
5100       // The user probably meant to invoke the given explicit
5101       // conversion; use it.
5102       QualType ConvTy
5103         = Conversion->getConversionType().getNonReferenceType();
5104       std::string TypeStr;
5105       ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
5106 
5107       Diag(Loc, ExplicitConvDiag)
5108         << T << ConvTy
5109         << FixItHint::CreateInsertion(From->getLocStart(),
5110                                       "static_cast<" + TypeStr + ">(")
5111         << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5112                                       ")");
5113       Diag(Conversion->getLocation(), ExplicitConvNote)
5114         << ConvTy->isEnumeralType() << ConvTy;
5115 
5116       // If we aren't in a SFINAE context, build a call to the
5117       // explicit conversion function.
5118       if (isSFINAEContext())
5119         return ExprError();
5120 
5121       CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5122       ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5123                                                  HadMultipleCandidates);
5124       if (Result.isInvalid())
5125         return ExprError();
5126       // Record usage of conversion in an implicit cast.
5127       From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5128                                       CK_UserDefinedConversion,
5129                                       Result.get(), 0,
5130                                       Result.get()->getValueKind());
5131     }
5132 
5133     // We'll complain below about a non-integral condition type.
5134     break;
5135 
5136   case 1: {
5137     // Apply this conversion.
5138     DeclAccessPair Found = ViableConversions[0];
5139     CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5140 
5141     CXXConversionDecl *Conversion
5142       = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5143     QualType ConvTy
5144       = Conversion->getConversionType().getNonReferenceType();
5145     if (ConvDiag.getDiagID()) {
5146       if (isSFINAEContext())
5147         return ExprError();
5148 
5149       Diag(Loc, ConvDiag)
5150         << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5151     }
5152 
5153     ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5154                                                HadMultipleCandidates);
5155     if (Result.isInvalid())
5156       return ExprError();
5157     // Record usage of conversion in an implicit cast.
5158     From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5159                                     CK_UserDefinedConversion,
5160                                     Result.get(), 0,
5161                                     Result.get()->getValueKind());
5162     break;
5163   }
5164 
5165   default:
5166     if (!AmbigDiag.getDiagID())
5167       return Owned(From);
5168 
5169     Diag(Loc, AmbigDiag)
5170       << T << From->getSourceRange();
5171     for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5172       CXXConversionDecl *Conv
5173         = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5174       QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5175       Diag(Conv->getLocation(), AmbigNote)
5176         << ConvTy->isEnumeralType() << ConvTy;
5177     }
5178     return Owned(From);
5179   }
5180 
5181   if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5182       NotIntDiag.getDiagID())
5183     Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
5184 
5185   return DefaultLvalueConversion(From);
5186 }
5187 
5188 /// AddOverloadCandidate - Adds the given function to the set of
5189 /// candidate functions, using the given function call arguments.  If
5190 /// @p SuppressUserConversions, then don't allow user-defined
5191 /// conversions via constructors or conversion operators.
5192 ///
5193 /// \para PartialOverloading true if we are performing "partial" overloading
5194 /// based on an incomplete set of function arguments. This feature is used by
5195 /// code completion.
5196 void
AddOverloadCandidate(FunctionDecl * Function,DeclAccessPair FoundDecl,llvm::ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,bool PartialOverloading,bool AllowExplicit)5197 Sema::AddOverloadCandidate(FunctionDecl *Function,
5198                            DeclAccessPair FoundDecl,
5199                            llvm::ArrayRef<Expr *> Args,
5200                            OverloadCandidateSet& CandidateSet,
5201                            bool SuppressUserConversions,
5202                            bool PartialOverloading,
5203                            bool AllowExplicit) {
5204   const FunctionProtoType* Proto
5205     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5206   assert(Proto && "Functions without a prototype cannot be overloaded");
5207   assert(!Function->getDescribedFunctionTemplate() &&
5208          "Use AddTemplateOverloadCandidate for function templates");
5209 
5210   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5211     if (!isa<CXXConstructorDecl>(Method)) {
5212       // If we get here, it's because we're calling a member function
5213       // that is named without a member access expression (e.g.,
5214       // "this->f") that was either written explicitly or created
5215       // implicitly. This can happen with a qualified call to a member
5216       // function, e.g., X::f(). We use an empty type for the implied
5217       // object argument (C++ [over.call.func]p3), and the acting context
5218       // is irrelevant.
5219       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5220                          QualType(), Expr::Classification::makeSimpleLValue(),
5221                          Args, CandidateSet, SuppressUserConversions);
5222       return;
5223     }
5224     // We treat a constructor like a non-member function, since its object
5225     // argument doesn't participate in overload resolution.
5226   }
5227 
5228   if (!CandidateSet.isNewCandidate(Function))
5229     return;
5230 
5231   // Overload resolution is always an unevaluated context.
5232   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5233 
5234   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5235     // C++ [class.copy]p3:
5236     //   A member function template is never instantiated to perform the copy
5237     //   of a class object to an object of its class type.
5238     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5239     if (Args.size() == 1 &&
5240         Constructor->isSpecializationCopyingObject() &&
5241         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5242          IsDerivedFrom(Args[0]->getType(), ClassType)))
5243       return;
5244   }
5245 
5246   // Add this candidate
5247   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5248   Candidate.FoundDecl = FoundDecl;
5249   Candidate.Function = Function;
5250   Candidate.Viable = true;
5251   Candidate.IsSurrogate = false;
5252   Candidate.IgnoreObjectArgument = false;
5253   Candidate.ExplicitCallArguments = Args.size();
5254 
5255   unsigned NumArgsInProto = Proto->getNumArgs();
5256 
5257   // (C++ 13.3.2p2): A candidate function having fewer than m
5258   // parameters is viable only if it has an ellipsis in its parameter
5259   // list (8.3.5).
5260   if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
5261       !Proto->isVariadic()) {
5262     Candidate.Viable = false;
5263     Candidate.FailureKind = ovl_fail_too_many_arguments;
5264     return;
5265   }
5266 
5267   // (C++ 13.3.2p2): A candidate function having more than m parameters
5268   // is viable only if the (m+1)st parameter has a default argument
5269   // (8.3.6). For the purposes of overload resolution, the
5270   // parameter list is truncated on the right, so that there are
5271   // exactly m parameters.
5272   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5273   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5274     // Not enough arguments.
5275     Candidate.Viable = false;
5276     Candidate.FailureKind = ovl_fail_too_few_arguments;
5277     return;
5278   }
5279 
5280   // (CUDA B.1): Check for invalid calls between targets.
5281   if (getLangOpts().CUDA)
5282     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5283       if (CheckCUDATarget(Caller, Function)) {
5284         Candidate.Viable = false;
5285         Candidate.FailureKind = ovl_fail_bad_target;
5286         return;
5287       }
5288 
5289   // Determine the implicit conversion sequences for each of the
5290   // arguments.
5291   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5292     if (ArgIdx < NumArgsInProto) {
5293       // (C++ 13.3.2p3): for F to be a viable function, there shall
5294       // exist for each argument an implicit conversion sequence
5295       // (13.3.3.1) that converts that argument to the corresponding
5296       // parameter of F.
5297       QualType ParamType = Proto->getArgType(ArgIdx);
5298       Candidate.Conversions[ArgIdx]
5299         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5300                                 SuppressUserConversions,
5301                                 /*InOverloadResolution=*/true,
5302                                 /*AllowObjCWritebackConversion=*/
5303                                   getLangOpts().ObjCAutoRefCount,
5304                                 AllowExplicit);
5305       if (Candidate.Conversions[ArgIdx].isBad()) {
5306         Candidate.Viable = false;
5307         Candidate.FailureKind = ovl_fail_bad_conversion;
5308         break;
5309       }
5310     } else {
5311       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5312       // argument for which there is no corresponding parameter is
5313       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5314       Candidate.Conversions[ArgIdx].setEllipsis();
5315     }
5316   }
5317 }
5318 
5319 /// \brief Add all of the function declarations in the given function set to
5320 /// the overload canddiate set.
AddFunctionCandidates(const UnresolvedSetImpl & Fns,llvm::ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions,TemplateArgumentListInfo * ExplicitTemplateArgs)5321 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5322                                  llvm::ArrayRef<Expr *> Args,
5323                                  OverloadCandidateSet& CandidateSet,
5324                                  bool SuppressUserConversions,
5325                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
5326   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5327     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5328     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5329       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5330         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5331                            cast<CXXMethodDecl>(FD)->getParent(),
5332                            Args[0]->getType(), Args[0]->Classify(Context),
5333                            Args.slice(1), CandidateSet,
5334                            SuppressUserConversions);
5335       else
5336         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5337                              SuppressUserConversions);
5338     } else {
5339       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5340       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5341           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5342         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5343                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5344                                    ExplicitTemplateArgs,
5345                                    Args[0]->getType(),
5346                                    Args[0]->Classify(Context), Args.slice(1),
5347                                    CandidateSet, SuppressUserConversions);
5348       else
5349         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5350                                      ExplicitTemplateArgs, Args,
5351                                      CandidateSet, SuppressUserConversions);
5352     }
5353   }
5354 }
5355 
5356 /// AddMethodCandidate - Adds a named decl (which is some kind of
5357 /// method) as a method candidate to the given overload set.
AddMethodCandidate(DeclAccessPair FoundDecl,QualType ObjectType,Expr::Classification ObjectClassification,Expr ** Args,unsigned NumArgs,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5358 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5359                               QualType ObjectType,
5360                               Expr::Classification ObjectClassification,
5361                               Expr **Args, unsigned NumArgs,
5362                               OverloadCandidateSet& CandidateSet,
5363                               bool SuppressUserConversions) {
5364   NamedDecl *Decl = FoundDecl.getDecl();
5365   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5366 
5367   if (isa<UsingShadowDecl>(Decl))
5368     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5369 
5370   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5371     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5372            "Expected a member function template");
5373     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5374                                /*ExplicitArgs*/ 0,
5375                                ObjectType, ObjectClassification,
5376                                llvm::makeArrayRef(Args, NumArgs), CandidateSet,
5377                                SuppressUserConversions);
5378   } else {
5379     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5380                        ObjectType, ObjectClassification,
5381                        llvm::makeArrayRef(Args, NumArgs),
5382                        CandidateSet, SuppressUserConversions);
5383   }
5384 }
5385 
5386 /// AddMethodCandidate - Adds the given C++ member function to the set
5387 /// of candidate functions, using the given function call arguments
5388 /// and the object argument (@c Object). For example, in a call
5389 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5390 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5391 /// allow user-defined conversions via constructors or conversion
5392 /// operators.
5393 void
AddMethodCandidate(CXXMethodDecl * Method,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,QualType ObjectType,Expr::Classification ObjectClassification,llvm::ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5394 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5395                          CXXRecordDecl *ActingContext, QualType ObjectType,
5396                          Expr::Classification ObjectClassification,
5397                          llvm::ArrayRef<Expr *> Args,
5398                          OverloadCandidateSet& CandidateSet,
5399                          bool SuppressUserConversions) {
5400   const FunctionProtoType* Proto
5401     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5402   assert(Proto && "Methods without a prototype cannot be overloaded");
5403   assert(!isa<CXXConstructorDecl>(Method) &&
5404          "Use AddOverloadCandidate for constructors");
5405 
5406   if (!CandidateSet.isNewCandidate(Method))
5407     return;
5408 
5409   // Overload resolution is always an unevaluated context.
5410   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5411 
5412   // Add this candidate
5413   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5414   Candidate.FoundDecl = FoundDecl;
5415   Candidate.Function = Method;
5416   Candidate.IsSurrogate = false;
5417   Candidate.IgnoreObjectArgument = false;
5418   Candidate.ExplicitCallArguments = Args.size();
5419 
5420   unsigned NumArgsInProto = Proto->getNumArgs();
5421 
5422   // (C++ 13.3.2p2): A candidate function having fewer than m
5423   // parameters is viable only if it has an ellipsis in its parameter
5424   // list (8.3.5).
5425   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5426     Candidate.Viable = false;
5427     Candidate.FailureKind = ovl_fail_too_many_arguments;
5428     return;
5429   }
5430 
5431   // (C++ 13.3.2p2): A candidate function having more than m parameters
5432   // is viable only if the (m+1)st parameter has a default argument
5433   // (8.3.6). For the purposes of overload resolution, the
5434   // parameter list is truncated on the right, so that there are
5435   // exactly m parameters.
5436   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5437   if (Args.size() < MinRequiredArgs) {
5438     // Not enough arguments.
5439     Candidate.Viable = false;
5440     Candidate.FailureKind = ovl_fail_too_few_arguments;
5441     return;
5442   }
5443 
5444   Candidate.Viable = true;
5445 
5446   if (Method->isStatic() || ObjectType.isNull())
5447     // The implicit object argument is ignored.
5448     Candidate.IgnoreObjectArgument = true;
5449   else {
5450     // Determine the implicit conversion sequence for the object
5451     // parameter.
5452     Candidate.Conversions[0]
5453       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5454                                         Method, ActingContext);
5455     if (Candidate.Conversions[0].isBad()) {
5456       Candidate.Viable = false;
5457       Candidate.FailureKind = ovl_fail_bad_conversion;
5458       return;
5459     }
5460   }
5461 
5462   // Determine the implicit conversion sequences for each of the
5463   // arguments.
5464   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5465     if (ArgIdx < NumArgsInProto) {
5466       // (C++ 13.3.2p3): for F to be a viable function, there shall
5467       // exist for each argument an implicit conversion sequence
5468       // (13.3.3.1) that converts that argument to the corresponding
5469       // parameter of F.
5470       QualType ParamType = Proto->getArgType(ArgIdx);
5471       Candidate.Conversions[ArgIdx + 1]
5472         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5473                                 SuppressUserConversions,
5474                                 /*InOverloadResolution=*/true,
5475                                 /*AllowObjCWritebackConversion=*/
5476                                   getLangOpts().ObjCAutoRefCount);
5477       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5478         Candidate.Viable = false;
5479         Candidate.FailureKind = ovl_fail_bad_conversion;
5480         break;
5481       }
5482     } else {
5483       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5484       // argument for which there is no corresponding parameter is
5485       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5486       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5487     }
5488   }
5489 }
5490 
5491 /// \brief Add a C++ member function template as a candidate to the candidate
5492 /// set, using template argument deduction to produce an appropriate member
5493 /// function template specialization.
5494 void
AddMethodTemplateCandidate(FunctionTemplateDecl * MethodTmpl,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,TemplateArgumentListInfo * ExplicitTemplateArgs,QualType ObjectType,Expr::Classification ObjectClassification,llvm::ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5495 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5496                                  DeclAccessPair FoundDecl,
5497                                  CXXRecordDecl *ActingContext,
5498                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5499                                  QualType ObjectType,
5500                                  Expr::Classification ObjectClassification,
5501                                  llvm::ArrayRef<Expr *> Args,
5502                                  OverloadCandidateSet& CandidateSet,
5503                                  bool SuppressUserConversions) {
5504   if (!CandidateSet.isNewCandidate(MethodTmpl))
5505     return;
5506 
5507   // C++ [over.match.funcs]p7:
5508   //   In each case where a candidate is a function template, candidate
5509   //   function template specializations are generated using template argument
5510   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5511   //   candidate functions in the usual way.113) A given name can refer to one
5512   //   or more function templates and also to a set of overloaded non-template
5513   //   functions. In such a case, the candidate functions generated from each
5514   //   function template are combined with the set of non-template candidate
5515   //   functions.
5516   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5517   FunctionDecl *Specialization = 0;
5518   if (TemplateDeductionResult Result
5519       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5520                                 Specialization, Info)) {
5521     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5522     Candidate.FoundDecl = FoundDecl;
5523     Candidate.Function = MethodTmpl->getTemplatedDecl();
5524     Candidate.Viable = false;
5525     Candidate.FailureKind = ovl_fail_bad_deduction;
5526     Candidate.IsSurrogate = false;
5527     Candidate.IgnoreObjectArgument = false;
5528     Candidate.ExplicitCallArguments = Args.size();
5529     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5530                                                           Info);
5531     return;
5532   }
5533 
5534   // Add the function template specialization produced by template argument
5535   // deduction as a candidate.
5536   assert(Specialization && "Missing member function template specialization?");
5537   assert(isa<CXXMethodDecl>(Specialization) &&
5538          "Specialization is not a member function?");
5539   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5540                      ActingContext, ObjectType, ObjectClassification, Args,
5541                      CandidateSet, SuppressUserConversions);
5542 }
5543 
5544 /// \brief Add a C++ function template specialization as a candidate
5545 /// in the candidate set, using template argument deduction to produce
5546 /// an appropriate function template specialization.
5547 void
AddTemplateOverloadCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,llvm::ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool SuppressUserConversions)5548 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5549                                    DeclAccessPair FoundDecl,
5550                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
5551                                    llvm::ArrayRef<Expr *> Args,
5552                                    OverloadCandidateSet& CandidateSet,
5553                                    bool SuppressUserConversions) {
5554   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5555     return;
5556 
5557   // C++ [over.match.funcs]p7:
5558   //   In each case where a candidate is a function template, candidate
5559   //   function template specializations are generated using template argument
5560   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
5561   //   candidate functions in the usual way.113) A given name can refer to one
5562   //   or more function templates and also to a set of overloaded non-template
5563   //   functions. In such a case, the candidate functions generated from each
5564   //   function template are combined with the set of non-template candidate
5565   //   functions.
5566   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5567   FunctionDecl *Specialization = 0;
5568   if (TemplateDeductionResult Result
5569         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5570                                   Specialization, Info)) {
5571     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5572     Candidate.FoundDecl = FoundDecl;
5573     Candidate.Function = FunctionTemplate->getTemplatedDecl();
5574     Candidate.Viable = false;
5575     Candidate.FailureKind = ovl_fail_bad_deduction;
5576     Candidate.IsSurrogate = false;
5577     Candidate.IgnoreObjectArgument = false;
5578     Candidate.ExplicitCallArguments = Args.size();
5579     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5580                                                           Info);
5581     return;
5582   }
5583 
5584   // Add the function template specialization produced by template argument
5585   // deduction as a candidate.
5586   assert(Specialization && "Missing function template specialization?");
5587   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
5588                        SuppressUserConversions);
5589 }
5590 
5591 /// AddConversionCandidate - Add a C++ conversion function as a
5592 /// candidate in the candidate set (C++ [over.match.conv],
5593 /// C++ [over.match.copy]). From is the expression we're converting from,
5594 /// and ToType is the type that we're eventually trying to convert to
5595 /// (which may or may not be the same type as the type that the
5596 /// conversion function produces).
5597 void
AddConversionCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet)5598 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
5599                              DeclAccessPair FoundDecl,
5600                              CXXRecordDecl *ActingContext,
5601                              Expr *From, QualType ToType,
5602                              OverloadCandidateSet& CandidateSet) {
5603   assert(!Conversion->getDescribedFunctionTemplate() &&
5604          "Conversion function templates use AddTemplateConversionCandidate");
5605   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
5606   if (!CandidateSet.isNewCandidate(Conversion))
5607     return;
5608 
5609   // Overload resolution is always an unevaluated context.
5610   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5611 
5612   // Add this candidate
5613   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
5614   Candidate.FoundDecl = FoundDecl;
5615   Candidate.Function = Conversion;
5616   Candidate.IsSurrogate = false;
5617   Candidate.IgnoreObjectArgument = false;
5618   Candidate.FinalConversion.setAsIdentityConversion();
5619   Candidate.FinalConversion.setFromType(ConvType);
5620   Candidate.FinalConversion.setAllToTypes(ToType);
5621   Candidate.Viable = true;
5622   Candidate.ExplicitCallArguments = 1;
5623 
5624   // C++ [over.match.funcs]p4:
5625   //   For conversion functions, the function is considered to be a member of
5626   //   the class of the implicit implied object argument for the purpose of
5627   //   defining the type of the implicit object parameter.
5628   //
5629   // Determine the implicit conversion sequence for the implicit
5630   // object parameter.
5631   QualType ImplicitParamType = From->getType();
5632   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5633     ImplicitParamType = FromPtrType->getPointeeType();
5634   CXXRecordDecl *ConversionContext
5635     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
5636 
5637   Candidate.Conversions[0]
5638     = TryObjectArgumentInitialization(*this, From->getType(),
5639                                       From->Classify(Context),
5640                                       Conversion, ConversionContext);
5641 
5642   if (Candidate.Conversions[0].isBad()) {
5643     Candidate.Viable = false;
5644     Candidate.FailureKind = ovl_fail_bad_conversion;
5645     return;
5646   }
5647 
5648   // We won't go through a user-define type conversion function to convert a
5649   // derived to base as such conversions are given Conversion Rank. They only
5650   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5651   QualType FromCanon
5652     = Context.getCanonicalType(From->getType().getUnqualifiedType());
5653   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5654   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5655     Candidate.Viable = false;
5656     Candidate.FailureKind = ovl_fail_trivial_conversion;
5657     return;
5658   }
5659 
5660   // To determine what the conversion from the result of calling the
5661   // conversion function to the type we're eventually trying to
5662   // convert to (ToType), we need to synthesize a call to the
5663   // conversion function and attempt copy initialization from it. This
5664   // makes sure that we get the right semantics with respect to
5665   // lvalues/rvalues and the type. Fortunately, we can allocate this
5666   // call on the stack and we don't need its arguments to be
5667   // well-formed.
5668   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
5669                             VK_LValue, From->getLocStart());
5670   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5671                                 Context.getPointerType(Conversion->getType()),
5672                                 CK_FunctionToPointerDecay,
5673                                 &ConversionRef, VK_RValue);
5674 
5675   QualType ConversionType = Conversion->getConversionType();
5676   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
5677     Candidate.Viable = false;
5678     Candidate.FailureKind = ovl_fail_bad_final_conversion;
5679     return;
5680   }
5681 
5682   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
5683 
5684   // Note that it is safe to allocate CallExpr on the stack here because
5685   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5686   // allocator).
5687   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
5688   CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
5689                 From->getLocStart());
5690   ImplicitConversionSequence ICS =
5691     TryCopyInitialization(*this, &Call, ToType,
5692                           /*SuppressUserConversions=*/true,
5693                           /*InOverloadResolution=*/false,
5694                           /*AllowObjCWritebackConversion=*/false);
5695 
5696   switch (ICS.getKind()) {
5697   case ImplicitConversionSequence::StandardConversion:
5698     Candidate.FinalConversion = ICS.Standard;
5699 
5700     // C++ [over.ics.user]p3:
5701     //   If the user-defined conversion is specified by a specialization of a
5702     //   conversion function template, the second standard conversion sequence
5703     //   shall have exact match rank.
5704     if (Conversion->getPrimaryTemplate() &&
5705         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5706       Candidate.Viable = false;
5707       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5708     }
5709 
5710     // C++0x [dcl.init.ref]p5:
5711     //    In the second case, if the reference is an rvalue reference and
5712     //    the second standard conversion sequence of the user-defined
5713     //    conversion sequence includes an lvalue-to-rvalue conversion, the
5714     //    program is ill-formed.
5715     if (ToType->isRValueReferenceType() &&
5716         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5717       Candidate.Viable = false;
5718       Candidate.FailureKind = ovl_fail_bad_final_conversion;
5719     }
5720     break;
5721 
5722   case ImplicitConversionSequence::BadConversion:
5723     Candidate.Viable = false;
5724     Candidate.FailureKind = ovl_fail_bad_final_conversion;
5725     break;
5726 
5727   default:
5728     llvm_unreachable(
5729            "Can only end up with a standard conversion sequence or failure");
5730   }
5731 }
5732 
5733 /// \brief Adds a conversion function template specialization
5734 /// candidate to the overload set, using template argument deduction
5735 /// to deduce the template arguments of the conversion function
5736 /// template from the type that we are converting to (C++
5737 /// [temp.deduct.conv]).
5738 void
AddTemplateConversionCandidate(FunctionTemplateDecl * FunctionTemplate,DeclAccessPair FoundDecl,CXXRecordDecl * ActingDC,Expr * From,QualType ToType,OverloadCandidateSet & CandidateSet)5739 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
5740                                      DeclAccessPair FoundDecl,
5741                                      CXXRecordDecl *ActingDC,
5742                                      Expr *From, QualType ToType,
5743                                      OverloadCandidateSet &CandidateSet) {
5744   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5745          "Only conversion function templates permitted here");
5746 
5747   if (!CandidateSet.isNewCandidate(FunctionTemplate))
5748     return;
5749 
5750   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
5751   CXXConversionDecl *Specialization = 0;
5752   if (TemplateDeductionResult Result
5753         = DeduceTemplateArguments(FunctionTemplate, ToType,
5754                                   Specialization, Info)) {
5755     OverloadCandidate &Candidate = CandidateSet.addCandidate();
5756     Candidate.FoundDecl = FoundDecl;
5757     Candidate.Function = FunctionTemplate->getTemplatedDecl();
5758     Candidate.Viable = false;
5759     Candidate.FailureKind = ovl_fail_bad_deduction;
5760     Candidate.IsSurrogate = false;
5761     Candidate.IgnoreObjectArgument = false;
5762     Candidate.ExplicitCallArguments = 1;
5763     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5764                                                           Info);
5765     return;
5766   }
5767 
5768   // Add the conversion function template specialization produced by
5769   // template argument deduction as a candidate.
5770   assert(Specialization && "Missing function template specialization?");
5771   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
5772                          CandidateSet);
5773 }
5774 
5775 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5776 /// converts the given @c Object to a function pointer via the
5777 /// conversion function @c Conversion, and then attempts to call it
5778 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
5779 /// the type of function that we'll eventually be calling.
AddSurrogateCandidate(CXXConversionDecl * Conversion,DeclAccessPair FoundDecl,CXXRecordDecl * ActingContext,const FunctionProtoType * Proto,Expr * Object,llvm::ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet)5780 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
5781                                  DeclAccessPair FoundDecl,
5782                                  CXXRecordDecl *ActingContext,
5783                                  const FunctionProtoType *Proto,
5784                                  Expr *Object,
5785                                  llvm::ArrayRef<Expr *> Args,
5786                                  OverloadCandidateSet& CandidateSet) {
5787   if (!CandidateSet.isNewCandidate(Conversion))
5788     return;
5789 
5790   // Overload resolution is always an unevaluated context.
5791   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5792 
5793   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5794   Candidate.FoundDecl = FoundDecl;
5795   Candidate.Function = 0;
5796   Candidate.Surrogate = Conversion;
5797   Candidate.Viable = true;
5798   Candidate.IsSurrogate = true;
5799   Candidate.IgnoreObjectArgument = false;
5800   Candidate.ExplicitCallArguments = Args.size();
5801 
5802   // Determine the implicit conversion sequence for the implicit
5803   // object parameter.
5804   ImplicitConversionSequence ObjectInit
5805     = TryObjectArgumentInitialization(*this, Object->getType(),
5806                                       Object->Classify(Context),
5807                                       Conversion, ActingContext);
5808   if (ObjectInit.isBad()) {
5809     Candidate.Viable = false;
5810     Candidate.FailureKind = ovl_fail_bad_conversion;
5811     Candidate.Conversions[0] = ObjectInit;
5812     return;
5813   }
5814 
5815   // The first conversion is actually a user-defined conversion whose
5816   // first conversion is ObjectInit's standard conversion (which is
5817   // effectively a reference binding). Record it as such.
5818   Candidate.Conversions[0].setUserDefined();
5819   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
5820   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
5821   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
5822   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
5823   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
5824   Candidate.Conversions[0].UserDefined.After
5825     = Candidate.Conversions[0].UserDefined.Before;
5826   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5827 
5828   // Find the
5829   unsigned NumArgsInProto = Proto->getNumArgs();
5830 
5831   // (C++ 13.3.2p2): A candidate function having fewer than m
5832   // parameters is viable only if it has an ellipsis in its parameter
5833   // list (8.3.5).
5834   if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
5835     Candidate.Viable = false;
5836     Candidate.FailureKind = ovl_fail_too_many_arguments;
5837     return;
5838   }
5839 
5840   // Function types don't have any default arguments, so just check if
5841   // we have enough arguments.
5842   if (Args.size() < NumArgsInProto) {
5843     // Not enough arguments.
5844     Candidate.Viable = false;
5845     Candidate.FailureKind = ovl_fail_too_few_arguments;
5846     return;
5847   }
5848 
5849   // Determine the implicit conversion sequences for each of the
5850   // arguments.
5851   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5852     if (ArgIdx < NumArgsInProto) {
5853       // (C++ 13.3.2p3): for F to be a viable function, there shall
5854       // exist for each argument an implicit conversion sequence
5855       // (13.3.3.1) that converts that argument to the corresponding
5856       // parameter of F.
5857       QualType ParamType = Proto->getArgType(ArgIdx);
5858       Candidate.Conversions[ArgIdx + 1]
5859         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5860                                 /*SuppressUserConversions=*/false,
5861                                 /*InOverloadResolution=*/false,
5862                                 /*AllowObjCWritebackConversion=*/
5863                                   getLangOpts().ObjCAutoRefCount);
5864       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5865         Candidate.Viable = false;
5866         Candidate.FailureKind = ovl_fail_bad_conversion;
5867         break;
5868       }
5869     } else {
5870       // (C++ 13.3.2p2): For the purposes of overload resolution, any
5871       // argument for which there is no corresponding parameter is
5872       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5873       Candidate.Conversions[ArgIdx + 1].setEllipsis();
5874     }
5875   }
5876 }
5877 
5878 /// \brief Add overload candidates for overloaded operators that are
5879 /// member functions.
5880 ///
5881 /// Add the overloaded operator candidates that are member functions
5882 /// for the operator Op that was used in an operator expression such
5883 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
5884 /// CandidateSet will store the added overload candidates. (C++
5885 /// [over.match.oper]).
AddMemberOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,Expr ** Args,unsigned NumArgs,OverloadCandidateSet & CandidateSet,SourceRange OpRange)5886 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5887                                        SourceLocation OpLoc,
5888                                        Expr **Args, unsigned NumArgs,
5889                                        OverloadCandidateSet& CandidateSet,
5890                                        SourceRange OpRange) {
5891   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5892 
5893   // C++ [over.match.oper]p3:
5894   //   For a unary operator @ with an operand of a type whose
5895   //   cv-unqualified version is T1, and for a binary operator @ with
5896   //   a left operand of a type whose cv-unqualified version is T1 and
5897   //   a right operand of a type whose cv-unqualified version is T2,
5898   //   three sets of candidate functions, designated member
5899   //   candidates, non-member candidates and built-in candidates, are
5900   //   constructed as follows:
5901   QualType T1 = Args[0]->getType();
5902 
5903   //     -- If T1 is a class type, the set of member candidates is the
5904   //        result of the qualified lookup of T1::operator@
5905   //        (13.3.1.1.1); otherwise, the set of member candidates is
5906   //        empty.
5907   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
5908     // Complete the type if it can be completed. Otherwise, we're done.
5909     if (RequireCompleteType(OpLoc, T1, PDiag()))
5910       return;
5911 
5912     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5913     LookupQualifiedName(Operators, T1Rec->getDecl());
5914     Operators.suppressDiagnostics();
5915 
5916     for (LookupResult::iterator Oper = Operators.begin(),
5917                              OperEnd = Operators.end();
5918          Oper != OperEnd;
5919          ++Oper)
5920       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
5921                          Args[0]->Classify(Context), Args + 1, NumArgs - 1,
5922                          CandidateSet,
5923                          /* SuppressUserConversions = */ false);
5924   }
5925 }
5926 
5927 /// AddBuiltinCandidate - Add a candidate for a built-in
5928 /// operator. ResultTy and ParamTys are the result and parameter types
5929 /// of the built-in candidate, respectively. Args and NumArgs are the
5930 /// arguments being passed to the candidate. IsAssignmentOperator
5931 /// should be true when this built-in candidate is an assignment
5932 /// operator. NumContextualBoolArguments is the number of arguments
5933 /// (at the beginning of the argument list) that will be contextually
5934 /// converted to bool.
AddBuiltinCandidate(QualType ResultTy,QualType * ParamTys,Expr ** Args,unsigned NumArgs,OverloadCandidateSet & CandidateSet,bool IsAssignmentOperator,unsigned NumContextualBoolArguments)5935 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
5936                                Expr **Args, unsigned NumArgs,
5937                                OverloadCandidateSet& CandidateSet,
5938                                bool IsAssignmentOperator,
5939                                unsigned NumContextualBoolArguments) {
5940   // Overload resolution is always an unevaluated context.
5941   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5942 
5943   // Add this candidate
5944   OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
5945   Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
5946   Candidate.Function = 0;
5947   Candidate.IsSurrogate = false;
5948   Candidate.IgnoreObjectArgument = false;
5949   Candidate.BuiltinTypes.ResultTy = ResultTy;
5950   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5951     Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5952 
5953   // Determine the implicit conversion sequences for each of the
5954   // arguments.
5955   Candidate.Viable = true;
5956   Candidate.ExplicitCallArguments = NumArgs;
5957   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5958     // C++ [over.match.oper]p4:
5959     //   For the built-in assignment operators, conversions of the
5960     //   left operand are restricted as follows:
5961     //     -- no temporaries are introduced to hold the left operand, and
5962     //     -- no user-defined conversions are applied to the left
5963     //        operand to achieve a type match with the left-most
5964     //        parameter of a built-in candidate.
5965     //
5966     // We block these conversions by turning off user-defined
5967     // conversions, since that is the only way that initialization of
5968     // a reference to a non-class type can occur from something that
5969     // is not of the same type.
5970     if (ArgIdx < NumContextualBoolArguments) {
5971       assert(ParamTys[ArgIdx] == Context.BoolTy &&
5972              "Contextual conversion to bool requires bool type");
5973       Candidate.Conversions[ArgIdx]
5974         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
5975     } else {
5976       Candidate.Conversions[ArgIdx]
5977         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
5978                                 ArgIdx == 0 && IsAssignmentOperator,
5979                                 /*InOverloadResolution=*/false,
5980                                 /*AllowObjCWritebackConversion=*/
5981                                   getLangOpts().ObjCAutoRefCount);
5982     }
5983     if (Candidate.Conversions[ArgIdx].isBad()) {
5984       Candidate.Viable = false;
5985       Candidate.FailureKind = ovl_fail_bad_conversion;
5986       break;
5987     }
5988   }
5989 }
5990 
5991 /// BuiltinCandidateTypeSet - A set of types that will be used for the
5992 /// candidate operator functions for built-in operators (C++
5993 /// [over.built]). The types are separated into pointer types and
5994 /// enumeration types.
5995 class BuiltinCandidateTypeSet  {
5996   /// TypeSet - A set of types.
5997   typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
5998 
5999   /// PointerTypes - The set of pointer types that will be used in the
6000   /// built-in candidates.
6001   TypeSet PointerTypes;
6002 
6003   /// MemberPointerTypes - The set of member pointer types that will be
6004   /// used in the built-in candidates.
6005   TypeSet MemberPointerTypes;
6006 
6007   /// EnumerationTypes - The set of enumeration types that will be
6008   /// used in the built-in candidates.
6009   TypeSet EnumerationTypes;
6010 
6011   /// \brief The set of vector types that will be used in the built-in
6012   /// candidates.
6013   TypeSet VectorTypes;
6014 
6015   /// \brief A flag indicating non-record types are viable candidates
6016   bool HasNonRecordTypes;
6017 
6018   /// \brief A flag indicating whether either arithmetic or enumeration types
6019   /// were present in the candidate set.
6020   bool HasArithmeticOrEnumeralTypes;
6021 
6022   /// \brief A flag indicating whether the nullptr type was present in the
6023   /// candidate set.
6024   bool HasNullPtrType;
6025 
6026   /// Sema - The semantic analysis instance where we are building the
6027   /// candidate type set.
6028   Sema &SemaRef;
6029 
6030   /// Context - The AST context in which we will build the type sets.
6031   ASTContext &Context;
6032 
6033   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6034                                                const Qualifiers &VisibleQuals);
6035   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6036 
6037 public:
6038   /// iterator - Iterates through the types that are part of the set.
6039   typedef TypeSet::iterator iterator;
6040 
BuiltinCandidateTypeSet(Sema & SemaRef)6041   BuiltinCandidateTypeSet(Sema &SemaRef)
6042     : HasNonRecordTypes(false),
6043       HasArithmeticOrEnumeralTypes(false),
6044       HasNullPtrType(false),
6045       SemaRef(SemaRef),
6046       Context(SemaRef.Context) { }
6047 
6048   void AddTypesConvertedFrom(QualType Ty,
6049                              SourceLocation Loc,
6050                              bool AllowUserConversions,
6051                              bool AllowExplicitConversions,
6052                              const Qualifiers &VisibleTypeConversionsQuals);
6053 
6054   /// pointer_begin - First pointer type found;
pointer_begin()6055   iterator pointer_begin() { return PointerTypes.begin(); }
6056 
6057   /// pointer_end - Past the last pointer type found;
pointer_end()6058   iterator pointer_end() { return PointerTypes.end(); }
6059 
6060   /// member_pointer_begin - First member pointer type found;
member_pointer_begin()6061   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6062 
6063   /// member_pointer_end - Past the last member pointer type found;
member_pointer_end()6064   iterator member_pointer_end() { return MemberPointerTypes.end(); }
6065 
6066   /// enumeration_begin - First enumeration type found;
enumeration_begin()6067   iterator enumeration_begin() { return EnumerationTypes.begin(); }
6068 
6069   /// enumeration_end - Past the last enumeration type found;
enumeration_end()6070   iterator enumeration_end() { return EnumerationTypes.end(); }
6071 
vector_begin()6072   iterator vector_begin() { return VectorTypes.begin(); }
vector_end()6073   iterator vector_end() { return VectorTypes.end(); }
6074 
hasNonRecordTypes()6075   bool hasNonRecordTypes() { return HasNonRecordTypes; }
hasArithmeticOrEnumeralTypes()6076   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
hasNullPtrType() const6077   bool hasNullPtrType() const { return HasNullPtrType; }
6078 };
6079 
6080 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6081 /// the set of pointer types along with any more-qualified variants of
6082 /// that type. For example, if @p Ty is "int const *", this routine
6083 /// will add "int const *", "int const volatile *", "int const
6084 /// restrict *", and "int const volatile restrict *" to the set of
6085 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6086 /// false otherwise.
6087 ///
6088 /// FIXME: what to do about extended qualifiers?
6089 bool
AddPointerWithMoreQualifiedTypeVariants(QualType Ty,const Qualifiers & VisibleQuals)6090 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6091                                              const Qualifiers &VisibleQuals) {
6092 
6093   // Insert this type.
6094   if (!PointerTypes.insert(Ty))
6095     return false;
6096 
6097   QualType PointeeTy;
6098   const PointerType *PointerTy = Ty->getAs<PointerType>();
6099   bool buildObjCPtr = false;
6100   if (!PointerTy) {
6101     if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
6102       PointeeTy = PTy->getPointeeType();
6103       buildObjCPtr = true;
6104     }
6105     else
6106       llvm_unreachable("type was not a pointer type!");
6107   }
6108   else
6109     PointeeTy = PointerTy->getPointeeType();
6110 
6111   // Don't add qualified variants of arrays. For one, they're not allowed
6112   // (the qualifier would sink to the element type), and for another, the
6113   // only overload situation where it matters is subscript or pointer +- int,
6114   // and those shouldn't have qualifier variants anyway.
6115   if (PointeeTy->isArrayType())
6116     return true;
6117   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6118   if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
6119     BaseCVR = Array->getElementType().getCVRQualifiers();
6120   bool hasVolatile = VisibleQuals.hasVolatile();
6121   bool hasRestrict = VisibleQuals.hasRestrict();
6122 
6123   // Iterate through all strict supersets of BaseCVR.
6124   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6125     if ((CVR | BaseCVR) != CVR) continue;
6126     // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6127     // in the types.
6128     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6129     if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
6130     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6131     if (!buildObjCPtr)
6132       PointerTypes.insert(Context.getPointerType(QPointeeTy));
6133     else
6134       PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
6135   }
6136 
6137   return true;
6138 }
6139 
6140 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6141 /// to the set of pointer types along with any more-qualified variants of
6142 /// that type. For example, if @p Ty is "int const *", this routine
6143 /// will add "int const *", "int const volatile *", "int const
6144 /// restrict *", and "int const volatile restrict *" to the set of
6145 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6146 /// false otherwise.
6147 ///
6148 /// FIXME: what to do about extended qualifiers?
6149 bool
AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty)6150 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6151     QualType Ty) {
6152   // Insert this type.
6153   if (!MemberPointerTypes.insert(Ty))
6154     return false;
6155 
6156   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6157   assert(PointerTy && "type was not a member pointer type!");
6158 
6159   QualType PointeeTy = PointerTy->getPointeeType();
6160   // Don't add qualified variants of arrays. For one, they're not allowed
6161   // (the qualifier would sink to the element type), and for another, the
6162   // only overload situation where it matters is subscript or pointer +- int,
6163   // and those shouldn't have qualifier variants anyway.
6164   if (PointeeTy->isArrayType())
6165     return true;
6166   const Type *ClassTy = PointerTy->getClass();
6167 
6168   // Iterate through all strict supersets of the pointee type's CVR
6169   // qualifiers.
6170   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6171   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6172     if ((CVR | BaseCVR) != CVR) continue;
6173 
6174     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6175     MemberPointerTypes.insert(
6176       Context.getMemberPointerType(QPointeeTy, ClassTy));
6177   }
6178 
6179   return true;
6180 }
6181 
6182 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6183 /// Ty can be implicit converted to the given set of @p Types. We're
6184 /// primarily interested in pointer types and enumeration types. We also
6185 /// take member pointer types, for the conditional operator.
6186 /// AllowUserConversions is true if we should look at the conversion
6187 /// functions of a class type, and AllowExplicitConversions if we
6188 /// should also include the explicit conversion functions of a class
6189 /// type.
6190 void
AddTypesConvertedFrom(QualType Ty,SourceLocation Loc,bool AllowUserConversions,bool AllowExplicitConversions,const Qualifiers & VisibleQuals)6191 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6192                                                SourceLocation Loc,
6193                                                bool AllowUserConversions,
6194                                                bool AllowExplicitConversions,
6195                                                const Qualifiers &VisibleQuals) {
6196   // Only deal with canonical types.
6197   Ty = Context.getCanonicalType(Ty);
6198 
6199   // Look through reference types; they aren't part of the type of an
6200   // expression for the purposes of conversions.
6201   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6202     Ty = RefTy->getPointeeType();
6203 
6204   // If we're dealing with an array type, decay to the pointer.
6205   if (Ty->isArrayType())
6206     Ty = SemaRef.Context.getArrayDecayedType(Ty);
6207 
6208   // Otherwise, we don't care about qualifiers on the type.
6209   Ty = Ty.getLocalUnqualifiedType();
6210 
6211   // Flag if we ever add a non-record type.
6212   const RecordType *TyRec = Ty->getAs<RecordType>();
6213   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6214 
6215   // Flag if we encounter an arithmetic type.
6216   HasArithmeticOrEnumeralTypes =
6217     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6218 
6219   if (Ty->isObjCIdType() || Ty->isObjCClassType())
6220     PointerTypes.insert(Ty);
6221   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6222     // Insert our type, and its more-qualified variants, into the set
6223     // of types.
6224     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6225       return;
6226   } else if (Ty->isMemberPointerType()) {
6227     // Member pointers are far easier, since the pointee can't be converted.
6228     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6229       return;
6230   } else if (Ty->isEnumeralType()) {
6231     HasArithmeticOrEnumeralTypes = true;
6232     EnumerationTypes.insert(Ty);
6233   } else if (Ty->isVectorType()) {
6234     // We treat vector types as arithmetic types in many contexts as an
6235     // extension.
6236     HasArithmeticOrEnumeralTypes = true;
6237     VectorTypes.insert(Ty);
6238   } else if (Ty->isNullPtrType()) {
6239     HasNullPtrType = true;
6240   } else if (AllowUserConversions && TyRec) {
6241     // No conversion functions in incomplete types.
6242     if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6243       return;
6244 
6245     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6246     const UnresolvedSetImpl *Conversions
6247       = ClassDecl->getVisibleConversionFunctions();
6248     for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6249            E = Conversions->end(); I != E; ++I) {
6250       NamedDecl *D = I.getDecl();
6251       if (isa<UsingShadowDecl>(D))
6252         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6253 
6254       // Skip conversion function templates; they don't tell us anything
6255       // about which builtin types we can convert to.
6256       if (isa<FunctionTemplateDecl>(D))
6257         continue;
6258 
6259       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6260       if (AllowExplicitConversions || !Conv->isExplicit()) {
6261         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6262                               VisibleQuals);
6263       }
6264     }
6265   }
6266 }
6267 
6268 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6269 /// the volatile- and non-volatile-qualified assignment operators for the
6270 /// given type to the candidate set.
AddBuiltinAssignmentOperatorCandidates(Sema & S,QualType T,Expr ** Args,unsigned NumArgs,OverloadCandidateSet & CandidateSet)6271 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6272                                                    QualType T,
6273                                                    Expr **Args,
6274                                                    unsigned NumArgs,
6275                                     OverloadCandidateSet &CandidateSet) {
6276   QualType ParamTypes[2];
6277 
6278   // T& operator=(T&, T)
6279   ParamTypes[0] = S.Context.getLValueReferenceType(T);
6280   ParamTypes[1] = T;
6281   S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6282                         /*IsAssignmentOperator=*/true);
6283 
6284   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6285     // volatile T& operator=(volatile T&, T)
6286     ParamTypes[0]
6287       = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6288     ParamTypes[1] = T;
6289     S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6290                           /*IsAssignmentOperator=*/true);
6291   }
6292 }
6293 
6294 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6295 /// if any, found in visible type conversion functions found in ArgExpr's type.
CollectVRQualifiers(ASTContext & Context,Expr * ArgExpr)6296 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6297     Qualifiers VRQuals;
6298     const RecordType *TyRec;
6299     if (const MemberPointerType *RHSMPType =
6300         ArgExpr->getType()->getAs<MemberPointerType>())
6301       TyRec = RHSMPType->getClass()->getAs<RecordType>();
6302     else
6303       TyRec = ArgExpr->getType()->getAs<RecordType>();
6304     if (!TyRec) {
6305       // Just to be safe, assume the worst case.
6306       VRQuals.addVolatile();
6307       VRQuals.addRestrict();
6308       return VRQuals;
6309     }
6310 
6311     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6312     if (!ClassDecl->hasDefinition())
6313       return VRQuals;
6314 
6315     const UnresolvedSetImpl *Conversions =
6316       ClassDecl->getVisibleConversionFunctions();
6317 
6318     for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6319            E = Conversions->end(); I != E; ++I) {
6320       NamedDecl *D = I.getDecl();
6321       if (isa<UsingShadowDecl>(D))
6322         D = cast<UsingShadowDecl>(D)->getTargetDecl();
6323       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6324         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6325         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6326           CanTy = ResTypeRef->getPointeeType();
6327         // Need to go down the pointer/mempointer chain and add qualifiers
6328         // as see them.
6329         bool done = false;
6330         while (!done) {
6331           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6332             CanTy = ResTypePtr->getPointeeType();
6333           else if (const MemberPointerType *ResTypeMPtr =
6334                 CanTy->getAs<MemberPointerType>())
6335             CanTy = ResTypeMPtr->getPointeeType();
6336           else
6337             done = true;
6338           if (CanTy.isVolatileQualified())
6339             VRQuals.addVolatile();
6340           if (CanTy.isRestrictQualified())
6341             VRQuals.addRestrict();
6342           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6343             return VRQuals;
6344         }
6345       }
6346     }
6347     return VRQuals;
6348 }
6349 
6350 namespace {
6351 
6352 /// \brief Helper class to manage the addition of builtin operator overload
6353 /// candidates. It provides shared state and utility methods used throughout
6354 /// the process, as well as a helper method to add each group of builtin
6355 /// operator overloads from the standard to a candidate set.
6356 class BuiltinOperatorOverloadBuilder {
6357   // Common instance state available to all overload candidate addition methods.
6358   Sema &S;
6359   Expr **Args;
6360   unsigned NumArgs;
6361   Qualifiers VisibleTypeConversionsQuals;
6362   bool HasArithmeticOrEnumeralCandidateType;
6363   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6364   OverloadCandidateSet &CandidateSet;
6365 
6366   // Define some constants used to index and iterate over the arithemetic types
6367   // provided via the getArithmeticType() method below.
6368   // The "promoted arithmetic types" are the arithmetic
6369   // types are that preserved by promotion (C++ [over.built]p2).
6370   static const unsigned FirstIntegralType = 3;
6371   static const unsigned LastIntegralType = 18;
6372   static const unsigned FirstPromotedIntegralType = 3,
6373                         LastPromotedIntegralType = 9;
6374   static const unsigned FirstPromotedArithmeticType = 0,
6375                         LastPromotedArithmeticType = 9;
6376   static const unsigned NumArithmeticTypes = 18;
6377 
6378   /// \brief Get the canonical type for a given arithmetic type index.
getArithmeticType(unsigned index)6379   CanQualType getArithmeticType(unsigned index) {
6380     assert(index < NumArithmeticTypes);
6381     static CanQualType ASTContext::* const
6382       ArithmeticTypes[NumArithmeticTypes] = {
6383       // Start of promoted types.
6384       &ASTContext::FloatTy,
6385       &ASTContext::DoubleTy,
6386       &ASTContext::LongDoubleTy,
6387 
6388       // Start of integral types.
6389       &ASTContext::IntTy,
6390       &ASTContext::LongTy,
6391       &ASTContext::LongLongTy,
6392       &ASTContext::UnsignedIntTy,
6393       &ASTContext::UnsignedLongTy,
6394       &ASTContext::UnsignedLongLongTy,
6395       // End of promoted types.
6396 
6397       &ASTContext::BoolTy,
6398       &ASTContext::CharTy,
6399       &ASTContext::WCharTy,
6400       &ASTContext::Char16Ty,
6401       &ASTContext::Char32Ty,
6402       &ASTContext::SignedCharTy,
6403       &ASTContext::ShortTy,
6404       &ASTContext::UnsignedCharTy,
6405       &ASTContext::UnsignedShortTy,
6406       // End of integral types.
6407       // FIXME: What about complex?
6408     };
6409     return S.Context.*ArithmeticTypes[index];
6410   }
6411 
6412   /// \brief Gets the canonical type resulting from the usual arithemetic
6413   /// converions for the given arithmetic types.
getUsualArithmeticConversions(unsigned L,unsigned R)6414   CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6415     // Accelerator table for performing the usual arithmetic conversions.
6416     // The rules are basically:
6417     //   - if either is floating-point, use the wider floating-point
6418     //   - if same signedness, use the higher rank
6419     //   - if same size, use unsigned of the higher rank
6420     //   - use the larger type
6421     // These rules, together with the axiom that higher ranks are
6422     // never smaller, are sufficient to precompute all of these results
6423     // *except* when dealing with signed types of higher rank.
6424     // (we could precompute SLL x UI for all known platforms, but it's
6425     // better not to make any assumptions).
6426     enum PromotedType {
6427                   Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL, Dep=-1
6428     };
6429     static PromotedType ConversionsTable[LastPromotedArithmeticType]
6430                                         [LastPromotedArithmeticType] = {
6431       /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
6432       /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
6433       /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6434       /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL },
6435       /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL,  Dep,   UL,  ULL },
6436       /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL,  Dep,  Dep,  ULL },
6437       /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep,   UI,   UL,  ULL },
6438       /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep,   UL,   UL,  ULL },
6439       /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL,  ULL,  ULL,  ULL },
6440     };
6441 
6442     assert(L < LastPromotedArithmeticType);
6443     assert(R < LastPromotedArithmeticType);
6444     int Idx = ConversionsTable[L][R];
6445 
6446     // Fast path: the table gives us a concrete answer.
6447     if (Idx != Dep) return getArithmeticType(Idx);
6448 
6449     // Slow path: we need to compare widths.
6450     // An invariant is that the signed type has higher rank.
6451     CanQualType LT = getArithmeticType(L),
6452                 RT = getArithmeticType(R);
6453     unsigned LW = S.Context.getIntWidth(LT),
6454              RW = S.Context.getIntWidth(RT);
6455 
6456     // If they're different widths, use the signed type.
6457     if (LW > RW) return LT;
6458     else if (LW < RW) return RT;
6459 
6460     // Otherwise, use the unsigned type of the signed type's rank.
6461     if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6462     assert(L == SLL || R == SLL);
6463     return S.Context.UnsignedLongLongTy;
6464   }
6465 
6466   /// \brief Helper method to factor out the common pattern of adding overloads
6467   /// for '++' and '--' builtin operators.
addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,bool HasVolatile)6468   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6469                                            bool HasVolatile) {
6470     QualType ParamTypes[2] = {
6471       S.Context.getLValueReferenceType(CandidateTy),
6472       S.Context.IntTy
6473     };
6474 
6475     // Non-volatile version.
6476     if (NumArgs == 1)
6477       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6478     else
6479       S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6480 
6481     // Use a heuristic to reduce number of builtin candidates in the set:
6482     // add volatile version only if there are conversions to a volatile type.
6483     if (HasVolatile) {
6484       ParamTypes[0] =
6485         S.Context.getLValueReferenceType(
6486           S.Context.getVolatileType(CandidateTy));
6487       if (NumArgs == 1)
6488         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6489       else
6490         S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6491     }
6492   }
6493 
6494 public:
BuiltinOperatorOverloadBuilder(Sema & S,Expr ** Args,unsigned NumArgs,Qualifiers VisibleTypeConversionsQuals,bool HasArithmeticOrEnumeralCandidateType,SmallVectorImpl<BuiltinCandidateTypeSet> & CandidateTypes,OverloadCandidateSet & CandidateSet)6495   BuiltinOperatorOverloadBuilder(
6496     Sema &S, Expr **Args, unsigned NumArgs,
6497     Qualifiers VisibleTypeConversionsQuals,
6498     bool HasArithmeticOrEnumeralCandidateType,
6499     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
6500     OverloadCandidateSet &CandidateSet)
6501     : S(S), Args(Args), NumArgs(NumArgs),
6502       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
6503       HasArithmeticOrEnumeralCandidateType(
6504         HasArithmeticOrEnumeralCandidateType),
6505       CandidateTypes(CandidateTypes),
6506       CandidateSet(CandidateSet) {
6507     // Validate some of our static helper constants in debug builds.
6508     assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
6509            "Invalid first promoted integral type");
6510     assert(getArithmeticType(LastPromotedIntegralType - 1)
6511              == S.Context.UnsignedLongLongTy &&
6512            "Invalid last promoted integral type");
6513     assert(getArithmeticType(FirstPromotedArithmeticType)
6514              == S.Context.FloatTy &&
6515            "Invalid first promoted arithmetic type");
6516     assert(getArithmeticType(LastPromotedArithmeticType - 1)
6517              == S.Context.UnsignedLongLongTy &&
6518            "Invalid last promoted arithmetic type");
6519   }
6520 
6521   // C++ [over.built]p3:
6522   //
6523   //   For every pair (T, VQ), where T is an arithmetic type, and VQ
6524   //   is either volatile or empty, there exist candidate operator
6525   //   functions of the form
6526   //
6527   //       VQ T&      operator++(VQ T&);
6528   //       T          operator++(VQ T&, int);
6529   //
6530   // C++ [over.built]p4:
6531   //
6532   //   For every pair (T, VQ), where T is an arithmetic type other
6533   //   than bool, and VQ is either volatile or empty, there exist
6534   //   candidate operator functions of the form
6535   //
6536   //       VQ T&      operator--(VQ T&);
6537   //       T          operator--(VQ T&, int);
addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op)6538   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
6539     if (!HasArithmeticOrEnumeralCandidateType)
6540       return;
6541 
6542     for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6543          Arith < NumArithmeticTypes; ++Arith) {
6544       addPlusPlusMinusMinusStyleOverloads(
6545         getArithmeticType(Arith),
6546         VisibleTypeConversionsQuals.hasVolatile());
6547     }
6548   }
6549 
6550   // C++ [over.built]p5:
6551   //
6552   //   For every pair (T, VQ), where T is a cv-qualified or
6553   //   cv-unqualified object type, and VQ is either volatile or
6554   //   empty, there exist candidate operator functions of the form
6555   //
6556   //       T*VQ&      operator++(T*VQ&);
6557   //       T*VQ&      operator--(T*VQ&);
6558   //       T*         operator++(T*VQ&, int);
6559   //       T*         operator--(T*VQ&, int);
addPlusPlusMinusMinusPointerOverloads()6560   void addPlusPlusMinusMinusPointerOverloads() {
6561     for (BuiltinCandidateTypeSet::iterator
6562               Ptr = CandidateTypes[0].pointer_begin(),
6563            PtrEnd = CandidateTypes[0].pointer_end();
6564          Ptr != PtrEnd; ++Ptr) {
6565       // Skip pointer types that aren't pointers to object types.
6566       if (!(*Ptr)->getPointeeType()->isObjectType())
6567         continue;
6568 
6569       addPlusPlusMinusMinusStyleOverloads(*Ptr,
6570         (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6571          VisibleTypeConversionsQuals.hasVolatile()));
6572     }
6573   }
6574 
6575   // C++ [over.built]p6:
6576   //   For every cv-qualified or cv-unqualified object type T, there
6577   //   exist candidate operator functions of the form
6578   //
6579   //       T&         operator*(T*);
6580   //
6581   // C++ [over.built]p7:
6582   //   For every function type T that does not have cv-qualifiers or a
6583   //   ref-qualifier, there exist candidate operator functions of the form
6584   //       T&         operator*(T*);
addUnaryStarPointerOverloads()6585   void addUnaryStarPointerOverloads() {
6586     for (BuiltinCandidateTypeSet::iterator
6587               Ptr = CandidateTypes[0].pointer_begin(),
6588            PtrEnd = CandidateTypes[0].pointer_end();
6589          Ptr != PtrEnd; ++Ptr) {
6590       QualType ParamTy = *Ptr;
6591       QualType PointeeTy = ParamTy->getPointeeType();
6592       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6593         continue;
6594 
6595       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6596         if (Proto->getTypeQuals() || Proto->getRefQualifier())
6597           continue;
6598 
6599       S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6600                             &ParamTy, Args, 1, CandidateSet);
6601     }
6602   }
6603 
6604   // C++ [over.built]p9:
6605   //  For every promoted arithmetic type T, there exist candidate
6606   //  operator functions of the form
6607   //
6608   //       T         operator+(T);
6609   //       T         operator-(T);
addUnaryPlusOrMinusArithmeticOverloads()6610   void addUnaryPlusOrMinusArithmeticOverloads() {
6611     if (!HasArithmeticOrEnumeralCandidateType)
6612       return;
6613 
6614     for (unsigned Arith = FirstPromotedArithmeticType;
6615          Arith < LastPromotedArithmeticType; ++Arith) {
6616       QualType ArithTy = getArithmeticType(Arith);
6617       S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6618     }
6619 
6620     // Extension: We also add these operators for vector types.
6621     for (BuiltinCandidateTypeSet::iterator
6622               Vec = CandidateTypes[0].vector_begin(),
6623            VecEnd = CandidateTypes[0].vector_end();
6624          Vec != VecEnd; ++Vec) {
6625       QualType VecTy = *Vec;
6626       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6627     }
6628   }
6629 
6630   // C++ [over.built]p8:
6631   //   For every type T, there exist candidate operator functions of
6632   //   the form
6633   //
6634   //       T*         operator+(T*);
addUnaryPlusPointerOverloads()6635   void addUnaryPlusPointerOverloads() {
6636     for (BuiltinCandidateTypeSet::iterator
6637               Ptr = CandidateTypes[0].pointer_begin(),
6638            PtrEnd = CandidateTypes[0].pointer_end();
6639          Ptr != PtrEnd; ++Ptr) {
6640       QualType ParamTy = *Ptr;
6641       S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6642     }
6643   }
6644 
6645   // C++ [over.built]p10:
6646   //   For every promoted integral type T, there exist candidate
6647   //   operator functions of the form
6648   //
6649   //        T         operator~(T);
addUnaryTildePromotedIntegralOverloads()6650   void addUnaryTildePromotedIntegralOverloads() {
6651     if (!HasArithmeticOrEnumeralCandidateType)
6652       return;
6653 
6654     for (unsigned Int = FirstPromotedIntegralType;
6655          Int < LastPromotedIntegralType; ++Int) {
6656       QualType IntTy = getArithmeticType(Int);
6657       S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6658     }
6659 
6660     // Extension: We also add this operator for vector types.
6661     for (BuiltinCandidateTypeSet::iterator
6662               Vec = CandidateTypes[0].vector_begin(),
6663            VecEnd = CandidateTypes[0].vector_end();
6664          Vec != VecEnd; ++Vec) {
6665       QualType VecTy = *Vec;
6666       S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6667     }
6668   }
6669 
6670   // C++ [over.match.oper]p16:
6671   //   For every pointer to member type T, there exist candidate operator
6672   //   functions of the form
6673   //
6674   //        bool operator==(T,T);
6675   //        bool operator!=(T,T);
addEqualEqualOrNotEqualMemberPointerOverloads()6676   void addEqualEqualOrNotEqualMemberPointerOverloads() {
6677     /// Set of (canonical) types that we've already handled.
6678     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6679 
6680     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6681       for (BuiltinCandidateTypeSet::iterator
6682                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6683              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6684            MemPtr != MemPtrEnd;
6685            ++MemPtr) {
6686         // Don't add the same builtin candidate twice.
6687         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6688           continue;
6689 
6690         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6691         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6692                               CandidateSet);
6693       }
6694     }
6695   }
6696 
6697   // C++ [over.built]p15:
6698   //
6699   //   For every T, where T is an enumeration type, a pointer type, or
6700   //   std::nullptr_t, there exist candidate operator functions of the form
6701   //
6702   //        bool       operator<(T, T);
6703   //        bool       operator>(T, T);
6704   //        bool       operator<=(T, T);
6705   //        bool       operator>=(T, T);
6706   //        bool       operator==(T, T);
6707   //        bool       operator!=(T, T);
addRelationalPointerOrEnumeralOverloads()6708   void addRelationalPointerOrEnumeralOverloads() {
6709     // C++ [over.built]p1:
6710     //   If there is a user-written candidate with the same name and parameter
6711     //   types as a built-in candidate operator function, the built-in operator
6712     //   function is hidden and is not included in the set of candidate
6713     //   functions.
6714     //
6715     // The text is actually in a note, but if we don't implement it then we end
6716     // up with ambiguities when the user provides an overloaded operator for
6717     // an enumeration type. Note that only enumeration types have this problem,
6718     // so we track which enumeration types we've seen operators for. Also, the
6719     // only other overloaded operator with enumeration argumenst, operator=,
6720     // cannot be overloaded for enumeration types, so this is the only place
6721     // where we must suppress candidates like this.
6722     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6723       UserDefinedBinaryOperators;
6724 
6725     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6726       if (CandidateTypes[ArgIdx].enumeration_begin() !=
6727           CandidateTypes[ArgIdx].enumeration_end()) {
6728         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6729                                          CEnd = CandidateSet.end();
6730              C != CEnd; ++C) {
6731           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6732             continue;
6733 
6734           QualType FirstParamType =
6735             C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6736           QualType SecondParamType =
6737             C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6738 
6739           // Skip if either parameter isn't of enumeral type.
6740           if (!FirstParamType->isEnumeralType() ||
6741               !SecondParamType->isEnumeralType())
6742             continue;
6743 
6744           // Add this operator to the set of known user-defined operators.
6745           UserDefinedBinaryOperators.insert(
6746             std::make_pair(S.Context.getCanonicalType(FirstParamType),
6747                            S.Context.getCanonicalType(SecondParamType)));
6748         }
6749       }
6750     }
6751 
6752     /// Set of (canonical) types that we've already handled.
6753     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6754 
6755     for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6756       for (BuiltinCandidateTypeSet::iterator
6757                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6758              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6759            Ptr != PtrEnd; ++Ptr) {
6760         // Don't add the same builtin candidate twice.
6761         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6762           continue;
6763 
6764         QualType ParamTypes[2] = { *Ptr, *Ptr };
6765         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6766                               CandidateSet);
6767       }
6768       for (BuiltinCandidateTypeSet::iterator
6769                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6770              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6771            Enum != EnumEnd; ++Enum) {
6772         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6773 
6774         // Don't add the same builtin candidate twice, or if a user defined
6775         // candidate exists.
6776         if (!AddedTypes.insert(CanonType) ||
6777             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6778                                                             CanonType)))
6779           continue;
6780 
6781         QualType ParamTypes[2] = { *Enum, *Enum };
6782         S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6783                               CandidateSet);
6784       }
6785 
6786       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6787         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6788         if (AddedTypes.insert(NullPtrTy) &&
6789             !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6790                                                              NullPtrTy))) {
6791           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6792           S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6793                                 CandidateSet);
6794         }
6795       }
6796     }
6797   }
6798 
6799   // C++ [over.built]p13:
6800   //
6801   //   For every cv-qualified or cv-unqualified object type T
6802   //   there exist candidate operator functions of the form
6803   //
6804   //      T*         operator+(T*, ptrdiff_t);
6805   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
6806   //      T*         operator-(T*, ptrdiff_t);
6807   //      T*         operator+(ptrdiff_t, T*);
6808   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
6809   //
6810   // C++ [over.built]p14:
6811   //
6812   //   For every T, where T is a pointer to object type, there
6813   //   exist candidate operator functions of the form
6814   //
6815   //      ptrdiff_t  operator-(T, T);
addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op)6816   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6817     /// Set of (canonical) types that we've already handled.
6818     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6819 
6820     for (int Arg = 0; Arg < 2; ++Arg) {
6821       QualType AsymetricParamTypes[2] = {
6822         S.Context.getPointerDiffType(),
6823         S.Context.getPointerDiffType(),
6824       };
6825       for (BuiltinCandidateTypeSet::iterator
6826                 Ptr = CandidateTypes[Arg].pointer_begin(),
6827              PtrEnd = CandidateTypes[Arg].pointer_end();
6828            Ptr != PtrEnd; ++Ptr) {
6829         QualType PointeeTy = (*Ptr)->getPointeeType();
6830         if (!PointeeTy->isObjectType())
6831           continue;
6832 
6833         AsymetricParamTypes[Arg] = *Ptr;
6834         if (Arg == 0 || Op == OO_Plus) {
6835           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6836           // T* operator+(ptrdiff_t, T*);
6837           S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6838                                 CandidateSet);
6839         }
6840         if (Op == OO_Minus) {
6841           // ptrdiff_t operator-(T, T);
6842           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6843             continue;
6844 
6845           QualType ParamTypes[2] = { *Ptr, *Ptr };
6846           S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6847                                 Args, 2, CandidateSet);
6848         }
6849       }
6850     }
6851   }
6852 
6853   // C++ [over.built]p12:
6854   //
6855   //   For every pair of promoted arithmetic types L and R, there
6856   //   exist candidate operator functions of the form
6857   //
6858   //        LR         operator*(L, R);
6859   //        LR         operator/(L, R);
6860   //        LR         operator+(L, R);
6861   //        LR         operator-(L, R);
6862   //        bool       operator<(L, R);
6863   //        bool       operator>(L, R);
6864   //        bool       operator<=(L, R);
6865   //        bool       operator>=(L, R);
6866   //        bool       operator==(L, R);
6867   //        bool       operator!=(L, R);
6868   //
6869   //   where LR is the result of the usual arithmetic conversions
6870   //   between types L and R.
6871   //
6872   // C++ [over.built]p24:
6873   //
6874   //   For every pair of promoted arithmetic types L and R, there exist
6875   //   candidate operator functions of the form
6876   //
6877   //        LR       operator?(bool, L, R);
6878   //
6879   //   where LR is the result of the usual arithmetic conversions
6880   //   between types L and R.
6881   // Our candidates ignore the first parameter.
addGenericBinaryArithmeticOverloads(bool isComparison)6882   void addGenericBinaryArithmeticOverloads(bool isComparison) {
6883     if (!HasArithmeticOrEnumeralCandidateType)
6884       return;
6885 
6886     for (unsigned Left = FirstPromotedArithmeticType;
6887          Left < LastPromotedArithmeticType; ++Left) {
6888       for (unsigned Right = FirstPromotedArithmeticType;
6889            Right < LastPromotedArithmeticType; ++Right) {
6890         QualType LandR[2] = { getArithmeticType(Left),
6891                               getArithmeticType(Right) };
6892         QualType Result =
6893           isComparison ? S.Context.BoolTy
6894                        : getUsualArithmeticConversions(Left, Right);
6895         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6896       }
6897     }
6898 
6899     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6900     // conditional operator for vector types.
6901     for (BuiltinCandidateTypeSet::iterator
6902               Vec1 = CandidateTypes[0].vector_begin(),
6903            Vec1End = CandidateTypes[0].vector_end();
6904          Vec1 != Vec1End; ++Vec1) {
6905       for (BuiltinCandidateTypeSet::iterator
6906                 Vec2 = CandidateTypes[1].vector_begin(),
6907              Vec2End = CandidateTypes[1].vector_end();
6908            Vec2 != Vec2End; ++Vec2) {
6909         QualType LandR[2] = { *Vec1, *Vec2 };
6910         QualType Result = S.Context.BoolTy;
6911         if (!isComparison) {
6912           if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6913             Result = *Vec1;
6914           else
6915             Result = *Vec2;
6916         }
6917 
6918         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6919       }
6920     }
6921   }
6922 
6923   // C++ [over.built]p17:
6924   //
6925   //   For every pair of promoted integral types L and R, there
6926   //   exist candidate operator functions of the form
6927   //
6928   //      LR         operator%(L, R);
6929   //      LR         operator&(L, R);
6930   //      LR         operator^(L, R);
6931   //      LR         operator|(L, R);
6932   //      L          operator<<(L, R);
6933   //      L          operator>>(L, R);
6934   //
6935   //   where LR is the result of the usual arithmetic conversions
6936   //   between types L and R.
addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op)6937   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
6938     if (!HasArithmeticOrEnumeralCandidateType)
6939       return;
6940 
6941     for (unsigned Left = FirstPromotedIntegralType;
6942          Left < LastPromotedIntegralType; ++Left) {
6943       for (unsigned Right = FirstPromotedIntegralType;
6944            Right < LastPromotedIntegralType; ++Right) {
6945         QualType LandR[2] = { getArithmeticType(Left),
6946                               getArithmeticType(Right) };
6947         QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6948             ? LandR[0]
6949             : getUsualArithmeticConversions(Left, Right);
6950         S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6951       }
6952     }
6953   }
6954 
6955   // C++ [over.built]p20:
6956   //
6957   //   For every pair (T, VQ), where T is an enumeration or
6958   //   pointer to member type and VQ is either volatile or
6959   //   empty, there exist candidate operator functions of the form
6960   //
6961   //        VQ T&      operator=(VQ T&, T);
addAssignmentMemberPointerOrEnumeralOverloads()6962   void addAssignmentMemberPointerOrEnumeralOverloads() {
6963     /// Set of (canonical) types that we've already handled.
6964     llvm::SmallPtrSet<QualType, 8> AddedTypes;
6965 
6966     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6967       for (BuiltinCandidateTypeSet::iterator
6968                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6969              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6970            Enum != EnumEnd; ++Enum) {
6971         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6972           continue;
6973 
6974         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6975                                                CandidateSet);
6976       }
6977 
6978       for (BuiltinCandidateTypeSet::iterator
6979                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6980              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6981            MemPtr != MemPtrEnd; ++MemPtr) {
6982         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6983           continue;
6984 
6985         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6986                                                CandidateSet);
6987       }
6988     }
6989   }
6990 
6991   // C++ [over.built]p19:
6992   //
6993   //   For every pair (T, VQ), where T is any type and VQ is either
6994   //   volatile or empty, there exist candidate operator functions
6995   //   of the form
6996   //
6997   //        T*VQ&      operator=(T*VQ&, T*);
6998   //
6999   // C++ [over.built]p21:
7000   //
7001   //   For every pair (T, VQ), where T is a cv-qualified or
7002   //   cv-unqualified object type and VQ is either volatile or
7003   //   empty, there exist candidate operator functions of the form
7004   //
7005   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
7006   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
addAssignmentPointerOverloads(bool isEqualOp)7007   void addAssignmentPointerOverloads(bool isEqualOp) {
7008     /// Set of (canonical) types that we've already handled.
7009     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7010 
7011     for (BuiltinCandidateTypeSet::iterator
7012               Ptr = CandidateTypes[0].pointer_begin(),
7013            PtrEnd = CandidateTypes[0].pointer_end();
7014          Ptr != PtrEnd; ++Ptr) {
7015       // If this is operator=, keep track of the builtin candidates we added.
7016       if (isEqualOp)
7017         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7018       else if (!(*Ptr)->getPointeeType()->isObjectType())
7019         continue;
7020 
7021       // non-volatile version
7022       QualType ParamTypes[2] = {
7023         S.Context.getLValueReferenceType(*Ptr),
7024         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7025       };
7026       S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7027                             /*IsAssigmentOperator=*/ isEqualOp);
7028 
7029       if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7030           VisibleTypeConversionsQuals.hasVolatile()) {
7031         // volatile version
7032         ParamTypes[0] =
7033           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7034         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7035                               /*IsAssigmentOperator=*/isEqualOp);
7036       }
7037     }
7038 
7039     if (isEqualOp) {
7040       for (BuiltinCandidateTypeSet::iterator
7041                 Ptr = CandidateTypes[1].pointer_begin(),
7042              PtrEnd = CandidateTypes[1].pointer_end();
7043            Ptr != PtrEnd; ++Ptr) {
7044         // Make sure we don't add the same candidate twice.
7045         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7046           continue;
7047 
7048         QualType ParamTypes[2] = {
7049           S.Context.getLValueReferenceType(*Ptr),
7050           *Ptr,
7051         };
7052 
7053         // non-volatile version
7054         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7055                               /*IsAssigmentOperator=*/true);
7056 
7057         if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7058             VisibleTypeConversionsQuals.hasVolatile()) {
7059           // volatile version
7060           ParamTypes[0] =
7061             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7062           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7063                                 CandidateSet, /*IsAssigmentOperator=*/true);
7064         }
7065       }
7066     }
7067   }
7068 
7069   // C++ [over.built]p18:
7070   //
7071   //   For every triple (L, VQ, R), where L is an arithmetic type,
7072   //   VQ is either volatile or empty, and R is a promoted
7073   //   arithmetic type, there exist candidate operator functions of
7074   //   the form
7075   //
7076   //        VQ L&      operator=(VQ L&, R);
7077   //        VQ L&      operator*=(VQ L&, R);
7078   //        VQ L&      operator/=(VQ L&, R);
7079   //        VQ L&      operator+=(VQ L&, R);
7080   //        VQ L&      operator-=(VQ L&, R);
addAssignmentArithmeticOverloads(bool isEqualOp)7081   void addAssignmentArithmeticOverloads(bool isEqualOp) {
7082     if (!HasArithmeticOrEnumeralCandidateType)
7083       return;
7084 
7085     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7086       for (unsigned Right = FirstPromotedArithmeticType;
7087            Right < LastPromotedArithmeticType; ++Right) {
7088         QualType ParamTypes[2];
7089         ParamTypes[1] = getArithmeticType(Right);
7090 
7091         // Add this built-in operator as a candidate (VQ is empty).
7092         ParamTypes[0] =
7093           S.Context.getLValueReferenceType(getArithmeticType(Left));
7094         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7095                               /*IsAssigmentOperator=*/isEqualOp);
7096 
7097         // Add this built-in operator as a candidate (VQ is 'volatile').
7098         if (VisibleTypeConversionsQuals.hasVolatile()) {
7099           ParamTypes[0] =
7100             S.Context.getVolatileType(getArithmeticType(Left));
7101           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7102           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7103                                 CandidateSet,
7104                                 /*IsAssigmentOperator=*/isEqualOp);
7105         }
7106       }
7107     }
7108 
7109     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7110     for (BuiltinCandidateTypeSet::iterator
7111               Vec1 = CandidateTypes[0].vector_begin(),
7112            Vec1End = CandidateTypes[0].vector_end();
7113          Vec1 != Vec1End; ++Vec1) {
7114       for (BuiltinCandidateTypeSet::iterator
7115                 Vec2 = CandidateTypes[1].vector_begin(),
7116              Vec2End = CandidateTypes[1].vector_end();
7117            Vec2 != Vec2End; ++Vec2) {
7118         QualType ParamTypes[2];
7119         ParamTypes[1] = *Vec2;
7120         // Add this built-in operator as a candidate (VQ is empty).
7121         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7122         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7123                               /*IsAssigmentOperator=*/isEqualOp);
7124 
7125         // Add this built-in operator as a candidate (VQ is 'volatile').
7126         if (VisibleTypeConversionsQuals.hasVolatile()) {
7127           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7128           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7129           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7130                                 CandidateSet,
7131                                 /*IsAssigmentOperator=*/isEqualOp);
7132         }
7133       }
7134     }
7135   }
7136 
7137   // C++ [over.built]p22:
7138   //
7139   //   For every triple (L, VQ, R), where L is an integral type, VQ
7140   //   is either volatile or empty, and R is a promoted integral
7141   //   type, there exist candidate operator functions of the form
7142   //
7143   //        VQ L&       operator%=(VQ L&, R);
7144   //        VQ L&       operator<<=(VQ L&, R);
7145   //        VQ L&       operator>>=(VQ L&, R);
7146   //        VQ L&       operator&=(VQ L&, R);
7147   //        VQ L&       operator^=(VQ L&, R);
7148   //        VQ L&       operator|=(VQ L&, R);
addAssignmentIntegralOverloads()7149   void addAssignmentIntegralOverloads() {
7150     if (!HasArithmeticOrEnumeralCandidateType)
7151       return;
7152 
7153     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7154       for (unsigned Right = FirstPromotedIntegralType;
7155            Right < LastPromotedIntegralType; ++Right) {
7156         QualType ParamTypes[2];
7157         ParamTypes[1] = getArithmeticType(Right);
7158 
7159         // Add this built-in operator as a candidate (VQ is empty).
7160         ParamTypes[0] =
7161           S.Context.getLValueReferenceType(getArithmeticType(Left));
7162         S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7163         if (VisibleTypeConversionsQuals.hasVolatile()) {
7164           // Add this built-in operator as a candidate (VQ is 'volatile').
7165           ParamTypes[0] = getArithmeticType(Left);
7166           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7167           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7168           S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7169                                 CandidateSet);
7170         }
7171       }
7172     }
7173   }
7174 
7175   // C++ [over.operator]p23:
7176   //
7177   //   There also exist candidate operator functions of the form
7178   //
7179   //        bool        operator!(bool);
7180   //        bool        operator&&(bool, bool);
7181   //        bool        operator||(bool, bool);
addExclaimOverload()7182   void addExclaimOverload() {
7183     QualType ParamTy = S.Context.BoolTy;
7184     S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7185                           /*IsAssignmentOperator=*/false,
7186                           /*NumContextualBoolArguments=*/1);
7187   }
addAmpAmpOrPipePipeOverload()7188   void addAmpAmpOrPipePipeOverload() {
7189     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7190     S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7191                           /*IsAssignmentOperator=*/false,
7192                           /*NumContextualBoolArguments=*/2);
7193   }
7194 
7195   // C++ [over.built]p13:
7196   //
7197   //   For every cv-qualified or cv-unqualified object type T there
7198   //   exist candidate operator functions of the form
7199   //
7200   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
7201   //        T&         operator[](T*, ptrdiff_t);
7202   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
7203   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
7204   //        T&         operator[](ptrdiff_t, T*);
addSubscriptOverloads()7205   void addSubscriptOverloads() {
7206     for (BuiltinCandidateTypeSet::iterator
7207               Ptr = CandidateTypes[0].pointer_begin(),
7208            PtrEnd = CandidateTypes[0].pointer_end();
7209          Ptr != PtrEnd; ++Ptr) {
7210       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7211       QualType PointeeType = (*Ptr)->getPointeeType();
7212       if (!PointeeType->isObjectType())
7213         continue;
7214 
7215       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7216 
7217       // T& operator[](T*, ptrdiff_t)
7218       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7219     }
7220 
7221     for (BuiltinCandidateTypeSet::iterator
7222               Ptr = CandidateTypes[1].pointer_begin(),
7223            PtrEnd = CandidateTypes[1].pointer_end();
7224          Ptr != PtrEnd; ++Ptr) {
7225       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7226       QualType PointeeType = (*Ptr)->getPointeeType();
7227       if (!PointeeType->isObjectType())
7228         continue;
7229 
7230       QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7231 
7232       // T& operator[](ptrdiff_t, T*)
7233       S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7234     }
7235   }
7236 
7237   // C++ [over.built]p11:
7238   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7239   //    C1 is the same type as C2 or is a derived class of C2, T is an object
7240   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7241   //    there exist candidate operator functions of the form
7242   //
7243   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7244   //
7245   //    where CV12 is the union of CV1 and CV2.
addArrowStarOverloads()7246   void addArrowStarOverloads() {
7247     for (BuiltinCandidateTypeSet::iterator
7248              Ptr = CandidateTypes[0].pointer_begin(),
7249            PtrEnd = CandidateTypes[0].pointer_end();
7250          Ptr != PtrEnd; ++Ptr) {
7251       QualType C1Ty = (*Ptr);
7252       QualType C1;
7253       QualifierCollector Q1;
7254       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7255       if (!isa<RecordType>(C1))
7256         continue;
7257       // heuristic to reduce number of builtin candidates in the set.
7258       // Add volatile/restrict version only if there are conversions to a
7259       // volatile/restrict type.
7260       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7261         continue;
7262       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7263         continue;
7264       for (BuiltinCandidateTypeSet::iterator
7265                 MemPtr = CandidateTypes[1].member_pointer_begin(),
7266              MemPtrEnd = CandidateTypes[1].member_pointer_end();
7267            MemPtr != MemPtrEnd; ++MemPtr) {
7268         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7269         QualType C2 = QualType(mptr->getClass(), 0);
7270         C2 = C2.getUnqualifiedType();
7271         if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7272           break;
7273         QualType ParamTypes[2] = { *Ptr, *MemPtr };
7274         // build CV12 T&
7275         QualType T = mptr->getPointeeType();
7276         if (!VisibleTypeConversionsQuals.hasVolatile() &&
7277             T.isVolatileQualified())
7278           continue;
7279         if (!VisibleTypeConversionsQuals.hasRestrict() &&
7280             T.isRestrictQualified())
7281           continue;
7282         T = Q1.apply(S.Context, T);
7283         QualType ResultTy = S.Context.getLValueReferenceType(T);
7284         S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7285       }
7286     }
7287   }
7288 
7289   // Note that we don't consider the first argument, since it has been
7290   // contextually converted to bool long ago. The candidates below are
7291   // therefore added as binary.
7292   //
7293   // C++ [over.built]p25:
7294   //   For every type T, where T is a pointer, pointer-to-member, or scoped
7295   //   enumeration type, there exist candidate operator functions of the form
7296   //
7297   //        T        operator?(bool, T, T);
7298   //
addConditionalOperatorOverloads()7299   void addConditionalOperatorOverloads() {
7300     /// Set of (canonical) types that we've already handled.
7301     llvm::SmallPtrSet<QualType, 8> AddedTypes;
7302 
7303     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7304       for (BuiltinCandidateTypeSet::iterator
7305                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7306              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7307            Ptr != PtrEnd; ++Ptr) {
7308         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7309           continue;
7310 
7311         QualType ParamTypes[2] = { *Ptr, *Ptr };
7312         S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7313       }
7314 
7315       for (BuiltinCandidateTypeSet::iterator
7316                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7317              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7318            MemPtr != MemPtrEnd; ++MemPtr) {
7319         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7320           continue;
7321 
7322         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7323         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7324       }
7325 
7326       if (S.getLangOpts().CPlusPlus0x) {
7327         for (BuiltinCandidateTypeSet::iterator
7328                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7329                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7330              Enum != EnumEnd; ++Enum) {
7331           if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7332             continue;
7333 
7334           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7335             continue;
7336 
7337           QualType ParamTypes[2] = { *Enum, *Enum };
7338           S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7339         }
7340       }
7341     }
7342   }
7343 };
7344 
7345 } // end anonymous namespace
7346 
7347 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
7348 /// operator overloads to the candidate set (C++ [over.built]), based
7349 /// on the operator @p Op and the arguments given. For example, if the
7350 /// operator is a binary '+', this routine might add "int
7351 /// operator+(int, int)" to cover integer addition.
7352 void
AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,SourceLocation OpLoc,Expr ** Args,unsigned NumArgs,OverloadCandidateSet & CandidateSet)7353 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7354                                    SourceLocation OpLoc,
7355                                    Expr **Args, unsigned NumArgs,
7356                                    OverloadCandidateSet& CandidateSet) {
7357   // Find all of the types that the arguments can convert to, but only
7358   // if the operator we're looking at has built-in operator candidates
7359   // that make use of these types. Also record whether we encounter non-record
7360   // candidate types or either arithmetic or enumeral candidate types.
7361   Qualifiers VisibleTypeConversionsQuals;
7362   VisibleTypeConversionsQuals.addConst();
7363   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7364     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7365 
7366   bool HasNonRecordCandidateType = false;
7367   bool HasArithmeticOrEnumeralCandidateType = false;
7368   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7369   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7370     CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7371     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7372                                                  OpLoc,
7373                                                  true,
7374                                                  (Op == OO_Exclaim ||
7375                                                   Op == OO_AmpAmp ||
7376                                                   Op == OO_PipePipe),
7377                                                  VisibleTypeConversionsQuals);
7378     HasNonRecordCandidateType = HasNonRecordCandidateType ||
7379         CandidateTypes[ArgIdx].hasNonRecordTypes();
7380     HasArithmeticOrEnumeralCandidateType =
7381         HasArithmeticOrEnumeralCandidateType ||
7382         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7383   }
7384 
7385   // Exit early when no non-record types have been added to the candidate set
7386   // for any of the arguments to the operator.
7387   //
7388   // We can't exit early for !, ||, or &&, since there we have always have
7389   // 'bool' overloads.
7390   if (!HasNonRecordCandidateType &&
7391       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7392     return;
7393 
7394   // Setup an object to manage the common state for building overloads.
7395   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7396                                            VisibleTypeConversionsQuals,
7397                                            HasArithmeticOrEnumeralCandidateType,
7398                                            CandidateTypes, CandidateSet);
7399 
7400   // Dispatch over the operation to add in only those overloads which apply.
7401   switch (Op) {
7402   case OO_None:
7403   case NUM_OVERLOADED_OPERATORS:
7404     llvm_unreachable("Expected an overloaded operator");
7405 
7406   case OO_New:
7407   case OO_Delete:
7408   case OO_Array_New:
7409   case OO_Array_Delete:
7410   case OO_Call:
7411     llvm_unreachable(
7412                     "Special operators don't use AddBuiltinOperatorCandidates");
7413 
7414   case OO_Comma:
7415   case OO_Arrow:
7416     // C++ [over.match.oper]p3:
7417     //   -- For the operator ',', the unary operator '&', or the
7418     //      operator '->', the built-in candidates set is empty.
7419     break;
7420 
7421   case OO_Plus: // '+' is either unary or binary
7422     if (NumArgs == 1)
7423       OpBuilder.addUnaryPlusPointerOverloads();
7424     // Fall through.
7425 
7426   case OO_Minus: // '-' is either unary or binary
7427     if (NumArgs == 1) {
7428       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
7429     } else {
7430       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7431       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7432     }
7433     break;
7434 
7435   case OO_Star: // '*' is either unary or binary
7436     if (NumArgs == 1)
7437       OpBuilder.addUnaryStarPointerOverloads();
7438     else
7439       OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7440     break;
7441 
7442   case OO_Slash:
7443     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7444     break;
7445 
7446   case OO_PlusPlus:
7447   case OO_MinusMinus:
7448     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7449     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
7450     break;
7451 
7452   case OO_EqualEqual:
7453   case OO_ExclaimEqual:
7454     OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
7455     // Fall through.
7456 
7457   case OO_Less:
7458   case OO_Greater:
7459   case OO_LessEqual:
7460   case OO_GreaterEqual:
7461     OpBuilder.addRelationalPointerOrEnumeralOverloads();
7462     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7463     break;
7464 
7465   case OO_Percent:
7466   case OO_Caret:
7467   case OO_Pipe:
7468   case OO_LessLess:
7469   case OO_GreaterGreater:
7470     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7471     break;
7472 
7473   case OO_Amp: // '&' is either unary or binary
7474     if (NumArgs == 1)
7475       // C++ [over.match.oper]p3:
7476       //   -- For the operator ',', the unary operator '&', or the
7477       //      operator '->', the built-in candidates set is empty.
7478       break;
7479 
7480     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7481     break;
7482 
7483   case OO_Tilde:
7484     OpBuilder.addUnaryTildePromotedIntegralOverloads();
7485     break;
7486 
7487   case OO_Equal:
7488     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
7489     // Fall through.
7490 
7491   case OO_PlusEqual:
7492   case OO_MinusEqual:
7493     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
7494     // Fall through.
7495 
7496   case OO_StarEqual:
7497   case OO_SlashEqual:
7498     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
7499     break;
7500 
7501   case OO_PercentEqual:
7502   case OO_LessLessEqual:
7503   case OO_GreaterGreaterEqual:
7504   case OO_AmpEqual:
7505   case OO_CaretEqual:
7506   case OO_PipeEqual:
7507     OpBuilder.addAssignmentIntegralOverloads();
7508     break;
7509 
7510   case OO_Exclaim:
7511     OpBuilder.addExclaimOverload();
7512     break;
7513 
7514   case OO_AmpAmp:
7515   case OO_PipePipe:
7516     OpBuilder.addAmpAmpOrPipePipeOverload();
7517     break;
7518 
7519   case OO_Subscript:
7520     OpBuilder.addSubscriptOverloads();
7521     break;
7522 
7523   case OO_ArrowStar:
7524     OpBuilder.addArrowStarOverloads();
7525     break;
7526 
7527   case OO_Conditional:
7528     OpBuilder.addConditionalOperatorOverloads();
7529     OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7530     break;
7531   }
7532 }
7533 
7534 /// \brief Add function candidates found via argument-dependent lookup
7535 /// to the set of overloading candidates.
7536 ///
7537 /// This routine performs argument-dependent name lookup based on the
7538 /// given function name (which may also be an operator name) and adds
7539 /// all of the overload candidates found by ADL to the overload
7540 /// candidate set (C++ [basic.lookup.argdep]).
7541 void
AddArgumentDependentLookupCandidates(DeclarationName Name,bool Operator,SourceLocation Loc,llvm::ArrayRef<Expr * > Args,TemplateArgumentListInfo * ExplicitTemplateArgs,OverloadCandidateSet & CandidateSet,bool PartialOverloading,bool StdNamespaceIsAssociated)7542 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
7543                                            bool Operator, SourceLocation Loc,
7544                                            llvm::ArrayRef<Expr *> Args,
7545                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
7546                                            OverloadCandidateSet& CandidateSet,
7547                                            bool PartialOverloading,
7548                                            bool StdNamespaceIsAssociated) {
7549   ADLResult Fns;
7550 
7551   // FIXME: This approach for uniquing ADL results (and removing
7552   // redundant candidates from the set) relies on pointer-equality,
7553   // which means we need to key off the canonical decl.  However,
7554   // always going back to the canonical decl might not get us the
7555   // right set of default arguments.  What default arguments are
7556   // we supposed to consider on ADL candidates, anyway?
7557 
7558   // FIXME: Pass in the explicit template arguments?
7559   ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
7560                           StdNamespaceIsAssociated);
7561 
7562   // Erase all of the candidates we already knew about.
7563   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7564                                    CandEnd = CandidateSet.end();
7565        Cand != CandEnd; ++Cand)
7566     if (Cand->Function) {
7567       Fns.erase(Cand->Function);
7568       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
7569         Fns.erase(FunTmpl);
7570     }
7571 
7572   // For each of the ADL candidates we found, add it to the overload
7573   // set.
7574   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
7575     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
7576     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
7577       if (ExplicitTemplateArgs)
7578         continue;
7579 
7580       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7581                            PartialOverloading);
7582     } else
7583       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
7584                                    FoundDecl, ExplicitTemplateArgs,
7585                                    Args, CandidateSet);
7586   }
7587 }
7588 
7589 /// isBetterOverloadCandidate - Determines whether the first overload
7590 /// candidate is a better candidate than the second (C++ 13.3.3p1).
7591 bool
isBetterOverloadCandidate(Sema & S,const OverloadCandidate & Cand1,const OverloadCandidate & Cand2,SourceLocation Loc,bool UserDefinedConversion)7592 isBetterOverloadCandidate(Sema &S,
7593                           const OverloadCandidate &Cand1,
7594                           const OverloadCandidate &Cand2,
7595                           SourceLocation Loc,
7596                           bool UserDefinedConversion) {
7597   // Define viable functions to be better candidates than non-viable
7598   // functions.
7599   if (!Cand2.Viable)
7600     return Cand1.Viable;
7601   else if (!Cand1.Viable)
7602     return false;
7603 
7604   // C++ [over.match.best]p1:
7605   //
7606   //   -- if F is a static member function, ICS1(F) is defined such
7607   //      that ICS1(F) is neither better nor worse than ICS1(G) for
7608   //      any function G, and, symmetrically, ICS1(G) is neither
7609   //      better nor worse than ICS1(F).
7610   unsigned StartArg = 0;
7611   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7612     StartArg = 1;
7613 
7614   // C++ [over.match.best]p1:
7615   //   A viable function F1 is defined to be a better function than another
7616   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
7617   //   conversion sequence than ICSi(F2), and then...
7618   unsigned NumArgs = Cand1.NumConversions;
7619   assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
7620   bool HasBetterConversion = false;
7621   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
7622     switch (CompareImplicitConversionSequences(S,
7623                                                Cand1.Conversions[ArgIdx],
7624                                                Cand2.Conversions[ArgIdx])) {
7625     case ImplicitConversionSequence::Better:
7626       // Cand1 has a better conversion sequence.
7627       HasBetterConversion = true;
7628       break;
7629 
7630     case ImplicitConversionSequence::Worse:
7631       // Cand1 can't be better than Cand2.
7632       return false;
7633 
7634     case ImplicitConversionSequence::Indistinguishable:
7635       // Do nothing.
7636       break;
7637     }
7638   }
7639 
7640   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
7641   //       ICSj(F2), or, if not that,
7642   if (HasBetterConversion)
7643     return true;
7644 
7645   //     - F1 is a non-template function and F2 is a function template
7646   //       specialization, or, if not that,
7647   if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
7648       Cand2.Function && Cand2.Function->getPrimaryTemplate())
7649     return true;
7650 
7651   //   -- F1 and F2 are function template specializations, and the function
7652   //      template for F1 is more specialized than the template for F2
7653   //      according to the partial ordering rules described in 14.5.5.2, or,
7654   //      if not that,
7655   if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
7656       Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
7657     if (FunctionTemplateDecl *BetterTemplate
7658           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7659                                          Cand2.Function->getPrimaryTemplate(),
7660                                          Loc,
7661                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
7662                                                              : TPOC_Call,
7663                                          Cand1.ExplicitCallArguments))
7664       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
7665   }
7666 
7667   //   -- the context is an initialization by user-defined conversion
7668   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
7669   //      from the return type of F1 to the destination type (i.e.,
7670   //      the type of the entity being initialized) is a better
7671   //      conversion sequence than the standard conversion sequence
7672   //      from the return type of F2 to the destination type.
7673   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
7674       isa<CXXConversionDecl>(Cand1.Function) &&
7675       isa<CXXConversionDecl>(Cand2.Function)) {
7676     // First check whether we prefer one of the conversion functions over the
7677     // other. This only distinguishes the results in non-standard, extension
7678     // cases such as the conversion from a lambda closure type to a function
7679     // pointer or block.
7680     ImplicitConversionSequence::CompareKind FuncResult
7681       = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7682     if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7683       return FuncResult;
7684 
7685     switch (CompareStandardConversionSequences(S,
7686                                                Cand1.FinalConversion,
7687                                                Cand2.FinalConversion)) {
7688     case ImplicitConversionSequence::Better:
7689       // Cand1 has a better conversion sequence.
7690       return true;
7691 
7692     case ImplicitConversionSequence::Worse:
7693       // Cand1 can't be better than Cand2.
7694       return false;
7695 
7696     case ImplicitConversionSequence::Indistinguishable:
7697       // Do nothing
7698       break;
7699     }
7700   }
7701 
7702   return false;
7703 }
7704 
7705 /// \brief Computes the best viable function (C++ 13.3.3)
7706 /// within an overload candidate set.
7707 ///
7708 /// \param CandidateSet the set of candidate functions.
7709 ///
7710 /// \param Loc the location of the function name (or operator symbol) for
7711 /// which overload resolution occurs.
7712 ///
7713 /// \param Best f overload resolution was successful or found a deleted
7714 /// function, Best points to the candidate function found.
7715 ///
7716 /// \returns The result of overload resolution.
7717 OverloadingResult
BestViableFunction(Sema & S,SourceLocation Loc,iterator & Best,bool UserDefinedConversion)7718 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
7719                                          iterator &Best,
7720                                          bool UserDefinedConversion) {
7721   // Find the best viable function.
7722   Best = end();
7723   for (iterator Cand = begin(); Cand != end(); ++Cand) {
7724     if (Cand->Viable)
7725       if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
7726                                                      UserDefinedConversion))
7727         Best = Cand;
7728   }
7729 
7730   // If we didn't find any viable functions, abort.
7731   if (Best == end())
7732     return OR_No_Viable_Function;
7733 
7734   // Make sure that this function is better than every other viable
7735   // function. If not, we have an ambiguity.
7736   for (iterator Cand = begin(); Cand != end(); ++Cand) {
7737     if (Cand->Viable &&
7738         Cand != Best &&
7739         !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
7740                                    UserDefinedConversion)) {
7741       Best = end();
7742       return OR_Ambiguous;
7743     }
7744   }
7745 
7746   // Best is the best viable function.
7747   if (Best->Function &&
7748       (Best->Function->isDeleted() ||
7749        S.isFunctionConsideredUnavailable(Best->Function)))
7750     return OR_Deleted;
7751 
7752   return OR_Success;
7753 }
7754 
7755 namespace {
7756 
7757 enum OverloadCandidateKind {
7758   oc_function,
7759   oc_method,
7760   oc_constructor,
7761   oc_function_template,
7762   oc_method_template,
7763   oc_constructor_template,
7764   oc_implicit_default_constructor,
7765   oc_implicit_copy_constructor,
7766   oc_implicit_move_constructor,
7767   oc_implicit_copy_assignment,
7768   oc_implicit_move_assignment,
7769   oc_implicit_inherited_constructor
7770 };
7771 
ClassifyOverloadCandidate(Sema & S,FunctionDecl * Fn,std::string & Description)7772 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7773                                                 FunctionDecl *Fn,
7774                                                 std::string &Description) {
7775   bool isTemplate = false;
7776 
7777   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7778     isTemplate = true;
7779     Description = S.getTemplateArgumentBindingsText(
7780       FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7781   }
7782 
7783   if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
7784     if (!Ctor->isImplicit())
7785       return isTemplate ? oc_constructor_template : oc_constructor;
7786 
7787     if (Ctor->getInheritedConstructor())
7788       return oc_implicit_inherited_constructor;
7789 
7790     if (Ctor->isDefaultConstructor())
7791       return oc_implicit_default_constructor;
7792 
7793     if (Ctor->isMoveConstructor())
7794       return oc_implicit_move_constructor;
7795 
7796     assert(Ctor->isCopyConstructor() &&
7797            "unexpected sort of implicit constructor");
7798     return oc_implicit_copy_constructor;
7799   }
7800 
7801   if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7802     // This actually gets spelled 'candidate function' for now, but
7803     // it doesn't hurt to split it out.
7804     if (!Meth->isImplicit())
7805       return isTemplate ? oc_method_template : oc_method;
7806 
7807     if (Meth->isMoveAssignmentOperator())
7808       return oc_implicit_move_assignment;
7809 
7810     if (Meth->isCopyAssignmentOperator())
7811       return oc_implicit_copy_assignment;
7812 
7813     assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7814     return oc_method;
7815   }
7816 
7817   return isTemplate ? oc_function_template : oc_function;
7818 }
7819 
MaybeEmitInheritedConstructorNote(Sema & S,FunctionDecl * Fn)7820 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7821   const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7822   if (!Ctor) return;
7823 
7824   Ctor = Ctor->getInheritedConstructor();
7825   if (!Ctor) return;
7826 
7827   S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7828 }
7829 
7830 } // end anonymous namespace
7831 
7832 // Notes the location of an overload candidate.
NoteOverloadCandidate(FunctionDecl * Fn,QualType DestType)7833 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
7834   std::string FnDesc;
7835   OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
7836   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7837                              << (unsigned) K << FnDesc;
7838   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7839   Diag(Fn->getLocation(), PD);
7840   MaybeEmitInheritedConstructorNote(*this, Fn);
7841 }
7842 
7843 //Notes the location of all overload candidates designated through
7844 // OverloadedExpr
NoteAllOverloadCandidates(Expr * OverloadedExpr,QualType DestType)7845 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
7846   assert(OverloadedExpr->getType() == Context.OverloadTy);
7847 
7848   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7849   OverloadExpr *OvlExpr = Ovl.Expression;
7850 
7851   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7852                             IEnd = OvlExpr->decls_end();
7853        I != IEnd; ++I) {
7854     if (FunctionTemplateDecl *FunTmpl =
7855                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
7856       NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
7857     } else if (FunctionDecl *Fun
7858                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
7859       NoteOverloadCandidate(Fun, DestType);
7860     }
7861   }
7862 }
7863 
7864 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
7865 /// "lead" diagnostic; it will be given two arguments, the source and
7866 /// target types of the conversion.
DiagnoseAmbiguousConversion(Sema & S,SourceLocation CaretLoc,const PartialDiagnostic & PDiag) const7867 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7868                                  Sema &S,
7869                                  SourceLocation CaretLoc,
7870                                  const PartialDiagnostic &PDiag) const {
7871   S.Diag(CaretLoc, PDiag)
7872     << Ambiguous.getFromType() << Ambiguous.getToType();
7873   for (AmbiguousConversionSequence::const_iterator
7874          I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7875     S.NoteOverloadCandidate(*I);
7876   }
7877 }
7878 
7879 namespace {
7880 
DiagnoseBadConversion(Sema & S,OverloadCandidate * Cand,unsigned I)7881 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7882   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7883   assert(Conv.isBad());
7884   assert(Cand->Function && "for now, candidate must be a function");
7885   FunctionDecl *Fn = Cand->Function;
7886 
7887   // There's a conversion slot for the object argument if this is a
7888   // non-constructor method.  Note that 'I' corresponds the
7889   // conversion-slot index.
7890   bool isObjectArgument = false;
7891   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
7892     if (I == 0)
7893       isObjectArgument = true;
7894     else
7895       I--;
7896   }
7897 
7898   std::string FnDesc;
7899   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7900 
7901   Expr *FromExpr = Conv.Bad.FromExpr;
7902   QualType FromTy = Conv.Bad.getFromType();
7903   QualType ToTy = Conv.Bad.getToType();
7904 
7905   if (FromTy == S.Context.OverloadTy) {
7906     assert(FromExpr && "overload set argument came from implicit argument?");
7907     Expr *E = FromExpr->IgnoreParens();
7908     if (isa<UnaryOperator>(E))
7909       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
7910     DeclarationName Name = cast<OverloadExpr>(E)->getName();
7911 
7912     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7913       << (unsigned) FnKind << FnDesc
7914       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7915       << ToTy << Name << I+1;
7916     MaybeEmitInheritedConstructorNote(S, Fn);
7917     return;
7918   }
7919 
7920   // Do some hand-waving analysis to see if the non-viability is due
7921   // to a qualifier mismatch.
7922   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7923   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7924   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7925     CToTy = RT->getPointeeType();
7926   else {
7927     // TODO: detect and diagnose the full richness of const mismatches.
7928     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7929       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7930         CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7931   }
7932 
7933   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7934       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7935     Qualifiers FromQs = CFromTy.getQualifiers();
7936     Qualifiers ToQs = CToTy.getQualifiers();
7937 
7938     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7939       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7940         << (unsigned) FnKind << FnDesc
7941         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7942         << FromTy
7943         << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7944         << (unsigned) isObjectArgument << I+1;
7945       MaybeEmitInheritedConstructorNote(S, Fn);
7946       return;
7947     }
7948 
7949     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7950       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
7951         << (unsigned) FnKind << FnDesc
7952         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7953         << FromTy
7954         << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7955         << (unsigned) isObjectArgument << I+1;
7956       MaybeEmitInheritedConstructorNote(S, Fn);
7957       return;
7958     }
7959 
7960     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7961       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7962       << (unsigned) FnKind << FnDesc
7963       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7964       << FromTy
7965       << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7966       << (unsigned) isObjectArgument << I+1;
7967       MaybeEmitInheritedConstructorNote(S, Fn);
7968       return;
7969     }
7970 
7971     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7972     assert(CVR && "unexpected qualifiers mismatch");
7973 
7974     if (isObjectArgument) {
7975       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7976         << (unsigned) FnKind << FnDesc
7977         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7978         << FromTy << (CVR - 1);
7979     } else {
7980       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7981         << (unsigned) FnKind << FnDesc
7982         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7983         << FromTy << (CVR - 1) << I+1;
7984     }
7985     MaybeEmitInheritedConstructorNote(S, Fn);
7986     return;
7987   }
7988 
7989   // Special diagnostic for failure to convert an initializer list, since
7990   // telling the user that it has type void is not useful.
7991   if (FromExpr && isa<InitListExpr>(FromExpr)) {
7992     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7993       << (unsigned) FnKind << FnDesc
7994       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7995       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7996     MaybeEmitInheritedConstructorNote(S, Fn);
7997     return;
7998   }
7999 
8000   // Diagnose references or pointers to incomplete types differently,
8001   // since it's far from impossible that the incompleteness triggered
8002   // the failure.
8003   QualType TempFromTy = FromTy.getNonReferenceType();
8004   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8005     TempFromTy = PTy->getPointeeType();
8006   if (TempFromTy->isIncompleteType()) {
8007     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8008       << (unsigned) FnKind << FnDesc
8009       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8010       << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8011     MaybeEmitInheritedConstructorNote(S, Fn);
8012     return;
8013   }
8014 
8015   // Diagnose base -> derived pointer conversions.
8016   unsigned BaseToDerivedConversion = 0;
8017   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8018     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8019       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8020                                                FromPtrTy->getPointeeType()) &&
8021           !FromPtrTy->getPointeeType()->isIncompleteType() &&
8022           !ToPtrTy->getPointeeType()->isIncompleteType() &&
8023           S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8024                           FromPtrTy->getPointeeType()))
8025         BaseToDerivedConversion = 1;
8026     }
8027   } else if (const ObjCObjectPointerType *FromPtrTy
8028                                     = FromTy->getAs<ObjCObjectPointerType>()) {
8029     if (const ObjCObjectPointerType *ToPtrTy
8030                                         = ToTy->getAs<ObjCObjectPointerType>())
8031       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8032         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8033           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8034                                                 FromPtrTy->getPointeeType()) &&
8035               FromIface->isSuperClassOf(ToIface))
8036             BaseToDerivedConversion = 2;
8037   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8038       if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8039           !FromTy->isIncompleteType() &&
8040           !ToRefTy->getPointeeType()->isIncompleteType() &&
8041           S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
8042         BaseToDerivedConversion = 3;
8043     }
8044 
8045   if (BaseToDerivedConversion) {
8046     S.Diag(Fn->getLocation(),
8047            diag::note_ovl_candidate_bad_base_to_derived_conv)
8048       << (unsigned) FnKind << FnDesc
8049       << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8050       << (BaseToDerivedConversion - 1)
8051       << FromTy << ToTy << I+1;
8052     MaybeEmitInheritedConstructorNote(S, Fn);
8053     return;
8054   }
8055 
8056   if (isa<ObjCObjectPointerType>(CFromTy) &&
8057       isa<PointerType>(CToTy)) {
8058       Qualifiers FromQs = CFromTy.getQualifiers();
8059       Qualifiers ToQs = CToTy.getQualifiers();
8060       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8061         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8062         << (unsigned) FnKind << FnDesc
8063         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8064         << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8065         MaybeEmitInheritedConstructorNote(S, Fn);
8066         return;
8067       }
8068   }
8069 
8070   // Emit the generic diagnostic and, optionally, add the hints to it.
8071   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8072   FDiag << (unsigned) FnKind << FnDesc
8073     << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8074     << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8075     << (unsigned) (Cand->Fix.Kind);
8076 
8077   // If we can fix the conversion, suggest the FixIts.
8078   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8079        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8080     FDiag << *HI;
8081   S.Diag(Fn->getLocation(), FDiag);
8082 
8083   MaybeEmitInheritedConstructorNote(S, Fn);
8084 }
8085 
DiagnoseArityMismatch(Sema & S,OverloadCandidate * Cand,unsigned NumFormalArgs)8086 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8087                            unsigned NumFormalArgs) {
8088   // TODO: treat calls to a missing default constructor as a special case
8089 
8090   FunctionDecl *Fn = Cand->Function;
8091   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8092 
8093   unsigned MinParams = Fn->getMinRequiredArguments();
8094 
8095   // With invalid overloaded operators, it's possible that we think we
8096   // have an arity mismatch when it fact it looks like we have the
8097   // right number of arguments, because only overloaded operators have
8098   // the weird behavior of overloading member and non-member functions.
8099   // Just don't report anything.
8100   if (Fn->isInvalidDecl() &&
8101       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8102     return;
8103 
8104   // at least / at most / exactly
8105   unsigned mode, modeCount;
8106   if (NumFormalArgs < MinParams) {
8107     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8108            (Cand->FailureKind == ovl_fail_bad_deduction &&
8109             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8110     if (MinParams != FnTy->getNumArgs() ||
8111         FnTy->isVariadic() || FnTy->isTemplateVariadic())
8112       mode = 0; // "at least"
8113     else
8114       mode = 2; // "exactly"
8115     modeCount = MinParams;
8116   } else {
8117     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8118            (Cand->FailureKind == ovl_fail_bad_deduction &&
8119             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8120     if (MinParams != FnTy->getNumArgs())
8121       mode = 1; // "at most"
8122     else
8123       mode = 2; // "exactly"
8124     modeCount = FnTy->getNumArgs();
8125   }
8126 
8127   std::string Description;
8128   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8129 
8130   S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8131     << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8132     << modeCount << NumFormalArgs;
8133   MaybeEmitInheritedConstructorNote(S, Fn);
8134 }
8135 
8136 /// Diagnose a failed template-argument deduction.
DiagnoseBadDeduction(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)8137 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
8138                           unsigned NumArgs) {
8139   FunctionDecl *Fn = Cand->Function; // pattern
8140 
8141   TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
8142   NamedDecl *ParamD;
8143   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8144   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8145   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8146   switch (Cand->DeductionFailure.Result) {
8147   case Sema::TDK_Success:
8148     llvm_unreachable("TDK_success while diagnosing bad deduction");
8149 
8150   case Sema::TDK_Incomplete: {
8151     assert(ParamD && "no parameter found for incomplete deduction result");
8152     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8153       << ParamD->getDeclName();
8154     MaybeEmitInheritedConstructorNote(S, Fn);
8155     return;
8156   }
8157 
8158   case Sema::TDK_Underqualified: {
8159     assert(ParamD && "no parameter found for bad qualifiers deduction result");
8160     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8161 
8162     QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8163 
8164     // Param will have been canonicalized, but it should just be a
8165     // qualified version of ParamD, so move the qualifiers to that.
8166     QualifierCollector Qs;
8167     Qs.strip(Param);
8168     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8169     assert(S.Context.hasSameType(Param, NonCanonParam));
8170 
8171     // Arg has also been canonicalized, but there's nothing we can do
8172     // about that.  It also doesn't matter as much, because it won't
8173     // have any template parameters in it (because deduction isn't
8174     // done on dependent types).
8175     QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8176 
8177     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8178       << ParamD->getDeclName() << Arg << NonCanonParam;
8179     MaybeEmitInheritedConstructorNote(S, Fn);
8180     return;
8181   }
8182 
8183   case Sema::TDK_Inconsistent: {
8184     assert(ParamD && "no parameter found for inconsistent deduction result");
8185     int which = 0;
8186     if (isa<TemplateTypeParmDecl>(ParamD))
8187       which = 0;
8188     else if (isa<NonTypeTemplateParmDecl>(ParamD))
8189       which = 1;
8190     else {
8191       which = 2;
8192     }
8193 
8194     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
8195       << which << ParamD->getDeclName()
8196       << *Cand->DeductionFailure.getFirstArg()
8197       << *Cand->DeductionFailure.getSecondArg();
8198     MaybeEmitInheritedConstructorNote(S, Fn);
8199     return;
8200   }
8201 
8202   case Sema::TDK_InvalidExplicitArguments:
8203     assert(ParamD && "no parameter found for invalid explicit arguments");
8204     if (ParamD->getDeclName())
8205       S.Diag(Fn->getLocation(),
8206              diag::note_ovl_candidate_explicit_arg_mismatch_named)
8207         << ParamD->getDeclName();
8208     else {
8209       int index = 0;
8210       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8211         index = TTP->getIndex();
8212       else if (NonTypeTemplateParmDecl *NTTP
8213                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8214         index = NTTP->getIndex();
8215       else
8216         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8217       S.Diag(Fn->getLocation(),
8218              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8219         << (index + 1);
8220     }
8221     MaybeEmitInheritedConstructorNote(S, Fn);
8222     return;
8223 
8224   case Sema::TDK_TooManyArguments:
8225   case Sema::TDK_TooFewArguments:
8226     DiagnoseArityMismatch(S, Cand, NumArgs);
8227     return;
8228 
8229   case Sema::TDK_InstantiationDepth:
8230     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
8231     MaybeEmitInheritedConstructorNote(S, Fn);
8232     return;
8233 
8234   case Sema::TDK_SubstitutionFailure: {
8235     std::string ArgString;
8236     if (TemplateArgumentList *Args
8237                             = Cand->DeductionFailure.getTemplateArgumentList())
8238       ArgString = S.getTemplateArgumentBindingsText(
8239                     Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8240                                                     *Args);
8241     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8242       << ArgString;
8243     MaybeEmitInheritedConstructorNote(S, Fn);
8244     return;
8245   }
8246 
8247   // TODO: diagnose these individually, then kill off
8248   // note_ovl_candidate_bad_deduction, which is uselessly vague.
8249   case Sema::TDK_NonDeducedMismatch:
8250   case Sema::TDK_FailedOverloadResolution:
8251     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
8252     MaybeEmitInheritedConstructorNote(S, Fn);
8253     return;
8254   }
8255 }
8256 
8257 /// CUDA: diagnose an invalid call across targets.
DiagnoseBadTarget(Sema & S,OverloadCandidate * Cand)8258 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8259   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8260   FunctionDecl *Callee = Cand->Function;
8261 
8262   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8263                            CalleeTarget = S.IdentifyCUDATarget(Callee);
8264 
8265   std::string FnDesc;
8266   OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8267 
8268   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8269       << (unsigned) FnKind << CalleeTarget << CallerTarget;
8270 }
8271 
8272 /// Generates a 'note' diagnostic for an overload candidate.  We've
8273 /// already generated a primary error at the call site.
8274 ///
8275 /// It really does need to be a single diagnostic with its caret
8276 /// pointed at the candidate declaration.  Yes, this creates some
8277 /// major challenges of technical writing.  Yes, this makes pointing
8278 /// out problems with specific arguments quite awkward.  It's still
8279 /// better than generating twenty screens of text for every failed
8280 /// overload.
8281 ///
8282 /// It would be great to be able to express per-candidate problems
8283 /// more richly for those diagnostic clients that cared, but we'd
8284 /// still have to be just as careful with the default diagnostics.
NoteFunctionCandidate(Sema & S,OverloadCandidate * Cand,unsigned NumArgs)8285 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
8286                            unsigned NumArgs) {
8287   FunctionDecl *Fn = Cand->Function;
8288 
8289   // Note deleted candidates, but only if they're viable.
8290   if (Cand->Viable && (Fn->isDeleted() ||
8291       S.isFunctionConsideredUnavailable(Fn))) {
8292     std::string FnDesc;
8293     OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8294 
8295     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
8296       << FnKind << FnDesc
8297       << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
8298     MaybeEmitInheritedConstructorNote(S, Fn);
8299     return;
8300   }
8301 
8302   // We don't really have anything else to say about viable candidates.
8303   if (Cand->Viable) {
8304     S.NoteOverloadCandidate(Fn);
8305     return;
8306   }
8307 
8308   switch (Cand->FailureKind) {
8309   case ovl_fail_too_many_arguments:
8310   case ovl_fail_too_few_arguments:
8311     return DiagnoseArityMismatch(S, Cand, NumArgs);
8312 
8313   case ovl_fail_bad_deduction:
8314     return DiagnoseBadDeduction(S, Cand, NumArgs);
8315 
8316   case ovl_fail_trivial_conversion:
8317   case ovl_fail_bad_final_conversion:
8318   case ovl_fail_final_conversion_not_exact:
8319     return S.NoteOverloadCandidate(Fn);
8320 
8321   case ovl_fail_bad_conversion: {
8322     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
8323     for (unsigned N = Cand->NumConversions; I != N; ++I)
8324       if (Cand->Conversions[I].isBad())
8325         return DiagnoseBadConversion(S, Cand, I);
8326 
8327     // FIXME: this currently happens when we're called from SemaInit
8328     // when user-conversion overload fails.  Figure out how to handle
8329     // those conditions and diagnose them well.
8330     return S.NoteOverloadCandidate(Fn);
8331   }
8332 
8333   case ovl_fail_bad_target:
8334     return DiagnoseBadTarget(S, Cand);
8335   }
8336 }
8337 
NoteSurrogateCandidate(Sema & S,OverloadCandidate * Cand)8338 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8339   // Desugar the type of the surrogate down to a function type,
8340   // retaining as many typedefs as possible while still showing
8341   // the function type (and, therefore, its parameter types).
8342   QualType FnType = Cand->Surrogate->getConversionType();
8343   bool isLValueReference = false;
8344   bool isRValueReference = false;
8345   bool isPointer = false;
8346   if (const LValueReferenceType *FnTypeRef =
8347         FnType->getAs<LValueReferenceType>()) {
8348     FnType = FnTypeRef->getPointeeType();
8349     isLValueReference = true;
8350   } else if (const RValueReferenceType *FnTypeRef =
8351                FnType->getAs<RValueReferenceType>()) {
8352     FnType = FnTypeRef->getPointeeType();
8353     isRValueReference = true;
8354   }
8355   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8356     FnType = FnTypePtr->getPointeeType();
8357     isPointer = true;
8358   }
8359   // Desugar down to a function type.
8360   FnType = QualType(FnType->getAs<FunctionType>(), 0);
8361   // Reconstruct the pointer/reference as appropriate.
8362   if (isPointer) FnType = S.Context.getPointerType(FnType);
8363   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8364   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8365 
8366   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8367     << FnType;
8368   MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
8369 }
8370 
NoteBuiltinOperatorCandidate(Sema & S,const char * Opc,SourceLocation OpLoc,OverloadCandidate * Cand)8371 void NoteBuiltinOperatorCandidate(Sema &S,
8372                                   const char *Opc,
8373                                   SourceLocation OpLoc,
8374                                   OverloadCandidate *Cand) {
8375   assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
8376   std::string TypeStr("operator");
8377   TypeStr += Opc;
8378   TypeStr += "(";
8379   TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
8380   if (Cand->NumConversions == 1) {
8381     TypeStr += ")";
8382     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8383   } else {
8384     TypeStr += ", ";
8385     TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8386     TypeStr += ")";
8387     S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8388   }
8389 }
8390 
NoteAmbiguousUserConversions(Sema & S,SourceLocation OpLoc,OverloadCandidate * Cand)8391 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8392                                   OverloadCandidate *Cand) {
8393   unsigned NoOperands = Cand->NumConversions;
8394   for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8395     const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
8396     if (ICS.isBad()) break; // all meaningless after first invalid
8397     if (!ICS.isAmbiguous()) continue;
8398 
8399     ICS.DiagnoseAmbiguousConversion(S, OpLoc,
8400                               S.PDiag(diag::note_ambiguous_type_conversion));
8401   }
8402 }
8403 
GetLocationForCandidate(const OverloadCandidate * Cand)8404 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8405   if (Cand->Function)
8406     return Cand->Function->getLocation();
8407   if (Cand->IsSurrogate)
8408     return Cand->Surrogate->getLocation();
8409   return SourceLocation();
8410 }
8411 
8412 static unsigned
RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo & DFI)8413 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
8414   switch ((Sema::TemplateDeductionResult)DFI.Result) {
8415   case Sema::TDK_Success:
8416     llvm_unreachable("TDK_success while diagnosing bad deduction");
8417 
8418   case Sema::TDK_Incomplete:
8419     return 1;
8420 
8421   case Sema::TDK_Underqualified:
8422   case Sema::TDK_Inconsistent:
8423     return 2;
8424 
8425   case Sema::TDK_SubstitutionFailure:
8426   case Sema::TDK_NonDeducedMismatch:
8427     return 3;
8428 
8429   case Sema::TDK_InstantiationDepth:
8430   case Sema::TDK_FailedOverloadResolution:
8431     return 4;
8432 
8433   case Sema::TDK_InvalidExplicitArguments:
8434     return 5;
8435 
8436   case Sema::TDK_TooManyArguments:
8437   case Sema::TDK_TooFewArguments:
8438     return 6;
8439   }
8440   llvm_unreachable("Unhandled deduction result");
8441 }
8442 
8443 struct CompareOverloadCandidatesForDisplay {
8444   Sema &S;
CompareOverloadCandidatesForDisplayclang::__anond0ceed770611::CompareOverloadCandidatesForDisplay8445   CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
8446 
operator ()clang::__anond0ceed770611::CompareOverloadCandidatesForDisplay8447   bool operator()(const OverloadCandidate *L,
8448                   const OverloadCandidate *R) {
8449     // Fast-path this check.
8450     if (L == R) return false;
8451 
8452     // Order first by viability.
8453     if (L->Viable) {
8454       if (!R->Viable) return true;
8455 
8456       // TODO: introduce a tri-valued comparison for overload
8457       // candidates.  Would be more worthwhile if we had a sort
8458       // that could exploit it.
8459       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8460       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
8461     } else if (R->Viable)
8462       return false;
8463 
8464     assert(L->Viable == R->Viable);
8465 
8466     // Criteria by which we can sort non-viable candidates:
8467     if (!L->Viable) {
8468       // 1. Arity mismatches come after other candidates.
8469       if (L->FailureKind == ovl_fail_too_many_arguments ||
8470           L->FailureKind == ovl_fail_too_few_arguments)
8471         return false;
8472       if (R->FailureKind == ovl_fail_too_many_arguments ||
8473           R->FailureKind == ovl_fail_too_few_arguments)
8474         return true;
8475 
8476       // 2. Bad conversions come first and are ordered by the number
8477       // of bad conversions and quality of good conversions.
8478       if (L->FailureKind == ovl_fail_bad_conversion) {
8479         if (R->FailureKind != ovl_fail_bad_conversion)
8480           return true;
8481 
8482         // The conversion that can be fixed with a smaller number of changes,
8483         // comes first.
8484         unsigned numLFixes = L->Fix.NumConversionsFixed;
8485         unsigned numRFixes = R->Fix.NumConversionsFixed;
8486         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8487         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
8488         if (numLFixes != numRFixes) {
8489           if (numLFixes < numRFixes)
8490             return true;
8491           else
8492             return false;
8493         }
8494 
8495         // If there's any ordering between the defined conversions...
8496         // FIXME: this might not be transitive.
8497         assert(L->NumConversions == R->NumConversions);
8498 
8499         int leftBetter = 0;
8500         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
8501         for (unsigned E = L->NumConversions; I != E; ++I) {
8502           switch (CompareImplicitConversionSequences(S,
8503                                                      L->Conversions[I],
8504                                                      R->Conversions[I])) {
8505           case ImplicitConversionSequence::Better:
8506             leftBetter++;
8507             break;
8508 
8509           case ImplicitConversionSequence::Worse:
8510             leftBetter--;
8511             break;
8512 
8513           case ImplicitConversionSequence::Indistinguishable:
8514             break;
8515           }
8516         }
8517         if (leftBetter > 0) return true;
8518         if (leftBetter < 0) return false;
8519 
8520       } else if (R->FailureKind == ovl_fail_bad_conversion)
8521         return false;
8522 
8523       if (L->FailureKind == ovl_fail_bad_deduction) {
8524         if (R->FailureKind != ovl_fail_bad_deduction)
8525           return true;
8526 
8527         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8528           return RankDeductionFailure(L->DeductionFailure)
8529                < RankDeductionFailure(R->DeductionFailure);
8530       } else if (R->FailureKind == ovl_fail_bad_deduction)
8531         return false;
8532 
8533       // TODO: others?
8534     }
8535 
8536     // Sort everything else by location.
8537     SourceLocation LLoc = GetLocationForCandidate(L);
8538     SourceLocation RLoc = GetLocationForCandidate(R);
8539 
8540     // Put candidates without locations (e.g. builtins) at the end.
8541     if (LLoc.isInvalid()) return false;
8542     if (RLoc.isInvalid()) return true;
8543 
8544     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
8545   }
8546 };
8547 
8548 /// CompleteNonViableCandidate - Normally, overload resolution only
8549 /// computes up to the first. Produces the FixIt set if possible.
CompleteNonViableCandidate(Sema & S,OverloadCandidate * Cand,llvm::ArrayRef<Expr * > Args)8550 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
8551                                 llvm::ArrayRef<Expr *> Args) {
8552   assert(!Cand->Viable);
8553 
8554   // Don't do anything on failures other than bad conversion.
8555   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8556 
8557   // We only want the FixIts if all the arguments can be corrected.
8558   bool Unfixable = false;
8559   // Use a implicit copy initialization to check conversion fixes.
8560   Cand->Fix.setConversionChecker(TryCopyInitialization);
8561 
8562   // Skip forward to the first bad conversion.
8563   unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
8564   unsigned ConvCount = Cand->NumConversions;
8565   while (true) {
8566     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8567     ConvIdx++;
8568     if (Cand->Conversions[ConvIdx - 1].isBad()) {
8569       Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
8570       break;
8571     }
8572   }
8573 
8574   if (ConvIdx == ConvCount)
8575     return;
8576 
8577   assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8578          "remaining conversion is initialized?");
8579 
8580   // FIXME: this should probably be preserved from the overload
8581   // operation somehow.
8582   bool SuppressUserConversions = false;
8583 
8584   const FunctionProtoType* Proto;
8585   unsigned ArgIdx = ConvIdx;
8586 
8587   if (Cand->IsSurrogate) {
8588     QualType ConvType
8589       = Cand->Surrogate->getConversionType().getNonReferenceType();
8590     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8591       ConvType = ConvPtrType->getPointeeType();
8592     Proto = ConvType->getAs<FunctionProtoType>();
8593     ArgIdx--;
8594   } else if (Cand->Function) {
8595     Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8596     if (isa<CXXMethodDecl>(Cand->Function) &&
8597         !isa<CXXConstructorDecl>(Cand->Function))
8598       ArgIdx--;
8599   } else {
8600     // Builtin binary operator with a bad first conversion.
8601     assert(ConvCount <= 3);
8602     for (; ConvIdx != ConvCount; ++ConvIdx)
8603       Cand->Conversions[ConvIdx]
8604         = TryCopyInitialization(S, Args[ConvIdx],
8605                                 Cand->BuiltinTypes.ParamTypes[ConvIdx],
8606                                 SuppressUserConversions,
8607                                 /*InOverloadResolution*/ true,
8608                                 /*AllowObjCWritebackConversion=*/
8609                                   S.getLangOpts().ObjCAutoRefCount);
8610     return;
8611   }
8612 
8613   // Fill in the rest of the conversions.
8614   unsigned NumArgsInProto = Proto->getNumArgs();
8615   for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
8616     if (ArgIdx < NumArgsInProto) {
8617       Cand->Conversions[ConvIdx]
8618         = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
8619                                 SuppressUserConversions,
8620                                 /*InOverloadResolution=*/true,
8621                                 /*AllowObjCWritebackConversion=*/
8622                                   S.getLangOpts().ObjCAutoRefCount);
8623       // Store the FixIt in the candidate if it exists.
8624       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
8625         Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
8626     }
8627     else
8628       Cand->Conversions[ConvIdx].setEllipsis();
8629   }
8630 }
8631 
8632 } // end anonymous namespace
8633 
8634 /// PrintOverloadCandidates - When overload resolution fails, prints
8635 /// diagnostic messages containing the candidates in the candidate
8636 /// set.
NoteCandidates(Sema & S,OverloadCandidateDisplayKind OCD,llvm::ArrayRef<Expr * > Args,const char * Opc,SourceLocation OpLoc)8637 void OverloadCandidateSet::NoteCandidates(Sema &S,
8638                                           OverloadCandidateDisplayKind OCD,
8639                                           llvm::ArrayRef<Expr *> Args,
8640                                           const char *Opc,
8641                                           SourceLocation OpLoc) {
8642   // Sort the candidates by viability and position.  Sorting directly would
8643   // be prohibitive, so we make a set of pointers and sort those.
8644   SmallVector<OverloadCandidate*, 32> Cands;
8645   if (OCD == OCD_AllCandidates) Cands.reserve(size());
8646   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
8647     if (Cand->Viable)
8648       Cands.push_back(Cand);
8649     else if (OCD == OCD_AllCandidates) {
8650       CompleteNonViableCandidate(S, Cand, Args);
8651       if (Cand->Function || Cand->IsSurrogate)
8652         Cands.push_back(Cand);
8653       // Otherwise, this a non-viable builtin candidate.  We do not, in general,
8654       // want to list every possible builtin candidate.
8655     }
8656   }
8657 
8658   std::sort(Cands.begin(), Cands.end(),
8659             CompareOverloadCandidatesForDisplay(S));
8660 
8661   bool ReportedAmbiguousConversions = false;
8662 
8663   SmallVectorImpl<OverloadCandidate*>::iterator I, E;
8664   const DiagnosticsEngine::OverloadsShown ShowOverloads =
8665       S.Diags.getShowOverloads();
8666   unsigned CandsShown = 0;
8667   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8668     OverloadCandidate *Cand = *I;
8669 
8670     // Set an arbitrary limit on the number of candidate functions we'll spam
8671     // the user with.  FIXME: This limit should depend on details of the
8672     // candidate list.
8673     if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
8674       break;
8675     }
8676     ++CandsShown;
8677 
8678     if (Cand->Function)
8679       NoteFunctionCandidate(S, Cand, Args.size());
8680     else if (Cand->IsSurrogate)
8681       NoteSurrogateCandidate(S, Cand);
8682     else {
8683       assert(Cand->Viable &&
8684              "Non-viable built-in candidates are not added to Cands.");
8685       // Generally we only see ambiguities including viable builtin
8686       // operators if overload resolution got screwed up by an
8687       // ambiguous user-defined conversion.
8688       //
8689       // FIXME: It's quite possible for different conversions to see
8690       // different ambiguities, though.
8691       if (!ReportedAmbiguousConversions) {
8692         NoteAmbiguousUserConversions(S, OpLoc, Cand);
8693         ReportedAmbiguousConversions = true;
8694       }
8695 
8696       // If this is a viable builtin, print it.
8697       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
8698     }
8699   }
8700 
8701   if (I != E)
8702     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
8703 }
8704 
8705 // [PossiblyAFunctionType]  -->   [Return]
8706 // NonFunctionType --> NonFunctionType
8707 // R (A) --> R(A)
8708 // R (*)(A) --> R (A)
8709 // R (&)(A) --> R (A)
8710 // R (S::*)(A) --> R (A)
ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)8711 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8712   QualType Ret = PossiblyAFunctionType;
8713   if (const PointerType *ToTypePtr =
8714     PossiblyAFunctionType->getAs<PointerType>())
8715     Ret = ToTypePtr->getPointeeType();
8716   else if (const ReferenceType *ToTypeRef =
8717     PossiblyAFunctionType->getAs<ReferenceType>())
8718     Ret = ToTypeRef->getPointeeType();
8719   else if (const MemberPointerType *MemTypePtr =
8720     PossiblyAFunctionType->getAs<MemberPointerType>())
8721     Ret = MemTypePtr->getPointeeType();
8722   Ret =
8723     Context.getCanonicalType(Ret).getUnqualifiedType();
8724   return Ret;
8725 }
8726 
8727 // A helper class to help with address of function resolution
8728 // - allows us to avoid passing around all those ugly parameters
8729 class AddressOfFunctionResolver
8730 {
8731   Sema& S;
8732   Expr* SourceExpr;
8733   const QualType& TargetType;
8734   QualType TargetFunctionType; // Extracted function type from target type
8735 
8736   bool Complain;
8737   //DeclAccessPair& ResultFunctionAccessPair;
8738   ASTContext& Context;
8739 
8740   bool TargetTypeIsNonStaticMemberFunction;
8741   bool FoundNonTemplateFunction;
8742 
8743   OverloadExpr::FindResult OvlExprInfo;
8744   OverloadExpr *OvlExpr;
8745   TemplateArgumentListInfo OvlExplicitTemplateArgs;
8746   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
8747 
8748 public:
AddressOfFunctionResolver(Sema & S,Expr * SourceExpr,const QualType & TargetType,bool Complain)8749   AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8750                             const QualType& TargetType, bool Complain)
8751     : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8752       Complain(Complain), Context(S.getASTContext()),
8753       TargetTypeIsNonStaticMemberFunction(
8754                                     !!TargetType->getAs<MemberPointerType>()),
8755       FoundNonTemplateFunction(false),
8756       OvlExprInfo(OverloadExpr::find(SourceExpr)),
8757       OvlExpr(OvlExprInfo.Expression)
8758   {
8759     ExtractUnqualifiedFunctionTypeFromTargetType();
8760 
8761     if (!TargetFunctionType->isFunctionType()) {
8762       if (OvlExpr->hasExplicitTemplateArgs()) {
8763         DeclAccessPair dap;
8764         if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
8765                                             OvlExpr, false, &dap) ) {
8766 
8767           if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8768             if (!Method->isStatic()) {
8769               // If the target type is a non-function type and the function
8770               // found is a non-static member function, pretend as if that was
8771               // the target, it's the only possible type to end up with.
8772               TargetTypeIsNonStaticMemberFunction = true;
8773 
8774               // And skip adding the function if its not in the proper form.
8775               // We'll diagnose this due to an empty set of functions.
8776               if (!OvlExprInfo.HasFormOfMemberPointer)
8777                 return;
8778             }
8779           }
8780 
8781           Matches.push_back(std::make_pair(dap,Fn));
8782         }
8783       }
8784       return;
8785     }
8786 
8787     if (OvlExpr->hasExplicitTemplateArgs())
8788       OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
8789 
8790     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8791       // C++ [over.over]p4:
8792       //   If more than one function is selected, [...]
8793       if (Matches.size() > 1) {
8794         if (FoundNonTemplateFunction)
8795           EliminateAllTemplateMatches();
8796         else
8797           EliminateAllExceptMostSpecializedTemplate();
8798       }
8799     }
8800   }
8801 
8802 private:
isTargetTypeAFunction() const8803   bool isTargetTypeAFunction() const {
8804     return TargetFunctionType->isFunctionType();
8805   }
8806 
8807   // [ToType]     [Return]
8808 
8809   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8810   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8811   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
ExtractUnqualifiedFunctionTypeFromTargetType()8812   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8813     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8814   }
8815 
8816   // return true if any matching specializations were found
AddMatchingTemplateFunction(FunctionTemplateDecl * FunctionTemplate,const DeclAccessPair & CurAccessFunPair)8817   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8818                                    const DeclAccessPair& CurAccessFunPair) {
8819     if (CXXMethodDecl *Method
8820               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8821       // Skip non-static function templates when converting to pointer, and
8822       // static when converting to member pointer.
8823       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8824         return false;
8825     }
8826     else if (TargetTypeIsNonStaticMemberFunction)
8827       return false;
8828 
8829     // C++ [over.over]p2:
8830     //   If the name is a function template, template argument deduction is
8831     //   done (14.8.2.2), and if the argument deduction succeeds, the
8832     //   resulting template argument list is used to generate a single
8833     //   function template specialization, which is added to the set of
8834     //   overloaded functions considered.
8835     FunctionDecl *Specialization = 0;
8836     TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8837     if (Sema::TemplateDeductionResult Result
8838           = S.DeduceTemplateArguments(FunctionTemplate,
8839                                       &OvlExplicitTemplateArgs,
8840                                       TargetFunctionType, Specialization,
8841                                       Info)) {
8842       // FIXME: make a note of the failed deduction for diagnostics.
8843       (void)Result;
8844       return false;
8845     }
8846 
8847     // Template argument deduction ensures that we have an exact match.
8848     // This function template specicalization works.
8849     Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8850     assert(TargetFunctionType
8851                       == Context.getCanonicalType(Specialization->getType()));
8852     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8853     return true;
8854   }
8855 
AddMatchingNonTemplateFunction(NamedDecl * Fn,const DeclAccessPair & CurAccessFunPair)8856   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8857                                       const DeclAccessPair& CurAccessFunPair) {
8858     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8859       // Skip non-static functions when converting to pointer, and static
8860       // when converting to member pointer.
8861       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8862         return false;
8863     }
8864     else if (TargetTypeIsNonStaticMemberFunction)
8865       return false;
8866 
8867     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
8868       if (S.getLangOpts().CUDA)
8869         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8870           if (S.CheckCUDATarget(Caller, FunDecl))
8871             return false;
8872 
8873       QualType ResultTy;
8874       if (Context.hasSameUnqualifiedType(TargetFunctionType,
8875                                          FunDecl->getType()) ||
8876           S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8877                                  ResultTy)) {
8878         Matches.push_back(std::make_pair(CurAccessFunPair,
8879           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
8880         FoundNonTemplateFunction = true;
8881         return true;
8882       }
8883     }
8884 
8885     return false;
8886   }
8887 
FindAllFunctionsThatMatchTargetTypeExactly()8888   bool FindAllFunctionsThatMatchTargetTypeExactly() {
8889     bool Ret = false;
8890 
8891     // If the overload expression doesn't have the form of a pointer to
8892     // member, don't try to convert it to a pointer-to-member type.
8893     if (IsInvalidFormOfPointerToMemberFunction())
8894       return false;
8895 
8896     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8897                                E = OvlExpr->decls_end();
8898          I != E; ++I) {
8899       // Look through any using declarations to find the underlying function.
8900       NamedDecl *Fn = (*I)->getUnderlyingDecl();
8901 
8902       // C++ [over.over]p3:
8903       //   Non-member functions and static member functions match
8904       //   targets of type "pointer-to-function" or "reference-to-function."
8905       //   Nonstatic member functions match targets of
8906       //   type "pointer-to-member-function."
8907       // Note that according to DR 247, the containing class does not matter.
8908       if (FunctionTemplateDecl *FunctionTemplate
8909                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
8910         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8911           Ret = true;
8912       }
8913       // If we have explicit template arguments supplied, skip non-templates.
8914       else if (!OvlExpr->hasExplicitTemplateArgs() &&
8915                AddMatchingNonTemplateFunction(Fn, I.getPair()))
8916         Ret = true;
8917     }
8918     assert(Ret || Matches.empty());
8919     return Ret;
8920   }
8921 
EliminateAllExceptMostSpecializedTemplate()8922   void EliminateAllExceptMostSpecializedTemplate() {
8923     //   [...] and any given function template specialization F1 is
8924     //   eliminated if the set contains a second function template
8925     //   specialization whose function template is more specialized
8926     //   than the function template of F1 according to the partial
8927     //   ordering rules of 14.5.5.2.
8928 
8929     // The algorithm specified above is quadratic. We instead use a
8930     // two-pass algorithm (similar to the one used to identify the
8931     // best viable function in an overload set) that identifies the
8932     // best function template (if it exists).
8933 
8934     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8935     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8936       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
8937 
8938     UnresolvedSetIterator Result =
8939       S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8940                            TPOC_Other, 0, SourceExpr->getLocStart(),
8941                            S.PDiag(),
8942                            S.PDiag(diag::err_addr_ovl_ambiguous)
8943                              << Matches[0].second->getDeclName(),
8944                            S.PDiag(diag::note_ovl_candidate)
8945                              << (unsigned) oc_function_template,
8946                            Complain, TargetFunctionType);
8947 
8948     if (Result != MatchesCopy.end()) {
8949       // Make it the first and only element
8950       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8951       Matches[0].second = cast<FunctionDecl>(*Result);
8952       Matches.resize(1);
8953     }
8954   }
8955 
EliminateAllTemplateMatches()8956   void EliminateAllTemplateMatches() {
8957     //   [...] any function template specializations in the set are
8958     //   eliminated if the set also contains a non-template function, [...]
8959     for (unsigned I = 0, N = Matches.size(); I != N; ) {
8960       if (Matches[I].second->getPrimaryTemplate() == 0)
8961         ++I;
8962       else {
8963         Matches[I] = Matches[--N];
8964         Matches.set_size(N);
8965       }
8966     }
8967   }
8968 
8969 public:
ComplainNoMatchesFound() const8970   void ComplainNoMatchesFound() const {
8971     assert(Matches.empty());
8972     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8973         << OvlExpr->getName() << TargetFunctionType
8974         << OvlExpr->getSourceRange();
8975     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
8976   }
8977 
IsInvalidFormOfPointerToMemberFunction() const8978   bool IsInvalidFormOfPointerToMemberFunction() const {
8979     return TargetTypeIsNonStaticMemberFunction &&
8980       !OvlExprInfo.HasFormOfMemberPointer;
8981   }
8982 
ComplainIsInvalidFormOfPointerToMemberFunction() const8983   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8984       // TODO: Should we condition this on whether any functions might
8985       // have matched, or is it more appropriate to do that in callers?
8986       // TODO: a fixit wouldn't hurt.
8987       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8988         << TargetType << OvlExpr->getSourceRange();
8989   }
8990 
ComplainOfInvalidConversion() const8991   void ComplainOfInvalidConversion() const {
8992     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8993       << OvlExpr->getName() << TargetType;
8994   }
8995 
ComplainMultipleMatchesFound() const8996   void ComplainMultipleMatchesFound() const {
8997     assert(Matches.size() > 1);
8998     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8999       << OvlExpr->getName()
9000       << OvlExpr->getSourceRange();
9001     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9002   }
9003 
hadMultipleCandidates() const9004   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9005 
getNumMatches() const9006   int getNumMatches() const { return Matches.size(); }
9007 
getMatchingFunctionDecl() const9008   FunctionDecl* getMatchingFunctionDecl() const {
9009     if (Matches.size() != 1) return 0;
9010     return Matches[0].second;
9011   }
9012 
getMatchingFunctionAccessPair() const9013   const DeclAccessPair* getMatchingFunctionAccessPair() const {
9014     if (Matches.size() != 1) return 0;
9015     return &Matches[0].first;
9016   }
9017 };
9018 
9019 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9020 /// an overloaded function (C++ [over.over]), where @p From is an
9021 /// expression with overloaded function type and @p ToType is the type
9022 /// we're trying to resolve to. For example:
9023 ///
9024 /// @code
9025 /// int f(double);
9026 /// int f(int);
9027 ///
9028 /// int (*pfd)(double) = f; // selects f(double)
9029 /// @endcode
9030 ///
9031 /// This routine returns the resulting FunctionDecl if it could be
9032 /// resolved, and NULL otherwise. When @p Complain is true, this
9033 /// routine will emit diagnostics if there is an error.
9034 FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr * AddressOfExpr,QualType TargetType,bool Complain,DeclAccessPair & FoundResult,bool * pHadMultipleCandidates)9035 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9036                                          QualType TargetType,
9037                                          bool Complain,
9038                                          DeclAccessPair &FoundResult,
9039                                          bool *pHadMultipleCandidates) {
9040   assert(AddressOfExpr->getType() == Context.OverloadTy);
9041 
9042   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9043                                      Complain);
9044   int NumMatches = Resolver.getNumMatches();
9045   FunctionDecl* Fn = 0;
9046   if (NumMatches == 0 && Complain) {
9047     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9048       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9049     else
9050       Resolver.ComplainNoMatchesFound();
9051   }
9052   else if (NumMatches > 1 && Complain)
9053     Resolver.ComplainMultipleMatchesFound();
9054   else if (NumMatches == 1) {
9055     Fn = Resolver.getMatchingFunctionDecl();
9056     assert(Fn);
9057     FoundResult = *Resolver.getMatchingFunctionAccessPair();
9058     MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
9059     if (Complain)
9060       CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9061   }
9062 
9063   if (pHadMultipleCandidates)
9064     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
9065   return Fn;
9066 }
9067 
9068 /// \brief Given an expression that refers to an overloaded function, try to
9069 /// resolve that overloaded function expression down to a single function.
9070 ///
9071 /// This routine can only resolve template-ids that refer to a single function
9072 /// template, where that template-id refers to a single template whose template
9073 /// arguments are either provided by the template-id or have defaults,
9074 /// as described in C++0x [temp.arg.explicit]p3.
9075 FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr * ovl,bool Complain,DeclAccessPair * FoundResult)9076 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9077                                                   bool Complain,
9078                                                   DeclAccessPair *FoundResult) {
9079   // C++ [over.over]p1:
9080   //   [...] [Note: any redundant set of parentheses surrounding the
9081   //   overloaded function name is ignored (5.1). ]
9082   // C++ [over.over]p1:
9083   //   [...] The overloaded function name can be preceded by the &
9084   //   operator.
9085 
9086   // If we didn't actually find any template-ids, we're done.
9087   if (!ovl->hasExplicitTemplateArgs())
9088     return 0;
9089 
9090   TemplateArgumentListInfo ExplicitTemplateArgs;
9091   ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
9092 
9093   // Look through all of the overloaded functions, searching for one
9094   // whose type matches exactly.
9095   FunctionDecl *Matched = 0;
9096   for (UnresolvedSetIterator I = ovl->decls_begin(),
9097          E = ovl->decls_end(); I != E; ++I) {
9098     // C++0x [temp.arg.explicit]p3:
9099     //   [...] In contexts where deduction is done and fails, or in contexts
9100     //   where deduction is not done, if a template argument list is
9101     //   specified and it, along with any default template arguments,
9102     //   identifies a single function template specialization, then the
9103     //   template-id is an lvalue for the function template specialization.
9104     FunctionTemplateDecl *FunctionTemplate
9105       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
9106 
9107     // C++ [over.over]p2:
9108     //   If the name is a function template, template argument deduction is
9109     //   done (14.8.2.2), and if the argument deduction succeeds, the
9110     //   resulting template argument list is used to generate a single
9111     //   function template specialization, which is added to the set of
9112     //   overloaded functions considered.
9113     FunctionDecl *Specialization = 0;
9114     TemplateDeductionInfo Info(Context, ovl->getNameLoc());
9115     if (TemplateDeductionResult Result
9116           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9117                                     Specialization, Info)) {
9118       // FIXME: make a note of the failed deduction for diagnostics.
9119       (void)Result;
9120       continue;
9121     }
9122 
9123     assert(Specialization && "no specialization and no error?");
9124 
9125     // Multiple matches; we can't resolve to a single declaration.
9126     if (Matched) {
9127       if (Complain) {
9128         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9129           << ovl->getName();
9130         NoteAllOverloadCandidates(ovl);
9131       }
9132       return 0;
9133     }
9134 
9135     Matched = Specialization;
9136     if (FoundResult) *FoundResult = I.getPair();
9137   }
9138 
9139   return Matched;
9140 }
9141 
9142 
9143 
9144 
9145 // Resolve and fix an overloaded expression that can be resolved
9146 // because it identifies a single function template specialization.
9147 //
9148 // Last three arguments should only be supplied if Complain = true
9149 //
9150 // Return true if it was logically possible to so resolve the
9151 // expression, regardless of whether or not it succeeded.  Always
9152 // returns true if 'complain' is set.
ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult & SrcExpr,bool doFunctionPointerConverion,bool complain,const SourceRange & OpRangeForComplaining,QualType DestTypeForComplaining,unsigned DiagIDForComplaining)9153 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9154                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
9155                    bool complain, const SourceRange& OpRangeForComplaining,
9156                                            QualType DestTypeForComplaining,
9157                                             unsigned DiagIDForComplaining) {
9158   assert(SrcExpr.get()->getType() == Context.OverloadTy);
9159 
9160   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
9161 
9162   DeclAccessPair found;
9163   ExprResult SingleFunctionExpression;
9164   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9165                            ovl.Expression, /*complain*/ false, &found)) {
9166     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
9167       SrcExpr = ExprError();
9168       return true;
9169     }
9170 
9171     // It is only correct to resolve to an instance method if we're
9172     // resolving a form that's permitted to be a pointer to member.
9173     // Otherwise we'll end up making a bound member expression, which
9174     // is illegal in all the contexts we resolve like this.
9175     if (!ovl.HasFormOfMemberPointer &&
9176         isa<CXXMethodDecl>(fn) &&
9177         cast<CXXMethodDecl>(fn)->isInstance()) {
9178       if (!complain) return false;
9179 
9180       Diag(ovl.Expression->getExprLoc(),
9181            diag::err_bound_member_function)
9182         << 0 << ovl.Expression->getSourceRange();
9183 
9184       // TODO: I believe we only end up here if there's a mix of
9185       // static and non-static candidates (otherwise the expression
9186       // would have 'bound member' type, not 'overload' type).
9187       // Ideally we would note which candidate was chosen and why
9188       // the static candidates were rejected.
9189       SrcExpr = ExprError();
9190       return true;
9191     }
9192 
9193     // Fix the expresion to refer to 'fn'.
9194     SingleFunctionExpression =
9195       Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
9196 
9197     // If desired, do function-to-pointer decay.
9198     if (doFunctionPointerConverion) {
9199       SingleFunctionExpression =
9200         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
9201       if (SingleFunctionExpression.isInvalid()) {
9202         SrcExpr = ExprError();
9203         return true;
9204       }
9205     }
9206   }
9207 
9208   if (!SingleFunctionExpression.isUsable()) {
9209     if (complain) {
9210       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9211         << ovl.Expression->getName()
9212         << DestTypeForComplaining
9213         << OpRangeForComplaining
9214         << ovl.Expression->getQualifierLoc().getSourceRange();
9215       NoteAllOverloadCandidates(SrcExpr.get());
9216 
9217       SrcExpr = ExprError();
9218       return true;
9219     }
9220 
9221     return false;
9222   }
9223 
9224   SrcExpr = SingleFunctionExpression;
9225   return true;
9226 }
9227 
9228 /// \brief Add a single candidate to the overload set.
AddOverloadedCallCandidate(Sema & S,DeclAccessPair FoundDecl,TemplateArgumentListInfo * ExplicitTemplateArgs,llvm::ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading,bool KnownValid)9229 static void AddOverloadedCallCandidate(Sema &S,
9230                                        DeclAccessPair FoundDecl,
9231                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9232                                        llvm::ArrayRef<Expr *> Args,
9233                                        OverloadCandidateSet &CandidateSet,
9234                                        bool PartialOverloading,
9235                                        bool KnownValid) {
9236   NamedDecl *Callee = FoundDecl.getDecl();
9237   if (isa<UsingShadowDecl>(Callee))
9238     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9239 
9240   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
9241     if (ExplicitTemplateArgs) {
9242       assert(!KnownValid && "Explicit template arguments?");
9243       return;
9244     }
9245     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9246                            PartialOverloading);
9247     return;
9248   }
9249 
9250   if (FunctionTemplateDecl *FuncTemplate
9251       = dyn_cast<FunctionTemplateDecl>(Callee)) {
9252     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
9253                                    ExplicitTemplateArgs, Args, CandidateSet);
9254     return;
9255   }
9256 
9257   assert(!KnownValid && "unhandled case in overloaded call candidate");
9258 }
9259 
9260 /// \brief Add the overload candidates named by callee and/or found by argument
9261 /// dependent lookup to the given overload set.
AddOverloadedCallCandidates(UnresolvedLookupExpr * ULE,llvm::ArrayRef<Expr * > Args,OverloadCandidateSet & CandidateSet,bool PartialOverloading)9262 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
9263                                        llvm::ArrayRef<Expr *> Args,
9264                                        OverloadCandidateSet &CandidateSet,
9265                                        bool PartialOverloading) {
9266 
9267 #ifndef NDEBUG
9268   // Verify that ArgumentDependentLookup is consistent with the rules
9269   // in C++0x [basic.lookup.argdep]p3:
9270   //
9271   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
9272   //   and let Y be the lookup set produced by argument dependent
9273   //   lookup (defined as follows). If X contains
9274   //
9275   //     -- a declaration of a class member, or
9276   //
9277   //     -- a block-scope function declaration that is not a
9278   //        using-declaration, or
9279   //
9280   //     -- a declaration that is neither a function or a function
9281   //        template
9282   //
9283   //   then Y is empty.
9284 
9285   if (ULE->requiresADL()) {
9286     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9287            E = ULE->decls_end(); I != E; ++I) {
9288       assert(!(*I)->getDeclContext()->isRecord());
9289       assert(isa<UsingShadowDecl>(*I) ||
9290              !(*I)->getDeclContext()->isFunctionOrMethod());
9291       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
9292     }
9293   }
9294 #endif
9295 
9296   // It would be nice to avoid this copy.
9297   TemplateArgumentListInfo TABuffer;
9298   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9299   if (ULE->hasExplicitTemplateArgs()) {
9300     ULE->copyTemplateArgumentsInto(TABuffer);
9301     ExplicitTemplateArgs = &TABuffer;
9302   }
9303 
9304   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9305          E = ULE->decls_end(); I != E; ++I)
9306     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9307                                CandidateSet, PartialOverloading,
9308                                /*KnownValid*/ true);
9309 
9310   if (ULE->requiresADL())
9311     AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
9312                                          ULE->getExprLoc(),
9313                                          Args, ExplicitTemplateArgs,
9314                                          CandidateSet, PartialOverloading,
9315                                          ULE->isStdAssociatedNamespace());
9316 }
9317 
9318 /// Attempt to recover from an ill-formed use of a non-dependent name in a
9319 /// template, where the non-dependent name was declared after the template
9320 /// was defined. This is common in code written for a compilers which do not
9321 /// correctly implement two-stage name lookup.
9322 ///
9323 /// Returns true if a viable candidate was found and a diagnostic was issued.
9324 static bool
DiagnoseTwoPhaseLookup(Sema & SemaRef,SourceLocation FnLoc,const CXXScopeSpec & SS,LookupResult & R,TemplateArgumentListInfo * ExplicitTemplateArgs,llvm::ArrayRef<Expr * > Args)9325 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9326                        const CXXScopeSpec &SS, LookupResult &R,
9327                        TemplateArgumentListInfo *ExplicitTemplateArgs,
9328                        llvm::ArrayRef<Expr *> Args) {
9329   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9330     return false;
9331 
9332   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
9333     if (DC->isTransparentContext())
9334       continue;
9335 
9336     SemaRef.LookupQualifiedName(R, DC);
9337 
9338     if (!R.empty()) {
9339       R.suppressDiagnostics();
9340 
9341       if (isa<CXXRecordDecl>(DC)) {
9342         // Don't diagnose names we find in classes; we get much better
9343         // diagnostics for these from DiagnoseEmptyLookup.
9344         R.clear();
9345         return false;
9346       }
9347 
9348       OverloadCandidateSet Candidates(FnLoc);
9349       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9350         AddOverloadedCallCandidate(SemaRef, I.getPair(),
9351                                    ExplicitTemplateArgs, Args,
9352                                    Candidates, false, /*KnownValid*/ false);
9353 
9354       OverloadCandidateSet::iterator Best;
9355       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
9356         // No viable functions. Don't bother the user with notes for functions
9357         // which don't work and shouldn't be found anyway.
9358         R.clear();
9359         return false;
9360       }
9361 
9362       // Find the namespaces where ADL would have looked, and suggest
9363       // declaring the function there instead.
9364       Sema::AssociatedNamespaceSet AssociatedNamespaces;
9365       Sema::AssociatedClassSet AssociatedClasses;
9366       SemaRef.FindAssociatedClassesAndNamespaces(Args,
9367                                                  AssociatedNamespaces,
9368                                                  AssociatedClasses);
9369       // Never suggest declaring a function within namespace 'std'.
9370       Sema::AssociatedNamespaceSet SuggestedNamespaces;
9371       if (DeclContext *Std = SemaRef.getStdNamespace()) {
9372         for (Sema::AssociatedNamespaceSet::iterator
9373                it = AssociatedNamespaces.begin(),
9374                end = AssociatedNamespaces.end(); it != end; ++it) {
9375           if (!Std->Encloses(*it))
9376             SuggestedNamespaces.insert(*it);
9377         }
9378       } else {
9379         // Lacking the 'std::' namespace, use all of the associated namespaces.
9380         SuggestedNamespaces = AssociatedNamespaces;
9381       }
9382 
9383       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9384         << R.getLookupName();
9385       if (SuggestedNamespaces.empty()) {
9386         SemaRef.Diag(Best->Function->getLocation(),
9387                      diag::note_not_found_by_two_phase_lookup)
9388           << R.getLookupName() << 0;
9389       } else if (SuggestedNamespaces.size() == 1) {
9390         SemaRef.Diag(Best->Function->getLocation(),
9391                      diag::note_not_found_by_two_phase_lookup)
9392           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
9393       } else {
9394         // FIXME: It would be useful to list the associated namespaces here,
9395         // but the diagnostics infrastructure doesn't provide a way to produce
9396         // a localized representation of a list of items.
9397         SemaRef.Diag(Best->Function->getLocation(),
9398                      diag::note_not_found_by_two_phase_lookup)
9399           << R.getLookupName() << 2;
9400       }
9401 
9402       // Try to recover by calling this function.
9403       return true;
9404     }
9405 
9406     R.clear();
9407   }
9408 
9409   return false;
9410 }
9411 
9412 /// Attempt to recover from ill-formed use of a non-dependent operator in a
9413 /// template, where the non-dependent operator was declared after the template
9414 /// was defined.
9415 ///
9416 /// Returns true if a viable candidate was found and a diagnostic was issued.
9417 static bool
DiagnoseTwoPhaseOperatorLookup(Sema & SemaRef,OverloadedOperatorKind Op,SourceLocation OpLoc,llvm::ArrayRef<Expr * > Args)9418 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9419                                SourceLocation OpLoc,
9420                                llvm::ArrayRef<Expr *> Args) {
9421   DeclarationName OpName =
9422     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9423   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9424   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
9425                                 /*ExplicitTemplateArgs=*/0, Args);
9426 }
9427 
9428 namespace {
9429 // Callback to limit the allowed keywords and to only accept typo corrections
9430 // that are keywords or whose decls refer to functions (or template functions)
9431 // that accept the given number of arguments.
9432 class RecoveryCallCCC : public CorrectionCandidateCallback {
9433  public:
RecoveryCallCCC(Sema & SemaRef,unsigned NumArgs,bool HasExplicitTemplateArgs)9434   RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9435       : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
9436     WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
9437     WantRemainingKeywords = false;
9438   }
9439 
ValidateCandidate(const TypoCorrection & candidate)9440   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9441     if (!candidate.getCorrectionDecl())
9442       return candidate.isKeyword();
9443 
9444     for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9445            DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9446       FunctionDecl *FD = 0;
9447       NamedDecl *ND = (*DI)->getUnderlyingDecl();
9448       if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9449         FD = FTD->getTemplatedDecl();
9450       if (!HasExplicitTemplateArgs && !FD) {
9451         if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9452           // If the Decl is neither a function nor a template function,
9453           // determine if it is a pointer or reference to a function. If so,
9454           // check against the number of arguments expected for the pointee.
9455           QualType ValType = cast<ValueDecl>(ND)->getType();
9456           if (ValType->isAnyPointerType() || ValType->isReferenceType())
9457             ValType = ValType->getPointeeType();
9458           if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9459             if (FPT->getNumArgs() == NumArgs)
9460               return true;
9461         }
9462       }
9463       if (FD && FD->getNumParams() >= NumArgs &&
9464           FD->getMinRequiredArguments() <= NumArgs)
9465         return true;
9466     }
9467     return false;
9468   }
9469 
9470  private:
9471   unsigned NumArgs;
9472   bool HasExplicitTemplateArgs;
9473 };
9474 
9475 // Callback that effectively disabled typo correction
9476 class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9477  public:
NoTypoCorrectionCCC()9478   NoTypoCorrectionCCC() {
9479     WantTypeSpecifiers = false;
9480     WantExpressionKeywords = false;
9481     WantCXXNamedCasts = false;
9482     WantRemainingKeywords = false;
9483   }
9484 
ValidateCandidate(const TypoCorrection & candidate)9485   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9486     return false;
9487   }
9488 };
9489 }
9490 
9491 /// Attempts to recover from a call where no functions were found.
9492 ///
9493 /// Returns true if new candidates were found.
9494 static ExprResult
BuildRecoveryCallExpr(Sema & SemaRef,Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,llvm::MutableArrayRef<Expr * > Args,SourceLocation RParenLoc,bool EmptyLookup,bool AllowTypoCorrection)9495 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9496                       UnresolvedLookupExpr *ULE,
9497                       SourceLocation LParenLoc,
9498                       llvm::MutableArrayRef<Expr *> Args,
9499                       SourceLocation RParenLoc,
9500                       bool EmptyLookup, bool AllowTypoCorrection) {
9501 
9502   CXXScopeSpec SS;
9503   SS.Adopt(ULE->getQualifierLoc());
9504   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
9505 
9506   TemplateArgumentListInfo TABuffer;
9507   TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
9508   if (ULE->hasExplicitTemplateArgs()) {
9509     ULE->copyTemplateArgumentsInto(TABuffer);
9510     ExplicitTemplateArgs = &TABuffer;
9511   }
9512 
9513   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9514                  Sema::LookupOrdinaryName);
9515   RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
9516   NoTypoCorrectionCCC RejectAll;
9517   CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9518       (CorrectionCandidateCallback*)&Validator :
9519       (CorrectionCandidateCallback*)&RejectAll;
9520   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
9521                               ExplicitTemplateArgs, Args) &&
9522       (!EmptyLookup ||
9523        SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
9524                                    ExplicitTemplateArgs, Args)))
9525     return ExprError();
9526 
9527   assert(!R.empty() && "lookup results empty despite recovery");
9528 
9529   // Build an implicit member call if appropriate.  Just drop the
9530   // casts and such from the call, we don't really care.
9531   ExprResult NewFn = ExprError();
9532   if ((*R.begin())->isCXXClassMember())
9533     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9534                                                     R, ExplicitTemplateArgs);
9535   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
9536     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
9537                                         ExplicitTemplateArgs);
9538   else
9539     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9540 
9541   if (NewFn.isInvalid())
9542     return ExprError();
9543 
9544   // This shouldn't cause an infinite loop because we're giving it
9545   // an expression with viable lookup results, which should never
9546   // end up here.
9547   return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
9548                                MultiExprArg(Args.data(), Args.size()),
9549                                RParenLoc);
9550 }
9551 
9552 /// ResolveOverloadedCallFn - Given the call expression that calls Fn
9553 /// (which eventually refers to the declaration Func) and the call
9554 /// arguments Args/NumArgs, attempt to resolve the function call down
9555 /// to a specific function. If overload resolution succeeds, returns
9556 /// the function declaration produced by overload
9557 /// resolution. Otherwise, emits diagnostics, deletes all of the
9558 /// arguments and Fn, and returns NULL.
9559 ExprResult
BuildOverloadedCallExpr(Scope * S,Expr * Fn,UnresolvedLookupExpr * ULE,SourceLocation LParenLoc,Expr ** Args,unsigned NumArgs,SourceLocation RParenLoc,Expr * ExecConfig,bool AllowTypoCorrection)9560 Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
9561                               SourceLocation LParenLoc,
9562                               Expr **Args, unsigned NumArgs,
9563                               SourceLocation RParenLoc,
9564                               Expr *ExecConfig,
9565                               bool AllowTypoCorrection) {
9566 #ifndef NDEBUG
9567   if (ULE->requiresADL()) {
9568     // To do ADL, we must have found an unqualified name.
9569     assert(!ULE->getQualifier() && "qualified name with ADL");
9570 
9571     // We don't perform ADL for implicit declarations of builtins.
9572     // Verify that this was correctly set up.
9573     FunctionDecl *F;
9574     if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9575         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9576         F->getBuiltinID() && F->isImplicit())
9577       llvm_unreachable("performing ADL for builtin");
9578 
9579     // We don't perform ADL in C.
9580     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
9581   } else
9582     assert(!ULE->isStdAssociatedNamespace() &&
9583            "std is associated namespace but not doing ADL");
9584 #endif
9585 
9586   UnbridgedCastsSet UnbridgedCasts;
9587   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9588     return ExprError();
9589 
9590   OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9591 
9592   // Add the functions denoted by the callee to the set of candidate
9593   // functions, including those from argument-dependent lookup.
9594   AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9595                               CandidateSet);
9596 
9597   // If we found nothing, try to recover.
9598   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9599   // out if it fails.
9600   if (CandidateSet.empty()) {
9601     // In Microsoft mode, if we are inside a template class member function then
9602     // create a type dependent CallExpr. The goal is to postpone name lookup
9603     // to instantiation time to be able to search into type dependent base
9604     // classes.
9605     if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
9606         (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
9607       CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9608                                           Context.DependentTy, VK_RValue,
9609                                           RParenLoc);
9610       CE->setTypeDependent(true);
9611       return Owned(CE);
9612     }
9613     return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9614                                  llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9615                                  RParenLoc, /*EmptyLookup=*/true,
9616                                  AllowTypoCorrection);
9617   }
9618 
9619   UnbridgedCasts.restore();
9620 
9621   OverloadCandidateSet::iterator Best;
9622   switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
9623   case OR_Success: {
9624     FunctionDecl *FDecl = Best->Function;
9625     MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9626     CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
9627     DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9628     Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9629     return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9630                                  ExecConfig);
9631   }
9632 
9633   case OR_No_Viable_Function: {
9634     // Try to recover by looking for viable functions which the user might
9635     // have meant to call.
9636     ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9637                                   llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9638                                                 RParenLoc,
9639                                                 /*EmptyLookup=*/false,
9640                                                 AllowTypoCorrection);
9641     if (!Recovery.isInvalid())
9642       return Recovery;
9643 
9644     Diag(Fn->getLocStart(),
9645          diag::err_ovl_no_viable_function_in_call)
9646       << ULE->getName() << Fn->getSourceRange();
9647     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9648                                 llvm::makeArrayRef(Args, NumArgs));
9649     break;
9650   }
9651 
9652   case OR_Ambiguous:
9653     Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
9654       << ULE->getName() << Fn->getSourceRange();
9655     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9656                                 llvm::makeArrayRef(Args, NumArgs));
9657     break;
9658 
9659   case OR_Deleted:
9660     {
9661       Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9662         << Best->Function->isDeleted()
9663         << ULE->getName()
9664         << getDeletedOrUnavailableSuffix(Best->Function)
9665         << Fn->getSourceRange();
9666       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9667                                   llvm::makeArrayRef(Args, NumArgs));
9668 
9669       // We emitted an error for the unvailable/deleted function call but keep
9670       // the call in the AST.
9671       FunctionDecl *FDecl = Best->Function;
9672       Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9673       return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9674                                    RParenLoc, ExecConfig);
9675     }
9676   }
9677 
9678   // Overload resolution failed.
9679   return ExprError();
9680 }
9681 
IsOverloaded(const UnresolvedSetImpl & Functions)9682 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
9683   return Functions.size() > 1 ||
9684     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9685 }
9686 
9687 /// \brief Create a unary operation that may resolve to an overloaded
9688 /// operator.
9689 ///
9690 /// \param OpLoc The location of the operator itself (e.g., '*').
9691 ///
9692 /// \param OpcIn The UnaryOperator::Opcode that describes this
9693 /// operator.
9694 ///
9695 /// \param Functions The set of non-member functions that will be
9696 /// considered by overload resolution. The caller needs to build this
9697 /// set based on the context using, e.g.,
9698 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9699 /// set should not contain any member functions; those will be added
9700 /// by CreateOverloadedUnaryOp().
9701 ///
9702 /// \param input The input argument.
9703 ExprResult
CreateOverloadedUnaryOp(SourceLocation OpLoc,unsigned OpcIn,const UnresolvedSetImpl & Fns,Expr * Input)9704 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9705                               const UnresolvedSetImpl &Fns,
9706                               Expr *Input) {
9707   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
9708 
9709   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9710   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9711   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9712   // TODO: provide better source location info.
9713   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
9714 
9715   if (checkPlaceholderForOverload(*this, Input))
9716     return ExprError();
9717 
9718   Expr *Args[2] = { Input, 0 };
9719   unsigned NumArgs = 1;
9720 
9721   // For post-increment and post-decrement, add the implicit '0' as
9722   // the second argument, so that we know this is a post-increment or
9723   // post-decrement.
9724   if (Opc == UO_PostInc || Opc == UO_PostDec) {
9725     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
9726     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9727                                      SourceLocation());
9728     NumArgs = 2;
9729   }
9730 
9731   if (Input->isTypeDependent()) {
9732     if (Fns.empty())
9733       return Owned(new (Context) UnaryOperator(Input,
9734                                                Opc,
9735                                                Context.DependentTy,
9736                                                VK_RValue, OK_Ordinary,
9737                                                OpLoc));
9738 
9739     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9740     UnresolvedLookupExpr *Fn
9741       = UnresolvedLookupExpr::Create(Context, NamingClass,
9742                                      NestedNameSpecifierLoc(), OpNameInfo,
9743                                      /*ADL*/ true, IsOverloaded(Fns),
9744                                      Fns.begin(), Fns.end());
9745     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
9746                                                   &Args[0], NumArgs,
9747                                                    Context.DependentTy,
9748                                                    VK_RValue,
9749                                                    OpLoc));
9750   }
9751 
9752   // Build an empty overload set.
9753   OverloadCandidateSet CandidateSet(OpLoc);
9754 
9755   // Add the candidates from the given function set.
9756   AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9757                         false);
9758 
9759   // Add operator candidates that are member functions.
9760   AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9761 
9762   // Add candidates from ADL.
9763   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9764                                        OpLoc, llvm::makeArrayRef(Args, NumArgs),
9765                                        /*ExplicitTemplateArgs*/ 0,
9766                                        CandidateSet);
9767 
9768   // Add builtin operator candidates.
9769   AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9770 
9771   bool HadMultipleCandidates = (CandidateSet.size() > 1);
9772 
9773   // Perform overload resolution.
9774   OverloadCandidateSet::iterator Best;
9775   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
9776   case OR_Success: {
9777     // We found a built-in operator or an overloaded operator.
9778     FunctionDecl *FnDecl = Best->Function;
9779 
9780     if (FnDecl) {
9781       // We matched an overloaded operator. Build a call to that
9782       // operator.
9783 
9784       MarkFunctionReferenced(OpLoc, FnDecl);
9785 
9786       // Convert the arguments.
9787       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
9788         CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
9789 
9790         ExprResult InputRes =
9791           PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9792                                               Best->FoundDecl, Method);
9793         if (InputRes.isInvalid())
9794           return ExprError();
9795         Input = InputRes.take();
9796       } else {
9797         // Convert the arguments.
9798         ExprResult InputInit
9799           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
9800                                                       Context,
9801                                                       FnDecl->getParamDecl(0)),
9802                                       SourceLocation(),
9803                                       Input);
9804         if (InputInit.isInvalid())
9805           return ExprError();
9806         Input = InputInit.take();
9807       }
9808 
9809       DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9810 
9811       // Determine the result type.
9812       QualType ResultTy = FnDecl->getResultType();
9813       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9814       ResultTy = ResultTy.getNonLValueExprType(Context);
9815 
9816       // Build the actual expression node.
9817       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9818                                                 HadMultipleCandidates, OpLoc);
9819       if (FnExpr.isInvalid())
9820         return ExprError();
9821 
9822       Args[0] = Input;
9823       CallExpr *TheCall =
9824         new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
9825                                           Args, NumArgs, ResultTy, VK, OpLoc);
9826 
9827       if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
9828                               FnDecl))
9829         return ExprError();
9830 
9831       return MaybeBindToTemporary(TheCall);
9832     } else {
9833       // We matched a built-in operator. Convert the arguments, then
9834       // break out so that we will build the appropriate built-in
9835       // operator node.
9836       ExprResult InputRes =
9837         PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9838                                   Best->Conversions[0], AA_Passing);
9839       if (InputRes.isInvalid())
9840         return ExprError();
9841       Input = InputRes.take();
9842       break;
9843     }
9844   }
9845 
9846   case OR_No_Viable_Function:
9847     // This is an erroneous use of an operator which can be overloaded by
9848     // a non-member function. Check for non-member operators which were
9849     // defined too late to be candidates.
9850     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9851                                        llvm::makeArrayRef(Args, NumArgs)))
9852       // FIXME: Recover by calling the found function.
9853       return ExprError();
9854 
9855     // No viable function; fall through to handling this as a
9856     // built-in operator, which will produce an error message for us.
9857     break;
9858 
9859   case OR_Ambiguous:
9860     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
9861         << UnaryOperator::getOpcodeStr(Opc)
9862         << Input->getType()
9863         << Input->getSourceRange();
9864     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9865                                 llvm::makeArrayRef(Args, NumArgs),
9866                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9867     return ExprError();
9868 
9869   case OR_Deleted:
9870     Diag(OpLoc, diag::err_ovl_deleted_oper)
9871       << Best->Function->isDeleted()
9872       << UnaryOperator::getOpcodeStr(Opc)
9873       << getDeletedOrUnavailableSuffix(Best->Function)
9874       << Input->getSourceRange();
9875     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9876                                 llvm::makeArrayRef(Args, NumArgs),
9877                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9878     return ExprError();
9879   }
9880 
9881   // Either we found no viable overloaded operator or we matched a
9882   // built-in operator. In either case, fall through to trying to
9883   // build a built-in operation.
9884   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9885 }
9886 
9887 /// \brief Create a binary operation that may resolve to an overloaded
9888 /// operator.
9889 ///
9890 /// \param OpLoc The location of the operator itself (e.g., '+').
9891 ///
9892 /// \param OpcIn The BinaryOperator::Opcode that describes this
9893 /// operator.
9894 ///
9895 /// \param Functions The set of non-member functions that will be
9896 /// considered by overload resolution. The caller needs to build this
9897 /// set based on the context using, e.g.,
9898 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9899 /// set should not contain any member functions; those will be added
9900 /// by CreateOverloadedBinOp().
9901 ///
9902 /// \param LHS Left-hand argument.
9903 /// \param RHS Right-hand argument.
9904 ExprResult
CreateOverloadedBinOp(SourceLocation OpLoc,unsigned OpcIn,const UnresolvedSetImpl & Fns,Expr * LHS,Expr * RHS)9905 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
9906                             unsigned OpcIn,
9907                             const UnresolvedSetImpl &Fns,
9908                             Expr *LHS, Expr *RHS) {
9909   Expr *Args[2] = { LHS, RHS };
9910   LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
9911 
9912   BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9913   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9914   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9915 
9916   // If either side is type-dependent, create an appropriate dependent
9917   // expression.
9918   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9919     if (Fns.empty()) {
9920       // If there are no functions to store, just build a dependent
9921       // BinaryOperator or CompoundAssignment.
9922       if (Opc <= BO_Assign || Opc > BO_OrAssign)
9923         return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
9924                                                   Context.DependentTy,
9925                                                   VK_RValue, OK_Ordinary,
9926                                                   OpLoc));
9927 
9928       return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9929                                                         Context.DependentTy,
9930                                                         VK_LValue,
9931                                                         OK_Ordinary,
9932                                                         Context.DependentTy,
9933                                                         Context.DependentTy,
9934                                                         OpLoc));
9935     }
9936 
9937     // FIXME: save results of ADL from here?
9938     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
9939     // TODO: provide better source location info in DNLoc component.
9940     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
9941     UnresolvedLookupExpr *Fn
9942       = UnresolvedLookupExpr::Create(Context, NamingClass,
9943                                      NestedNameSpecifierLoc(), OpNameInfo,
9944                                      /*ADL*/ true, IsOverloaded(Fns),
9945                                      Fns.begin(), Fns.end());
9946     return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
9947                                                    Args, 2,
9948                                                    Context.DependentTy,
9949                                                    VK_RValue,
9950                                                    OpLoc));
9951   }
9952 
9953   // Always do placeholder-like conversions on the RHS.
9954   if (checkPlaceholderForOverload(*this, Args[1]))
9955     return ExprError();
9956 
9957   // Do placeholder-like conversion on the LHS; note that we should
9958   // not get here with a PseudoObject LHS.
9959   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
9960   if (checkPlaceholderForOverload(*this, Args[0]))
9961     return ExprError();
9962 
9963   // If this is the assignment operator, we only perform overload resolution
9964   // if the left-hand side is a class or enumeration type. This is actually
9965   // a hack. The standard requires that we do overload resolution between the
9966   // various built-in candidates, but as DR507 points out, this can lead to
9967   // problems. So we do it this way, which pretty much follows what GCC does.
9968   // Note that we go the traditional code path for compound assignment forms.
9969   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
9970     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9971 
9972   // If this is the .* operator, which is not overloadable, just
9973   // create a built-in binary operator.
9974   if (Opc == BO_PtrMemD)
9975     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9976 
9977   // Build an empty overload set.
9978   OverloadCandidateSet CandidateSet(OpLoc);
9979 
9980   // Add the candidates from the given function set.
9981   AddFunctionCandidates(Fns, Args, CandidateSet, false);
9982 
9983   // Add operator candidates that are member functions.
9984   AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9985 
9986   // Add candidates from ADL.
9987   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9988                                        OpLoc, Args,
9989                                        /*ExplicitTemplateArgs*/ 0,
9990                                        CandidateSet);
9991 
9992   // Add builtin operator candidates.
9993   AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9994 
9995   bool HadMultipleCandidates = (CandidateSet.size() > 1);
9996 
9997   // Perform overload resolution.
9998   OverloadCandidateSet::iterator Best;
9999   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10000     case OR_Success: {
10001       // We found a built-in operator or an overloaded operator.
10002       FunctionDecl *FnDecl = Best->Function;
10003 
10004       if (FnDecl) {
10005         // We matched an overloaded operator. Build a call to that
10006         // operator.
10007 
10008         MarkFunctionReferenced(OpLoc, FnDecl);
10009 
10010         // Convert the arguments.
10011         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10012           // Best->Access is only meaningful for class members.
10013           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10014 
10015           ExprResult Arg1 =
10016             PerformCopyInitialization(
10017               InitializedEntity::InitializeParameter(Context,
10018                                                      FnDecl->getParamDecl(0)),
10019               SourceLocation(), Owned(Args[1]));
10020           if (Arg1.isInvalid())
10021             return ExprError();
10022 
10023           ExprResult Arg0 =
10024             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10025                                                 Best->FoundDecl, Method);
10026           if (Arg0.isInvalid())
10027             return ExprError();
10028           Args[0] = Arg0.takeAs<Expr>();
10029           Args[1] = RHS = Arg1.takeAs<Expr>();
10030         } else {
10031           // Convert the arguments.
10032           ExprResult Arg0 = PerformCopyInitialization(
10033             InitializedEntity::InitializeParameter(Context,
10034                                                    FnDecl->getParamDecl(0)),
10035             SourceLocation(), Owned(Args[0]));
10036           if (Arg0.isInvalid())
10037             return ExprError();
10038 
10039           ExprResult Arg1 =
10040             PerformCopyInitialization(
10041               InitializedEntity::InitializeParameter(Context,
10042                                                      FnDecl->getParamDecl(1)),
10043               SourceLocation(), Owned(Args[1]));
10044           if (Arg1.isInvalid())
10045             return ExprError();
10046           Args[0] = LHS = Arg0.takeAs<Expr>();
10047           Args[1] = RHS = Arg1.takeAs<Expr>();
10048         }
10049 
10050         DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10051 
10052         // Determine the result type.
10053         QualType ResultTy = FnDecl->getResultType();
10054         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10055         ResultTy = ResultTy.getNonLValueExprType(Context);
10056 
10057         // Build the actual expression node.
10058         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10059                                                   HadMultipleCandidates, OpLoc);
10060         if (FnExpr.isInvalid())
10061           return ExprError();
10062 
10063         CXXOperatorCallExpr *TheCall =
10064           new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
10065                                             Args, 2, ResultTy, VK, OpLoc);
10066 
10067         if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
10068                                 FnDecl))
10069           return ExprError();
10070 
10071         return MaybeBindToTemporary(TheCall);
10072       } else {
10073         // We matched a built-in operator. Convert the arguments, then
10074         // break out so that we will build the appropriate built-in
10075         // operator node.
10076         ExprResult ArgsRes0 =
10077           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10078                                     Best->Conversions[0], AA_Passing);
10079         if (ArgsRes0.isInvalid())
10080           return ExprError();
10081         Args[0] = ArgsRes0.take();
10082 
10083         ExprResult ArgsRes1 =
10084           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10085                                     Best->Conversions[1], AA_Passing);
10086         if (ArgsRes1.isInvalid())
10087           return ExprError();
10088         Args[1] = ArgsRes1.take();
10089         break;
10090       }
10091     }
10092 
10093     case OR_No_Viable_Function: {
10094       // C++ [over.match.oper]p9:
10095       //   If the operator is the operator , [...] and there are no
10096       //   viable functions, then the operator is assumed to be the
10097       //   built-in operator and interpreted according to clause 5.
10098       if (Opc == BO_Comma)
10099         break;
10100 
10101       // For class as left operand for assignment or compound assigment
10102       // operator do not fall through to handling in built-in, but report that
10103       // no overloaded assignment operator found
10104       ExprResult Result = ExprError();
10105       if (Args[0]->getType()->isRecordType() &&
10106           Opc >= BO_Assign && Opc <= BO_OrAssign) {
10107         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
10108              << BinaryOperator::getOpcodeStr(Opc)
10109              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10110       } else {
10111         // This is an erroneous use of an operator which can be overloaded by
10112         // a non-member function. Check for non-member operators which were
10113         // defined too late to be candidates.
10114         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
10115           // FIXME: Recover by calling the found function.
10116           return ExprError();
10117 
10118         // No viable function; try to create a built-in operation, which will
10119         // produce an error. Then, show the non-viable candidates.
10120         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10121       }
10122       assert(Result.isInvalid() &&
10123              "C++ binary operator overloading is missing candidates!");
10124       if (Result.isInvalid())
10125         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10126                                     BinaryOperator::getOpcodeStr(Opc), OpLoc);
10127       return move(Result);
10128     }
10129 
10130     case OR_Ambiguous:
10131       Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
10132           << BinaryOperator::getOpcodeStr(Opc)
10133           << Args[0]->getType() << Args[1]->getType()
10134           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10135       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10136                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10137       return ExprError();
10138 
10139     case OR_Deleted:
10140       if (isImplicitlyDeleted(Best->Function)) {
10141         CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10142         Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10143           << getSpecialMember(Method)
10144           << BinaryOperator::getOpcodeStr(Opc)
10145           << getDeletedOrUnavailableSuffix(Best->Function);
10146 
10147         if (getSpecialMember(Method) != CXXInvalid) {
10148           // The user probably meant to call this special member. Just
10149           // explain why it's deleted.
10150           NoteDeletedFunction(Method);
10151           return ExprError();
10152         }
10153       } else {
10154         Diag(OpLoc, diag::err_ovl_deleted_oper)
10155           << Best->Function->isDeleted()
10156           << BinaryOperator::getOpcodeStr(Opc)
10157           << getDeletedOrUnavailableSuffix(Best->Function)
10158           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10159       }
10160       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10161                                   BinaryOperator::getOpcodeStr(Opc), OpLoc);
10162       return ExprError();
10163   }
10164 
10165   // We matched a built-in operator; build it.
10166   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10167 }
10168 
10169 ExprResult
CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,SourceLocation RLoc,Expr * Base,Expr * Idx)10170 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10171                                          SourceLocation RLoc,
10172                                          Expr *Base, Expr *Idx) {
10173   Expr *Args[2] = { Base, Idx };
10174   DeclarationName OpName =
10175       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10176 
10177   // If either side is type-dependent, create an appropriate dependent
10178   // expression.
10179   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10180 
10181     CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
10182     // CHECKME: no 'operator' keyword?
10183     DeclarationNameInfo OpNameInfo(OpName, LLoc);
10184     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10185     UnresolvedLookupExpr *Fn
10186       = UnresolvedLookupExpr::Create(Context, NamingClass,
10187                                      NestedNameSpecifierLoc(), OpNameInfo,
10188                                      /*ADL*/ true, /*Overloaded*/ false,
10189                                      UnresolvedSetIterator(),
10190                                      UnresolvedSetIterator());
10191     // Can't add any actual overloads yet
10192 
10193     return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10194                                                    Args, 2,
10195                                                    Context.DependentTy,
10196                                                    VK_RValue,
10197                                                    RLoc));
10198   }
10199 
10200   // Handle placeholders on both operands.
10201   if (checkPlaceholderForOverload(*this, Args[0]))
10202     return ExprError();
10203   if (checkPlaceholderForOverload(*this, Args[1]))
10204     return ExprError();
10205 
10206   // Build an empty overload set.
10207   OverloadCandidateSet CandidateSet(LLoc);
10208 
10209   // Subscript can only be overloaded as a member function.
10210 
10211   // Add operator candidates that are member functions.
10212   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10213 
10214   // Add builtin operator candidates.
10215   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10216 
10217   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10218 
10219   // Perform overload resolution.
10220   OverloadCandidateSet::iterator Best;
10221   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
10222     case OR_Success: {
10223       // We found a built-in operator or an overloaded operator.
10224       FunctionDecl *FnDecl = Best->Function;
10225 
10226       if (FnDecl) {
10227         // We matched an overloaded operator. Build a call to that
10228         // operator.
10229 
10230         MarkFunctionReferenced(LLoc, FnDecl);
10231 
10232         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
10233         DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
10234 
10235         // Convert the arguments.
10236         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
10237         ExprResult Arg0 =
10238           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10239                                               Best->FoundDecl, Method);
10240         if (Arg0.isInvalid())
10241           return ExprError();
10242         Args[0] = Arg0.take();
10243 
10244         // Convert the arguments.
10245         ExprResult InputInit
10246           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10247                                                       Context,
10248                                                       FnDecl->getParamDecl(0)),
10249                                       SourceLocation(),
10250                                       Owned(Args[1]));
10251         if (InputInit.isInvalid())
10252           return ExprError();
10253 
10254         Args[1] = InputInit.takeAs<Expr>();
10255 
10256         // Determine the result type
10257         QualType ResultTy = FnDecl->getResultType();
10258         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10259         ResultTy = ResultTy.getNonLValueExprType(Context);
10260 
10261         // Build the actual expression node.
10262         DeclarationNameInfo OpLocInfo(OpName, LLoc);
10263         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
10264         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10265                                                   HadMultipleCandidates,
10266                                                   OpLocInfo.getLoc(),
10267                                                   OpLocInfo.getInfo());
10268         if (FnExpr.isInvalid())
10269           return ExprError();
10270 
10271         CXXOperatorCallExpr *TheCall =
10272           new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
10273                                             FnExpr.take(), Args, 2,
10274                                             ResultTy, VK, RLoc);
10275 
10276         if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
10277                                 FnDecl))
10278           return ExprError();
10279 
10280         return MaybeBindToTemporary(TheCall);
10281       } else {
10282         // We matched a built-in operator. Convert the arguments, then
10283         // break out so that we will build the appropriate built-in
10284         // operator node.
10285         ExprResult ArgsRes0 =
10286           PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10287                                     Best->Conversions[0], AA_Passing);
10288         if (ArgsRes0.isInvalid())
10289           return ExprError();
10290         Args[0] = ArgsRes0.take();
10291 
10292         ExprResult ArgsRes1 =
10293           PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10294                                     Best->Conversions[1], AA_Passing);
10295         if (ArgsRes1.isInvalid())
10296           return ExprError();
10297         Args[1] = ArgsRes1.take();
10298 
10299         break;
10300       }
10301     }
10302 
10303     case OR_No_Viable_Function: {
10304       if (CandidateSet.empty())
10305         Diag(LLoc, diag::err_ovl_no_oper)
10306           << Args[0]->getType() << /*subscript*/ 0
10307           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10308       else
10309         Diag(LLoc, diag::err_ovl_no_viable_subscript)
10310           << Args[0]->getType()
10311           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10312       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10313                                   "[]", LLoc);
10314       return ExprError();
10315     }
10316 
10317     case OR_Ambiguous:
10318       Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
10319           << "[]"
10320           << Args[0]->getType() << Args[1]->getType()
10321           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10322       CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
10323                                   "[]", LLoc);
10324       return ExprError();
10325 
10326     case OR_Deleted:
10327       Diag(LLoc, diag::err_ovl_deleted_oper)
10328         << Best->Function->isDeleted() << "[]"
10329         << getDeletedOrUnavailableSuffix(Best->Function)
10330         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10331       CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
10332                                   "[]", LLoc);
10333       return ExprError();
10334     }
10335 
10336   // We matched a built-in operator; build it.
10337   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
10338 }
10339 
10340 /// BuildCallToMemberFunction - Build a call to a member
10341 /// function. MemExpr is the expression that refers to the member
10342 /// function (and includes the object parameter), Args/NumArgs are the
10343 /// arguments to the function call (not including the object
10344 /// parameter). The caller needs to validate that the member
10345 /// expression refers to a non-static member function or an overloaded
10346 /// member function.
10347 ExprResult
BuildCallToMemberFunction(Scope * S,Expr * MemExprE,SourceLocation LParenLoc,Expr ** Args,unsigned NumArgs,SourceLocation RParenLoc)10348 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10349                                 SourceLocation LParenLoc, Expr **Args,
10350                                 unsigned NumArgs, SourceLocation RParenLoc) {
10351   assert(MemExprE->getType() == Context.BoundMemberTy ||
10352          MemExprE->getType() == Context.OverloadTy);
10353 
10354   // Dig out the member expression. This holds both the object
10355   // argument and the member function we're referring to.
10356   Expr *NakedMemExpr = MemExprE->IgnoreParens();
10357 
10358   // Determine whether this is a call to a pointer-to-member function.
10359   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10360     assert(op->getType() == Context.BoundMemberTy);
10361     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10362 
10363     QualType fnType =
10364       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10365 
10366     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10367     QualType resultType = proto->getCallResultType(Context);
10368     ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10369 
10370     // Check that the object type isn't more qualified than the
10371     // member function we're calling.
10372     Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10373 
10374     QualType objectType = op->getLHS()->getType();
10375     if (op->getOpcode() == BO_PtrMemI)
10376       objectType = objectType->castAs<PointerType>()->getPointeeType();
10377     Qualifiers objectQuals = objectType.getQualifiers();
10378 
10379     Qualifiers difference = objectQuals - funcQuals;
10380     difference.removeObjCGCAttr();
10381     difference.removeAddressSpace();
10382     if (difference) {
10383       std::string qualsString = difference.getAsString();
10384       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10385         << fnType.getUnqualifiedType()
10386         << qualsString
10387         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10388     }
10389 
10390     CXXMemberCallExpr *call
10391       = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10392                                         resultType, valueKind, RParenLoc);
10393 
10394     if (CheckCallReturnType(proto->getResultType(),
10395                             op->getRHS()->getLocStart(),
10396                             call, 0))
10397       return ExprError();
10398 
10399     if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10400       return ExprError();
10401 
10402     return MaybeBindToTemporary(call);
10403   }
10404 
10405   UnbridgedCastsSet UnbridgedCasts;
10406   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10407     return ExprError();
10408 
10409   MemberExpr *MemExpr;
10410   CXXMethodDecl *Method = 0;
10411   DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
10412   NestedNameSpecifier *Qualifier = 0;
10413   if (isa<MemberExpr>(NakedMemExpr)) {
10414     MemExpr = cast<MemberExpr>(NakedMemExpr);
10415     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
10416     FoundDecl = MemExpr->getFoundDecl();
10417     Qualifier = MemExpr->getQualifier();
10418     UnbridgedCasts.restore();
10419   } else {
10420     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
10421     Qualifier = UnresExpr->getQualifier();
10422 
10423     QualType ObjectType = UnresExpr->getBaseType();
10424     Expr::Classification ObjectClassification
10425       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10426                             : UnresExpr->getBase()->Classify(Context);
10427 
10428     // Add overload candidates
10429     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
10430 
10431     // FIXME: avoid copy.
10432     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10433     if (UnresExpr->hasExplicitTemplateArgs()) {
10434       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10435       TemplateArgs = &TemplateArgsBuffer;
10436     }
10437 
10438     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10439            E = UnresExpr->decls_end(); I != E; ++I) {
10440 
10441       NamedDecl *Func = *I;
10442       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10443       if (isa<UsingShadowDecl>(Func))
10444         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10445 
10446 
10447       // Microsoft supports direct constructor calls.
10448       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
10449         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10450                              llvm::makeArrayRef(Args, NumArgs), CandidateSet);
10451       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
10452         // If explicit template arguments were provided, we can't call a
10453         // non-template member function.
10454         if (TemplateArgs)
10455           continue;
10456 
10457         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
10458                            ObjectClassification,
10459                            llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10460                            /*SuppressUserConversions=*/false);
10461       } else {
10462         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
10463                                    I.getPair(), ActingDC, TemplateArgs,
10464                                    ObjectType,  ObjectClassification,
10465                                    llvm::makeArrayRef(Args, NumArgs),
10466                                    CandidateSet,
10467                                    /*SuppressUsedConversions=*/false);
10468       }
10469     }
10470 
10471     DeclarationName DeclName = UnresExpr->getMemberName();
10472 
10473     UnbridgedCasts.restore();
10474 
10475     OverloadCandidateSet::iterator Best;
10476     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
10477                                             Best)) {
10478     case OR_Success:
10479       Method = cast<CXXMethodDecl>(Best->Function);
10480       MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
10481       FoundDecl = Best->FoundDecl;
10482       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
10483       DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
10484       break;
10485 
10486     case OR_No_Viable_Function:
10487       Diag(UnresExpr->getMemberLoc(),
10488            diag::err_ovl_no_viable_member_function_in_call)
10489         << DeclName << MemExprE->getSourceRange();
10490       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10491                                   llvm::makeArrayRef(Args, NumArgs));
10492       // FIXME: Leaking incoming expressions!
10493       return ExprError();
10494 
10495     case OR_Ambiguous:
10496       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
10497         << DeclName << MemExprE->getSourceRange();
10498       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10499                                   llvm::makeArrayRef(Args, NumArgs));
10500       // FIXME: Leaking incoming expressions!
10501       return ExprError();
10502 
10503     case OR_Deleted:
10504       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
10505         << Best->Function->isDeleted()
10506         << DeclName
10507         << getDeletedOrUnavailableSuffix(Best->Function)
10508         << MemExprE->getSourceRange();
10509       CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10510                                   llvm::makeArrayRef(Args, NumArgs));
10511       // FIXME: Leaking incoming expressions!
10512       return ExprError();
10513     }
10514 
10515     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
10516 
10517     // If overload resolution picked a static member, build a
10518     // non-member call based on that function.
10519     if (Method->isStatic()) {
10520       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10521                                    Args, NumArgs, RParenLoc);
10522     }
10523 
10524     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
10525   }
10526 
10527   QualType ResultType = Method->getResultType();
10528   ExprValueKind VK = Expr::getValueKindForType(ResultType);
10529   ResultType = ResultType.getNonLValueExprType(Context);
10530 
10531   assert(Method && "Member call to something that isn't a method?");
10532   CXXMemberCallExpr *TheCall =
10533     new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10534                                     ResultType, VK, RParenLoc);
10535 
10536   // Check for a valid return type.
10537   if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
10538                           TheCall, Method))
10539     return ExprError();
10540 
10541   // Convert the object argument (for a non-static member function call).
10542   // We only need to do this if there was actually an overload; otherwise
10543   // it was done at lookup.
10544   if (!Method->isStatic()) {
10545     ExprResult ObjectArg =
10546       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10547                                           FoundDecl, Method);
10548     if (ObjectArg.isInvalid())
10549       return ExprError();
10550     MemExpr->setBase(ObjectArg.take());
10551   }
10552 
10553   // Convert the rest of the arguments
10554   const FunctionProtoType *Proto =
10555     Method->getType()->getAs<FunctionProtoType>();
10556   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
10557                               RParenLoc))
10558     return ExprError();
10559 
10560   DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10561 
10562   if (CheckFunctionCall(Method, TheCall))
10563     return ExprError();
10564 
10565   if ((isa<CXXConstructorDecl>(CurContext) ||
10566        isa<CXXDestructorDecl>(CurContext)) &&
10567       TheCall->getMethodDecl()->isPure()) {
10568     const CXXMethodDecl *MD = TheCall->getMethodDecl();
10569 
10570     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
10571       Diag(MemExpr->getLocStart(),
10572            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10573         << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10574         << MD->getParent()->getDeclName();
10575 
10576       Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
10577     }
10578   }
10579   return MaybeBindToTemporary(TheCall);
10580 }
10581 
10582 /// BuildCallToObjectOfClassType - Build a call to an object of class
10583 /// type (C++ [over.call.object]), which can end up invoking an
10584 /// overloaded function call operator (@c operator()) or performing a
10585 /// user-defined conversion on the object argument.
10586 ExprResult
BuildCallToObjectOfClassType(Scope * S,Expr * Obj,SourceLocation LParenLoc,Expr ** Args,unsigned NumArgs,SourceLocation RParenLoc)10587 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
10588                                    SourceLocation LParenLoc,
10589                                    Expr **Args, unsigned NumArgs,
10590                                    SourceLocation RParenLoc) {
10591   if (checkPlaceholderForOverload(*this, Obj))
10592     return ExprError();
10593   ExprResult Object = Owned(Obj);
10594 
10595   UnbridgedCastsSet UnbridgedCasts;
10596   if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10597     return ExprError();
10598 
10599   assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10600   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
10601 
10602   // C++ [over.call.object]p1:
10603   //  If the primary-expression E in the function call syntax
10604   //  evaluates to a class object of type "cv T", then the set of
10605   //  candidate functions includes at least the function call
10606   //  operators of T. The function call operators of T are obtained by
10607   //  ordinary lookup of the name operator() in the context of
10608   //  (E).operator().
10609   OverloadCandidateSet CandidateSet(LParenLoc);
10610   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
10611 
10612   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
10613                           PDiag(diag::err_incomplete_object_call)
10614                           << Object.get()->getSourceRange()))
10615     return true;
10616 
10617   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10618   LookupQualifiedName(R, Record->getDecl());
10619   R.suppressDiagnostics();
10620 
10621   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10622        Oper != OperEnd; ++Oper) {
10623     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10624                        Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
10625                        /*SuppressUserConversions=*/ false);
10626   }
10627 
10628   // C++ [over.call.object]p2:
10629   //   In addition, for each (non-explicit in C++0x) conversion function
10630   //   declared in T of the form
10631   //
10632   //        operator conversion-type-id () cv-qualifier;
10633   //
10634   //   where cv-qualifier is the same cv-qualification as, or a
10635   //   greater cv-qualification than, cv, and where conversion-type-id
10636   //   denotes the type "pointer to function of (P1,...,Pn) returning
10637   //   R", or the type "reference to pointer to function of
10638   //   (P1,...,Pn) returning R", or the type "reference to function
10639   //   of (P1,...,Pn) returning R", a surrogate call function [...]
10640   //   is also considered as a candidate function. Similarly,
10641   //   surrogate call functions are added to the set of candidate
10642   //   functions for each conversion function declared in an
10643   //   accessible base class provided the function is not hidden
10644   //   within T by another intervening declaration.
10645   const UnresolvedSetImpl *Conversions
10646     = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
10647   for (UnresolvedSetImpl::iterator I = Conversions->begin(),
10648          E = Conversions->end(); I != E; ++I) {
10649     NamedDecl *D = *I;
10650     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10651     if (isa<UsingShadowDecl>(D))
10652       D = cast<UsingShadowDecl>(D)->getTargetDecl();
10653 
10654     // Skip over templated conversion functions; they aren't
10655     // surrogates.
10656     if (isa<FunctionTemplateDecl>(D))
10657       continue;
10658 
10659     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
10660     if (!Conv->isExplicit()) {
10661       // Strip the reference type (if any) and then the pointer type (if
10662       // any) to get down to what might be a function type.
10663       QualType ConvType = Conv->getConversionType().getNonReferenceType();
10664       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10665         ConvType = ConvPtrType->getPointeeType();
10666 
10667       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10668       {
10669         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
10670                               Object.get(), llvm::makeArrayRef(Args, NumArgs),
10671                               CandidateSet);
10672       }
10673     }
10674   }
10675 
10676   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10677 
10678   // Perform overload resolution.
10679   OverloadCandidateSet::iterator Best;
10680   switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
10681                              Best)) {
10682   case OR_Success:
10683     // Overload resolution succeeded; we'll build the appropriate call
10684     // below.
10685     break;
10686 
10687   case OR_No_Viable_Function:
10688     if (CandidateSet.empty())
10689       Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
10690         << Object.get()->getType() << /*call*/ 1
10691         << Object.get()->getSourceRange();
10692     else
10693       Diag(Object.get()->getLocStart(),
10694            diag::err_ovl_no_viable_object_call)
10695         << Object.get()->getType() << Object.get()->getSourceRange();
10696     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10697                                 llvm::makeArrayRef(Args, NumArgs));
10698     break;
10699 
10700   case OR_Ambiguous:
10701     Diag(Object.get()->getLocStart(),
10702          diag::err_ovl_ambiguous_object_call)
10703       << Object.get()->getType() << Object.get()->getSourceRange();
10704     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10705                                 llvm::makeArrayRef(Args, NumArgs));
10706     break;
10707 
10708   case OR_Deleted:
10709     Diag(Object.get()->getLocStart(),
10710          diag::err_ovl_deleted_object_call)
10711       << Best->Function->isDeleted()
10712       << Object.get()->getType()
10713       << getDeletedOrUnavailableSuffix(Best->Function)
10714       << Object.get()->getSourceRange();
10715     CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10716                                 llvm::makeArrayRef(Args, NumArgs));
10717     break;
10718   }
10719 
10720   if (Best == CandidateSet.end())
10721     return true;
10722 
10723   UnbridgedCasts.restore();
10724 
10725   if (Best->Function == 0) {
10726     // Since there is no function declaration, this is one of the
10727     // surrogate candidates. Dig out the conversion function.
10728     CXXConversionDecl *Conv
10729       = cast<CXXConversionDecl>(
10730                          Best->Conversions[0].UserDefined.ConversionFunction);
10731 
10732     CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10733     DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10734 
10735     // We selected one of the surrogate functions that converts the
10736     // object parameter to a function pointer. Perform the conversion
10737     // on the object argument, then let ActOnCallExpr finish the job.
10738 
10739     // Create an implicit member expr to refer to the conversion operator.
10740     // and then call it.
10741     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10742                                              Conv, HadMultipleCandidates);
10743     if (Call.isInvalid())
10744       return ExprError();
10745     // Record usage of conversion in an implicit cast.
10746     Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10747                                           CK_UserDefinedConversion,
10748                                           Call.get(), 0, VK_RValue));
10749 
10750     return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
10751                          RParenLoc);
10752   }
10753 
10754   MarkFunctionReferenced(LParenLoc, Best->Function);
10755   CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
10756   DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
10757 
10758   // We found an overloaded operator(). Build a CXXOperatorCallExpr
10759   // that calls this method, using Object for the implicit object
10760   // parameter and passing along the remaining arguments.
10761   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10762   const FunctionProtoType *Proto =
10763     Method->getType()->getAs<FunctionProtoType>();
10764 
10765   unsigned NumArgsInProto = Proto->getNumArgs();
10766   unsigned NumArgsToCheck = NumArgs;
10767 
10768   // Build the full argument list for the method call (the
10769   // implicit object parameter is placed at the beginning of the
10770   // list).
10771   Expr **MethodArgs;
10772   if (NumArgs < NumArgsInProto) {
10773     NumArgsToCheck = NumArgsInProto;
10774     MethodArgs = new Expr*[NumArgsInProto + 1];
10775   } else {
10776     MethodArgs = new Expr*[NumArgs + 1];
10777   }
10778   MethodArgs[0] = Object.get();
10779   for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10780     MethodArgs[ArgIdx + 1] = Args[ArgIdx];
10781 
10782   DeclarationNameInfo OpLocInfo(
10783                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10784   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
10785   ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10786                                            HadMultipleCandidates,
10787                                            OpLocInfo.getLoc(),
10788                                            OpLocInfo.getInfo());
10789   if (NewFn.isInvalid())
10790     return true;
10791 
10792   // Once we've built TheCall, all of the expressions are properly
10793   // owned.
10794   QualType ResultTy = Method->getResultType();
10795   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10796   ResultTy = ResultTy.getNonLValueExprType(Context);
10797 
10798   CXXOperatorCallExpr *TheCall =
10799     new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
10800                                       MethodArgs, NumArgs + 1,
10801                                       ResultTy, VK, RParenLoc);
10802   delete [] MethodArgs;
10803 
10804   if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
10805                           Method))
10806     return true;
10807 
10808   // We may have default arguments. If so, we need to allocate more
10809   // slots in the call for them.
10810   if (NumArgs < NumArgsInProto)
10811     TheCall->setNumArgs(Context, NumArgsInProto + 1);
10812   else if (NumArgs > NumArgsInProto)
10813     NumArgsToCheck = NumArgsInProto;
10814 
10815   bool IsError = false;
10816 
10817   // Initialize the implicit object parameter.
10818   ExprResult ObjRes =
10819     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10820                                         Best->FoundDecl, Method);
10821   if (ObjRes.isInvalid())
10822     IsError = true;
10823   else
10824     Object = move(ObjRes);
10825   TheCall->setArg(0, Object.take());
10826 
10827   // Check the argument types.
10828   for (unsigned i = 0; i != NumArgsToCheck; i++) {
10829     Expr *Arg;
10830     if (i < NumArgs) {
10831       Arg = Args[i];
10832 
10833       // Pass the argument.
10834 
10835       ExprResult InputInit
10836         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10837                                                     Context,
10838                                                     Method->getParamDecl(i)),
10839                                     SourceLocation(), Arg);
10840 
10841       IsError |= InputInit.isInvalid();
10842       Arg = InputInit.takeAs<Expr>();
10843     } else {
10844       ExprResult DefArg
10845         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10846       if (DefArg.isInvalid()) {
10847         IsError = true;
10848         break;
10849       }
10850 
10851       Arg = DefArg.takeAs<Expr>();
10852     }
10853 
10854     TheCall->setArg(i + 1, Arg);
10855   }
10856 
10857   // If this is a variadic call, handle args passed through "...".
10858   if (Proto->isVariadic()) {
10859     // Promote the arguments (C99 6.5.2.2p7).
10860     for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
10861       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10862       IsError |= Arg.isInvalid();
10863       TheCall->setArg(i + 1, Arg.take());
10864     }
10865   }
10866 
10867   if (IsError) return true;
10868 
10869   DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10870 
10871   if (CheckFunctionCall(Method, TheCall))
10872     return true;
10873 
10874   return MaybeBindToTemporary(TheCall);
10875 }
10876 
10877 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
10878 ///  (if one exists), where @c Base is an expression of class type and
10879 /// @c Member is the name of the member we're trying to find.
10880 ExprResult
BuildOverloadedArrowExpr(Scope * S,Expr * Base,SourceLocation OpLoc)10881 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
10882   assert(Base->getType()->isRecordType() &&
10883          "left-hand side must have class type");
10884 
10885   if (checkPlaceholderForOverload(*this, Base))
10886     return ExprError();
10887 
10888   SourceLocation Loc = Base->getExprLoc();
10889 
10890   // C++ [over.ref]p1:
10891   //
10892   //   [...] An expression x->m is interpreted as (x.operator->())->m
10893   //   for a class object x of type T if T::operator->() exists and if
10894   //   the operator is selected as the best match function by the
10895   //   overload resolution mechanism (13.3).
10896   DeclarationName OpName =
10897     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
10898   OverloadCandidateSet CandidateSet(Loc);
10899   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
10900 
10901   if (RequireCompleteType(Loc, Base->getType(),
10902                           PDiag(diag::err_typecheck_incomplete_tag)
10903                             << Base->getSourceRange()))
10904     return ExprError();
10905 
10906   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10907   LookupQualifiedName(R, BaseRecord->getDecl());
10908   R.suppressDiagnostics();
10909 
10910   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
10911        Oper != OperEnd; ++Oper) {
10912     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10913                        0, 0, CandidateSet, /*SuppressUserConversions=*/false);
10914   }
10915 
10916   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10917 
10918   // Perform overload resolution.
10919   OverloadCandidateSet::iterator Best;
10920   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10921   case OR_Success:
10922     // Overload resolution succeeded; we'll build the call below.
10923     break;
10924 
10925   case OR_No_Viable_Function:
10926     if (CandidateSet.empty())
10927       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
10928         << Base->getType() << Base->getSourceRange();
10929     else
10930       Diag(OpLoc, diag::err_ovl_no_viable_oper)
10931         << "operator->" << Base->getSourceRange();
10932     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
10933     return ExprError();
10934 
10935   case OR_Ambiguous:
10936     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
10937       << "->" << Base->getType() << Base->getSourceRange();
10938     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
10939     return ExprError();
10940 
10941   case OR_Deleted:
10942     Diag(OpLoc,  diag::err_ovl_deleted_oper)
10943       << Best->Function->isDeleted()
10944       << "->"
10945       << getDeletedOrUnavailableSuffix(Best->Function)
10946       << Base->getSourceRange();
10947     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
10948     return ExprError();
10949   }
10950 
10951   MarkFunctionReferenced(OpLoc, Best->Function);
10952   CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
10953   DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10954 
10955   // Convert the object parameter.
10956   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10957   ExprResult BaseResult =
10958     PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10959                                         Best->FoundDecl, Method);
10960   if (BaseResult.isInvalid())
10961     return ExprError();
10962   Base = BaseResult.take();
10963 
10964   // Build the operator call.
10965   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10966                                             HadMultipleCandidates, OpLoc);
10967   if (FnExpr.isInvalid())
10968     return ExprError();
10969 
10970   QualType ResultTy = Method->getResultType();
10971   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10972   ResultTy = ResultTy.getNonLValueExprType(Context);
10973   CXXOperatorCallExpr *TheCall =
10974     new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
10975                                       &Base, 1, ResultTy, VK, OpLoc);
10976 
10977   if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
10978                           Method))
10979           return ExprError();
10980 
10981   return MaybeBindToTemporary(TheCall);
10982 }
10983 
10984 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
10985 /// a literal operator described by the provided lookup results.
BuildLiteralOperatorCall(LookupResult & R,DeclarationNameInfo & SuffixInfo,ArrayRef<Expr * > Args,SourceLocation LitEndLoc,TemplateArgumentListInfo * TemplateArgs)10986 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
10987                                           DeclarationNameInfo &SuffixInfo,
10988                                           ArrayRef<Expr*> Args,
10989                                           SourceLocation LitEndLoc,
10990                                        TemplateArgumentListInfo *TemplateArgs) {
10991   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
10992 
10993   OverloadCandidateSet CandidateSet(UDSuffixLoc);
10994   AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
10995                         TemplateArgs);
10996 
10997   bool HadMultipleCandidates = (CandidateSet.size() > 1);
10998 
10999   // Perform overload resolution. This will usually be trivial, but might need
11000   // to perform substitutions for a literal operator template.
11001   OverloadCandidateSet::iterator Best;
11002   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11003   case OR_Success:
11004   case OR_Deleted:
11005     break;
11006 
11007   case OR_No_Viable_Function:
11008     Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11009       << R.getLookupName();
11010     CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11011     return ExprError();
11012 
11013   case OR_Ambiguous:
11014     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11015     CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11016     return ExprError();
11017   }
11018 
11019   FunctionDecl *FD = Best->Function;
11020   MarkFunctionReferenced(UDSuffixLoc, FD);
11021   DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
11022 
11023   ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11024                                         SuffixInfo.getLoc(),
11025                                         SuffixInfo.getInfo());
11026   if (Fn.isInvalid())
11027     return true;
11028 
11029   // Check the argument types. This should almost always be a no-op, except
11030   // that array-to-pointer decay is applied to string literals.
11031   Expr *ConvArgs[2];
11032   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11033     ExprResult InputInit = PerformCopyInitialization(
11034       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11035       SourceLocation(), Args[ArgIdx]);
11036     if (InputInit.isInvalid())
11037       return true;
11038     ConvArgs[ArgIdx] = InputInit.take();
11039   }
11040 
11041   QualType ResultTy = FD->getResultType();
11042   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11043   ResultTy = ResultTy.getNonLValueExprType(Context);
11044 
11045   UserDefinedLiteral *UDL =
11046     new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11047                                      ResultTy, VK, LitEndLoc, UDSuffixLoc);
11048 
11049   if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11050     return ExprError();
11051 
11052   if (CheckFunctionCall(FD, UDL))
11053     return ExprError();
11054 
11055   return MaybeBindToTemporary(UDL);
11056 }
11057 
11058 /// FixOverloadedFunctionReference - E is an expression that refers to
11059 /// a C++ overloaded function (possibly with some parentheses and
11060 /// perhaps a '&' around it). We have resolved the overloaded function
11061 /// to the function declaration Fn, so patch up the expression E to
11062 /// refer (possibly indirectly) to Fn. Returns the new expr.
FixOverloadedFunctionReference(Expr * E,DeclAccessPair Found,FunctionDecl * Fn)11063 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
11064                                            FunctionDecl *Fn) {
11065   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
11066     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11067                                                    Found, Fn);
11068     if (SubExpr == PE->getSubExpr())
11069       return PE;
11070 
11071     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
11072   }
11073 
11074   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11075     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11076                                                    Found, Fn);
11077     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
11078                                SubExpr->getType()) &&
11079            "Implicit cast type cannot be determined from overload");
11080     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
11081     if (SubExpr == ICE->getSubExpr())
11082       return ICE;
11083 
11084     return ImplicitCastExpr::Create(Context, ICE->getType(),
11085                                     ICE->getCastKind(),
11086                                     SubExpr, 0,
11087                                     ICE->getValueKind());
11088   }
11089 
11090   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
11091     assert(UnOp->getOpcode() == UO_AddrOf &&
11092            "Can only take the address of an overloaded function");
11093     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11094       if (Method->isStatic()) {
11095         // Do nothing: static member functions aren't any different
11096         // from non-member functions.
11097       } else {
11098         // Fix the sub expression, which really has to be an
11099         // UnresolvedLookupExpr holding an overloaded member function
11100         // or template.
11101         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11102                                                        Found, Fn);
11103         if (SubExpr == UnOp->getSubExpr())
11104           return UnOp;
11105 
11106         assert(isa<DeclRefExpr>(SubExpr)
11107                && "fixed to something other than a decl ref");
11108         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11109                && "fixed to a member ref with no nested name qualifier");
11110 
11111         // We have taken the address of a pointer to member
11112         // function. Perform the computation here so that we get the
11113         // appropriate pointer to member type.
11114         QualType ClassType
11115           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11116         QualType MemPtrType
11117           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11118 
11119         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11120                                            VK_RValue, OK_Ordinary,
11121                                            UnOp->getOperatorLoc());
11122       }
11123     }
11124     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11125                                                    Found, Fn);
11126     if (SubExpr == UnOp->getSubExpr())
11127       return UnOp;
11128 
11129     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
11130                                      Context.getPointerType(SubExpr->getType()),
11131                                        VK_RValue, OK_Ordinary,
11132                                        UnOp->getOperatorLoc());
11133   }
11134 
11135   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11136     // FIXME: avoid copy.
11137     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11138     if (ULE->hasExplicitTemplateArgs()) {
11139       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11140       TemplateArgs = &TemplateArgsBuffer;
11141     }
11142 
11143     DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11144                                            ULE->getQualifierLoc(),
11145                                            ULE->getTemplateKeywordLoc(),
11146                                            Fn,
11147                                            /*enclosing*/ false, // FIXME?
11148                                            ULE->getNameLoc(),
11149                                            Fn->getType(),
11150                                            VK_LValue,
11151                                            Found.getDecl(),
11152                                            TemplateArgs);
11153     MarkDeclRefReferenced(DRE);
11154     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11155     return DRE;
11156   }
11157 
11158   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
11159     // FIXME: avoid copy.
11160     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11161     if (MemExpr->hasExplicitTemplateArgs()) {
11162       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11163       TemplateArgs = &TemplateArgsBuffer;
11164     }
11165 
11166     Expr *Base;
11167 
11168     // If we're filling in a static method where we used to have an
11169     // implicit member access, rewrite to a simple decl ref.
11170     if (MemExpr->isImplicitAccess()) {
11171       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11172         DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11173                                                MemExpr->getQualifierLoc(),
11174                                                MemExpr->getTemplateKeywordLoc(),
11175                                                Fn,
11176                                                /*enclosing*/ false,
11177                                                MemExpr->getMemberLoc(),
11178                                                Fn->getType(),
11179                                                VK_LValue,
11180                                                Found.getDecl(),
11181                                                TemplateArgs);
11182         MarkDeclRefReferenced(DRE);
11183         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11184         return DRE;
11185       } else {
11186         SourceLocation Loc = MemExpr->getMemberLoc();
11187         if (MemExpr->getQualifier())
11188           Loc = MemExpr->getQualifierLoc().getBeginLoc();
11189         CheckCXXThisCapture(Loc);
11190         Base = new (Context) CXXThisExpr(Loc,
11191                                          MemExpr->getBaseType(),
11192                                          /*isImplicit=*/true);
11193       }
11194     } else
11195       Base = MemExpr->getBase();
11196 
11197     ExprValueKind valueKind;
11198     QualType type;
11199     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11200       valueKind = VK_LValue;
11201       type = Fn->getType();
11202     } else {
11203       valueKind = VK_RValue;
11204       type = Context.BoundMemberTy;
11205     }
11206 
11207     MemberExpr *ME = MemberExpr::Create(Context, Base,
11208                                         MemExpr->isArrow(),
11209                                         MemExpr->getQualifierLoc(),
11210                                         MemExpr->getTemplateKeywordLoc(),
11211                                         Fn,
11212                                         Found,
11213                                         MemExpr->getMemberNameInfo(),
11214                                         TemplateArgs,
11215                                         type, valueKind, OK_Ordinary);
11216     ME->setHadMultipleCandidates(true);
11217     return ME;
11218   }
11219 
11220   llvm_unreachable("Invalid reference to overloaded function");
11221 }
11222 
FixOverloadedFunctionReference(ExprResult E,DeclAccessPair Found,FunctionDecl * Fn)11223 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
11224                                                 DeclAccessPair Found,
11225                                                 FunctionDecl *Fn) {
11226   return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
11227 }
11228 
11229 } // end namespace clang
11230